Search in sources :

Example 21 with WebBeansContext

use of org.apache.webbeans.config.WebBeansContext in project tomee by apache.

the class RESTService method afterApplicationCreated.

public void afterApplicationCreated(final AppInfo appInfo, final WebAppInfo webApp) {
    final WebContext webContext = containerSystem.getWebContextByHost(webApp.moduleId, webApp.host != null ? webApp.host : virtualHost);
    if (webContext == null) {
        return;
    }
    if (!deployedWebApps.add(webApp)) {
        return;
    }
    final Map<String, EJBRestServiceInfo> restEjbs = getRestEjbs(appInfo, webApp.moduleId);
    final ClassLoader classLoader = getClassLoader(webContext.getClassLoader());
    final Collection<Injection> injections = webContext.getInjections();
    final WebBeansContext owbCtx;
    if (webContext.getWebbeansContext() != null) {
        owbCtx = webContext.getWebbeansContext();
    } else {
        owbCtx = webContext.getAppContext().getWebBeansContext();
    }
    Context context = webContext.getJndiEnc();
    if (context == null) {
        // usually true since it is set in org.apache.tomee.catalina.TomcatWebAppBuilder.afterStart() and lookup(comp) fails
        context = webContext.getAppContext().getAppJndiContext();
    }
    final ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(classLoader);
    final Collection<Object> additionalProviders = new HashSet<>();
    addAppProvidersIfNeeded(appInfo, webApp, classLoader, additionalProviders);
    // done lazily
    Collection<IdPropertiesInfo> pojoConfigurations = null;
    try {
        boolean deploymentWithApplication = "true".equalsIgnoreCase(appInfo.properties.getProperty(OPENEJB_USE_APPLICATION_PROPERTY, APPLICATION_DEPLOYMENT));
        if (deploymentWithApplication) {
            Class<?> appClazz;
            for (final String app : webApp.restApplications) {
                Application application;
                boolean appSkipped = false;
                String prefix = "/";
                try {
                    appClazz = classLoader.loadClass(app);
                    application = Application.class.cast(appClazz.newInstance());
                    if (owbCtx != null && owbCtx.getBeanManagerImpl().isInUse()) {
                        try {
                            webContext.inject(application);
                        } catch (final Exception e) {
                        // not important since not required by the spec
                        }
                    }
                } catch (final Exception e) {
                    throw new OpenEJBRestRuntimeException("can't create class " + app, e);
                }
                application = "true".equalsIgnoreCase(appInfo.properties.getProperty("openejb.cxf-rs.cache-application", "true")) ? new InternalApplication(application) : /* caches singletons and classes */
                application;
                final Set<Class<?>> classes = new HashSet<>(application.getClasses());
                final Set<Object> singletons = application.getSingletons();
                if (classes.size() + singletons.size() == 0) {
                    appSkipped = true;
                } else {
                    for (final Class<?> clazz : classes) {
                        if (isProvider(clazz)) {
                            additionalProviders.add(clazz);
                        } else if (!hasEjbAndIsNotAManagedBean(restEjbs, clazz.getName())) {
                            pojoConfigurations = PojoUtil.findPojoConfig(pojoConfigurations, appInfo, webApp);
                            if (PojoUtil.findConfiguration(pojoConfigurations, clazz.getName()) != null) {
                                deploymentWithApplication = false;
                                logOldDeploymentUsage(clazz.getName());
                            }
                        }
                    }
                    if (deploymentWithApplication) {
                        // don't do it if we detected we should use old deployment
                        for (final Object o : singletons) {
                            final Class<?> clazz = o.getClass();
                            if (isProvider(clazz)) {
                                additionalProviders.add(o);
                            } else if (!hasEjbAndIsNotAManagedBean(restEjbs, clazz.getName())) {
                                pojoConfigurations = PojoUtil.findPojoConfig(pojoConfigurations, appInfo, webApp);
                                if (PojoUtil.findConfiguration(pojoConfigurations, clazz.getName()) != null) {
                                    deploymentWithApplication = false;
                                    logOldDeploymentUsage(clazz.getName());
                                }
                            }
                        }
                    }
                }
                if (deploymentWithApplication) {
                    // don't do it if we detected we should use old deployment
                    final String path = appPrefix(webApp, appClazz);
                    if (path != null) {
                        prefix += path + wildcard;
                    } else {
                        prefix += wildcard;
                    }
                }
                if (deploymentWithApplication) {
                    // don't do it if we detected we should use old deployment
                    if (appSkipped || application == null) {
                        application = !InternalApplication.class.isInstance(application) ? new InternalApplication(application) : application;
                        for (final String clazz : webApp.restClass) {
                            try {
                                final Class<?> loaded = classLoader.loadClass(clazz);
                                if (!isProvider(loaded)) {
                                    pojoConfigurations = PojoUtil.findPojoConfig(pojoConfigurations, appInfo, webApp);
                                    if (PojoUtil.findConfiguration(pojoConfigurations, loaded.getName()) != null) {
                                        deploymentWithApplication = false;
                                        logOldDeploymentUsage(loaded.getName());
                                        break;
                                    }
                                    application.getClasses().add(loaded);
                                } else {
                                    additionalProviders.add(loaded);
                                }
                            } catch (final Exception e) {
                                throw new OpenEJBRestRuntimeException("can't load class " + clazz, e);
                            }
                        }
                        if (deploymentWithApplication) {
                            addEjbToApplication(application, restEjbs);
                            if (!prefix.endsWith(wildcard)) {
                                prefix += wildcard;
                            }
                        }
                    }
                    if (!application.getClasses().isEmpty() || !application.getSingletons().isEmpty()) {
                        pojoConfigurations = PojoUtil.findPojoConfig(pojoConfigurations, appInfo, webApp);
                        deployApplication(appInfo, webApp.contextRoot, restEjbs, classLoader, injections, owbCtx, context, additionalProviders, pojoConfigurations, application, prefix);
                    }
                }
                if (!deploymentWithApplication) {
                    fullServletDeployment(appInfo, webApp, webContext, restEjbs, classLoader, injections, owbCtx, context, additionalProviders, pojoConfigurations);
                }
            }
            if (webApp.restApplications.isEmpty()) {
                final Application application = new InternalApplication(null);
                for (final String clazz : webApp.restClass) {
                    try {
                        final Class<?> loaded = classLoader.loadClass(clazz);
                        if (!isProvider(loaded)) {
                            pojoConfigurations = PojoUtil.findPojoConfig(pojoConfigurations, appInfo, webApp);
                            if (PojoUtil.findConfiguration(pojoConfigurations, loaded.getName()) != null) {
                                deploymentWithApplication = false;
                                logOldDeploymentUsage(loaded.getName());
                                break;
                            }
                            application.getClasses().add(loaded);
                        } else {
                            additionalProviders.add(loaded);
                        }
                    } catch (final Exception e) {
                        throw new OpenEJBRestRuntimeException("can't load class " + clazz, e);
                    }
                }
                addEjbToApplication(application, restEjbs);
                if (deploymentWithApplication) {
                    if (!application.getClasses().isEmpty() || !application.getSingletons().isEmpty()) {
                        final String path = appPrefix(webApp, application.getClass());
                        final String prefix;
                        if (path != null) {
                            prefix = "/" + path + wildcard;
                        } else {
                            prefix = "/" + wildcard;
                        }
                        pojoConfigurations = PojoUtil.findPojoConfig(pojoConfigurations, appInfo, webApp);
                        deployApplication(appInfo, webApp.contextRoot, restEjbs, classLoader, injections, owbCtx, context, additionalProviders, pojoConfigurations, application, prefix);
                    }
                } else {
                    fullServletDeployment(appInfo, webApp, webContext, restEjbs, classLoader, injections, owbCtx, context, additionalProviders, pojoConfigurations);
                }
            }
        } else {
            fullServletDeployment(appInfo, webApp, webContext, restEjbs, classLoader, injections, owbCtx, context, additionalProviders, pojoConfigurations);
        }
    } finally {
        Thread.currentThread().setContextClassLoader(oldLoader);
    }
}
Also used : WebContext(org.apache.openejb.core.WebContext) WebBeansContext(org.apache.webbeans.config.WebBeansContext) AppContext(org.apache.openejb.AppContext) BeanContext(org.apache.openejb.BeanContext) Context(javax.naming.Context) WebContext(org.apache.openejb.core.WebContext) Injection(org.apache.openejb.Injection) URISyntaxException(java.net.URISyntaxException) ServiceException(org.apache.openejb.server.ServiceException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) WebBeansContext(org.apache.webbeans.config.WebBeansContext) IdPropertiesInfo(org.apache.openejb.assembler.classic.IdPropertiesInfo) MetaAnnotatedClass(org.apache.xbean.finder.MetaAnnotatedClass) Application(javax.ws.rs.core.Application) HashSet(java.util.HashSet)

Example 22 with WebBeansContext

use of org.apache.webbeans.config.WebBeansContext in project tomee by apache.

the class Assembler method destroyApplication.

public void destroyApplication(final AppInfo appInfo) throws UndeployException {
    final ReentrantLock l = lock;
    l.lock();
    try {
        deployedApplications.remove(appInfo.path);
        logger.info("destroyApplication.start", appInfo.path);
        final Context globalContext = containerSystem.getJNDIContext();
        final AppContext appContext = containerSystem.getAppContext(appInfo.appId);
        final ClassLoader classLoader = appContext.getClassLoader();
        SystemInstance.get().fireEvent(new AssemblerBeforeApplicationDestroyed(appInfo, appContext));
        //noinspection ConstantConditions
        if (null == appContext) {
            logger.warning("Application id '" + appInfo.appId + "' not found in: " + Arrays.toString(containerSystem.getAppContextKeys()));
            return;
        } else {
            final WebBeansContext webBeansContext = appContext.getWebBeansContext();
            if (webBeansContext != null) {
                final ClassLoader old = Thread.currentThread().getContextClassLoader();
                Thread.currentThread().setContextClassLoader(classLoader);
                try {
                    final ServletContext context = appContext.isStandaloneModule() && appContext.getWebContexts().iterator().hasNext() ? appContext.getWebContexts().iterator().next().getServletContext() : null;
                    webBeansContext.getService(ContainerLifecycle.class).stopApplication(context);
                } finally {
                    Thread.currentThread().setContextClassLoader(old);
                }
            }
            final Map<String, Object> cb = appContext.getBindings();
            for (final Entry<String, Object> value : cb.entrySet()) {
                String path = value.getKey();
                if (path.startsWith("global")) {
                    path = "java:" + path;
                }
                if (!path.startsWith("java:global")) {
                    continue;
                }
                unbind(globalContext, path);
                unbind(globalContext, "openejb/global/" + path.substring("java:".length()));
                unbind(globalContext, path.substring("java:global".length()));
            }
            if (appInfo.appId != null && !appInfo.appId.isEmpty() && !"openejb".equals(appInfo.appId)) {
                unbind(globalContext, "global/" + appInfo.appId);
                unbind(globalContext, appInfo.appId);
            }
        }
        final EjbResolver globalResolver = new EjbResolver(null, EjbResolver.Scope.GLOBAL);
        for (final AppInfo info : deployedApplications.values()) {
            globalResolver.addAll(info.ejbJars);
        }
        SystemInstance.get().setComponent(EjbResolver.class, globalResolver);
        final UndeployException undeployException = new UndeployException(messages.format("destroyApplication.failed", appInfo.path));
        final WebAppBuilder webAppBuilder = SystemInstance.get().getComponent(WebAppBuilder.class);
        if (webAppBuilder != null && !appInfo.webAppAlone) {
            try {
                webAppBuilder.undeployWebApps(appInfo);
            } catch (final Exception e) {
                undeployException.getCauses().add(new Exception("App: " + appInfo.path + ": " + e.getMessage(), e));
            }
        }
        // get all of the ejb deployments
        List<BeanContext> deployments = new ArrayList<BeanContext>();
        for (final EjbJarInfo ejbJarInfo : appInfo.ejbJars) {
            for (final EnterpriseBeanInfo beanInfo : ejbJarInfo.enterpriseBeans) {
                final String deploymentId = beanInfo.ejbDeploymentId;
                final BeanContext beanContext = containerSystem.getBeanContext(deploymentId);
                if (beanContext == null) {
                    undeployException.getCauses().add(new Exception("deployment not found: " + deploymentId));
                } else {
                    deployments.add(beanContext);
                }
            }
        }
        // Just as with startup we need to get things in an
        // order that respects the singleton @DependsOn information
        // Theoreticlly if a Singleton depends on something in its
        // @PostConstruct, it can depend on it in its @PreDestroy.
        // Therefore we want to make sure that if A dependsOn B,
        // that we destroy A first then B so that B will still be
        // usable in the @PreDestroy method of A.
        // Sort them into the original starting order
        deployments = sort(deployments);
        // reverse that to get the stopping order
        Collections.reverse(deployments);
        // stop
        for (final BeanContext deployment : deployments) {
            final String deploymentID = String.valueOf(deployment.getDeploymentID());
            try {
                final Container container = deployment.getContainer();
                container.stop(deployment);
            } catch (final Throwable t) {
                undeployException.getCauses().add(new Exception("bean: " + deploymentID + ": " + t.getMessage(), t));
            }
        }
        // undeploy
        for (final BeanContext bean : deployments) {
            final String deploymentID = String.valueOf(bean.getDeploymentID());
            try {
                final Container container = bean.getContainer();
                container.undeploy(bean);
                bean.setContainer(null);
            } catch (final Throwable t) {
                undeployException.getCauses().add(new Exception("bean: " + deploymentID + ": " + t.getMessage(), t));
            } finally {
                bean.setDestroyed(true);
            }
        }
        if (webAppBuilder != null && appInfo.webAppAlone) {
            // now that EJB are stopped we can undeploy webapps
            try {
                webAppBuilder.undeployWebApps(appInfo);
            } catch (final Exception e) {
                undeployException.getCauses().add(new Exception("App: " + appInfo.path + ": " + e.getMessage(), e));
            }
        }
        // get the client ids
        final List<String> clientIds = new ArrayList<String>();
        for (final ClientInfo clientInfo : appInfo.clients) {
            clientIds.add(clientInfo.moduleId);
            for (final String className : clientInfo.localClients) {
                clientIds.add(className);
            }
            for (final String className : clientInfo.remoteClients) {
                clientIds.add(className);
            }
        }
        for (final WebContext webContext : appContext.getWebContexts()) {
            containerSystem.removeWebContext(webContext);
        }
        TldScanner.forceCompleteClean(classLoader);
        // Clear out naming for all components first
        for (final BeanContext deployment : deployments) {
            final String deploymentID = String.valueOf(deployment.getDeploymentID());
            try {
                containerSystem.removeBeanContext(deployment);
            } catch (final Throwable t) {
                undeployException.getCauses().add(new Exception(deploymentID, t));
            }
            final JndiBuilder.Bindings bindings = deployment.get(JndiBuilder.Bindings.class);
            if (bindings != null) {
                for (final String name : bindings.getBindings()) {
                    try {
                        globalContext.unbind(name);
                    } catch (final Throwable t) {
                        undeployException.getCauses().add(new Exception("bean: " + deploymentID + ": " + t.getMessage(), t));
                    }
                }
            }
        }
        // stop this executor only now since @PreDestroy can trigger some stop events
        final AsynchronousPool pool = appContext.get(AsynchronousPool.class);
        if (pool != null) {
            pool.stop();
        }
        for (final CommonInfoObject jar : listCommonInfoObjectsForAppInfo(appInfo)) {
            try {
                globalContext.unbind(VALIDATOR_FACTORY_NAMING_CONTEXT + jar.uniqueId);
                globalContext.unbind(VALIDATOR_NAMING_CONTEXT + jar.uniqueId);
            } catch (final NamingException e) {
                if (EjbJarInfo.class.isInstance(jar)) {
                    undeployException.getCauses().add(new Exception("validator: " + jar.uniqueId + ": " + e.getMessage(), e));
                }
            // else an error but not that important
            }
        }
        try {
            if (globalContext instanceof IvmContext) {
                final IvmContext ivmContext = (IvmContext) globalContext;
                ivmContext.prune("openejb/Deployment");
                ivmContext.prune("openejb/local");
                ivmContext.prune("openejb/remote");
                ivmContext.prune("openejb/global");
            }
        } catch (final NamingException e) {
            undeployException.getCauses().add(new Exception("Unable to prune openejb/Deployments and openejb/local namespaces, this could cause future deployments to fail.", e));
        }
        deployments.clear();
        for (final String clientId : clientIds) {
            try {
                globalContext.unbind("/openejb/client/" + clientId);
            } catch (final Throwable t) {
                undeployException.getCauses().add(new Exception("client: " + clientId + ": " + t.getMessage(), t));
            }
        }
        // mbeans
        final MBeanServer server = LocalMBeanServer.get();
        for (final Object objectName : appInfo.jmx.values()) {
            try {
                final ObjectName on = new ObjectName((String) objectName);
                if (server.isRegistered(on)) {
                    server.unregisterMBean(on);
                }
                final CreationalContext cc = creationalContextForAppMbeans.remove(on);
                if (cc != null) {
                    cc.release();
                }
            } catch (final InstanceNotFoundException e) {
                logger.warning("can't unregister " + objectName + " because the mbean was not found", e);
            } catch (final MBeanRegistrationException e) {
                logger.warning("can't unregister " + objectName, e);
            } catch (final MalformedObjectNameException mone) {
                logger.warning("can't unregister because the ObjectName is malformed: " + objectName, mone);
            }
        }
        // destroy PUs before resources since the JPA provider can use datasources
        for (final PersistenceUnitInfo unitInfo : appInfo.persistenceUnits) {
            try {
                final Object object = globalContext.lookup(PERSISTENCE_UNIT_NAMING_CONTEXT + unitInfo.id);
                globalContext.unbind(PERSISTENCE_UNIT_NAMING_CONTEXT + unitInfo.id);
                // close EMF so all resources are released
                final ReloadableEntityManagerFactory remf = (ReloadableEntityManagerFactory) object;
                remf.close();
                persistenceClassLoaderHandler.destroy(unitInfo.id);
                remf.unregister();
            } catch (final Throwable t) {
                undeployException.getCauses().add(new Exception("persistence-unit: " + unitInfo.id + ": " + t.getMessage(), t));
            }
        }
        for (final String id : appInfo.resourceAliases) {
            final String name = OPENEJB_RESOURCE_JNDI_PREFIX + id;
            ContextualJndiReference.followReference.set(false);
            try {
                final Object object;
                try {
                    object = globalContext.lookup(name);
                } finally {
                    ContextualJndiReference.followReference.remove();
                }
                if (object instanceof ContextualJndiReference) {
                    final ContextualJndiReference contextualJndiReference = ContextualJndiReference.class.cast(object);
                    contextualJndiReference.removePrefix(appContext.getId());
                    if (contextualJndiReference.hasNoMorePrefix()) {
                        globalContext.unbind(name);
                    }
                // else not the last deployed application to use this resource so keep it
                } else {
                    globalContext.unbind(name);
                }
            } catch (final NamingException e) {
                logger.warning("can't unbind resource '{0}'", id);
            }
        }
        for (final String id : appInfo.resourceIds) {
            final String name = OPENEJB_RESOURCE_JNDI_PREFIX + id;
            try {
                destroyLookedUpResource(globalContext, id, name);
            } catch (final NamingException e) {
                logger.warning("can't unbind resource '{0}'", id);
            }
        }
        for (final ConnectorInfo connector : appInfo.connectors) {
            if (connector.resourceAdapter == null || connector.resourceAdapter.id == null) {
                continue;
            }
            final String name = OPENEJB_RESOURCE_JNDI_PREFIX + connector.resourceAdapter.id;
            try {
                destroyLookedUpResource(globalContext, connector.resourceAdapter.id, name);
            } catch (final NamingException e) {
                logger.warning("can't unbind resource '{0}'", connector);
            }
            for (final ResourceInfo outbound : connector.outbound) {
                try {
                    destroyLookedUpResource(globalContext, outbound.id, OPENEJB_RESOURCE_JNDI_PREFIX + outbound.id);
                } catch (final Exception e) {
                // no-op
                }
            }
            for (final ResourceInfo outbound : connector.adminObject) {
                try {
                    destroyLookedUpResource(globalContext, outbound.id, OPENEJB_RESOURCE_JNDI_PREFIX + outbound.id);
                } catch (final Exception e) {
                // no-op
                }
            }
            for (final MdbContainerInfo container : connector.inbound) {
                try {
                    containerSystem.removeContainer(container.id);
                    config.containerSystem.containers.remove(container);
                    this.containerSystem.getJNDIContext().unbind(JAVA_OPENEJB_NAMING_CONTEXT + container.service + "/" + container.id);
                } catch (final Exception e) {
                // no-op
                }
            }
        }
        for (final String id : appInfo.containerIds) {
            removeContainer(id);
        }
        containerSystem.removeAppContext(appInfo.appId);
        if (!appInfo.properties.containsKey("tomee.destroying")) {
            // destroy tomee classloader after resources cleanup
            try {
                final Method m = classLoader.getClass().getMethod("internalStop");
                m.invoke(classLoader);
            } catch (final NoSuchMethodException nsme) {
            // no-op
            } catch (final Exception e) {
                logger.error("error stopping classloader of webapp " + appInfo.appId, e);
            }
            ClassLoaderUtil.cleanOpenJPACache(classLoader);
        }
        ClassLoaderUtil.destroyClassLoader(appInfo.appId, appInfo.path);
        if (undeployException.getCauses().size() > 0) {
            throw undeployException;
        }
        logger.debug("destroyApplication.success", appInfo.path);
    } finally {
        l.unlock();
    }
}
Also used : WebContext(org.apache.openejb.core.WebContext) IvmContext(org.apache.openejb.core.ivm.naming.IvmContext) ArrayList(java.util.ArrayList) AsynchronousPool(org.apache.openejb.async.AsynchronousPool) JMXContainer(org.apache.openejb.assembler.monitoring.JMXContainer) Container(org.apache.openejb.Container) WebBeansContext(org.apache.webbeans.config.WebBeansContext) ServletContext(javax.servlet.ServletContext) NamingException(javax.naming.NamingException) LocalMBeanServer(org.apache.openejb.monitoring.LocalMBeanServer) MBeanServer(javax.management.MBeanServer) ReentrantLock(java.util.concurrent.locks.ReentrantLock) WebContext(org.apache.openejb.core.WebContext) SimpleBootstrapContext(org.apache.openejb.core.transaction.SimpleBootstrapContext) Context(javax.naming.Context) ServletContext(javax.servlet.ServletContext) MethodContext(org.apache.openejb.MethodContext) IvmContext(org.apache.openejb.core.ivm.naming.IvmContext) AppContext(org.apache.openejb.AppContext) InitialContext(javax.naming.InitialContext) WebBeansContext(org.apache.webbeans.config.WebBeansContext) BeanContext(org.apache.openejb.BeanContext) CreationalContext(javax.enterprise.context.spi.CreationalContext) DeploymentContext(org.apache.openejb.DeploymentContext) GeronimoBootstrapContext(org.apache.geronimo.connector.GeronimoBootstrapContext) BootstrapContext(javax.resource.spi.BootstrapContext) MalformedObjectNameException(javax.management.MalformedObjectNameException) AppContext(org.apache.openejb.AppContext) InstanceNotFoundException(javax.management.InstanceNotFoundException) AssemblerBeforeApplicationDestroyed(org.apache.openejb.assembler.classic.event.AssemblerBeforeApplicationDestroyed) Method(java.lang.reflect.Method) InvalidObjectException(java.io.InvalidObjectException) NameAlreadyBoundException(javax.naming.NameAlreadyBoundException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ObjectStreamException(java.io.ObjectStreamException) ResourceAdapterInternalException(javax.resource.spi.ResourceAdapterInternalException) URISyntaxException(java.net.URISyntaxException) UndeployException(org.apache.openejb.UndeployException) DefinitionException(javax.enterprise.inject.spi.DefinitionException) ConstructionException(org.apache.xbean.recipe.ConstructionException) MBeanRegistrationException(javax.management.MBeanRegistrationException) InstanceNotFoundException(javax.management.InstanceNotFoundException) ValidationException(javax.validation.ValidationException) MalformedObjectNameException(javax.management.MalformedObjectNameException) DuplicateDeploymentIdException(org.apache.openejb.DuplicateDeploymentIdException) TimeoutException(java.util.concurrent.TimeoutException) NamingException(javax.naming.NamingException) OpenEJBException(org.apache.openejb.OpenEJBException) DeploymentException(javax.enterprise.inject.spi.DeploymentException) NoSuchApplicationException(org.apache.openejb.NoSuchApplicationException) MalformedURLException(java.net.MalformedURLException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) ContainerLifecycle(org.apache.webbeans.spi.ContainerLifecycle) ObjectName(javax.management.ObjectName) BeanContext(org.apache.openejb.BeanContext) CreationalContext(javax.enterprise.context.spi.CreationalContext) MBeanRegistrationException(javax.management.MBeanRegistrationException) ContextualJndiReference(org.apache.openejb.core.ivm.naming.ContextualJndiReference) UndeployException(org.apache.openejb.UndeployException)

Example 23 with WebBeansContext

use of org.apache.webbeans.config.WebBeansContext in project tomee by apache.

the class ValidatorBuilder method newInstance.

private static <T> T newInstance(final OpenEjbConfig config, final Class<T> clazz) throws Exception {
    final WebBeansContext webBeansContext = AppFinder.findAppContextOrWeb(Thread.currentThread().getContextClassLoader(), AppFinder.WebBeansContextTransformer.INSTANCE);
    if (webBeansContext == null) {
        return clazz.newInstance();
    }
    final BeanManagerImpl beanManager = webBeansContext.getBeanManagerImpl();
    if (!beanManager.isInUse()) {
        return clazz.newInstance();
    }
    final AnnotatedType<T> annotatedType = beanManager.createAnnotatedType(clazz);
    final InjectionTarget<T> it = beanManager.createInjectionTarget(annotatedType);
    final CreationalContext<T> context = beanManager.createCreationalContext(null);
    final T instance = it.produce(context);
    it.inject(instance, context);
    it.postConstruct(instance);
    config.releasables.add(new Releasable<T>(context, it, instance));
    return instance;
}
Also used : WebBeansContext(org.apache.webbeans.config.WebBeansContext) BeanManagerImpl(org.apache.webbeans.container.BeanManagerImpl)

Example 24 with WebBeansContext

use of org.apache.webbeans.config.WebBeansContext in project tomee by apache.

the class CdiResourceInjectionService method fillInjectionProperties.

@SuppressWarnings("unchecked")
private void fillInjectionProperties(final ObjectRecipe objectRecipe, final Object managedBeanInstance) {
    final boolean usePrefix = true;
    final Class<?> clazz = managedBeanInstance.getClass();
    Collection<BeanContext> comps;
    WebBeansContext webBeansContext = null;
    if (ear) {
        // let it be contextual, ie use webapp context (env-entries...) to create ear libs interceptors...
        try {
            webBeansContext = WebBeansContext.currentInstance();
            comps = CdiResourceInjectionService.class.cast(webBeansContext.getService(ResourceInjectionService.class)).compContexts;
        } catch (final Exception e) {
            comps = compContexts;
        }
    } else {
        comps = compContexts;
    }
    for (final BeanContext beanContext : comps) {
        for (final Injection injection : beanContext.getInjections()) {
            if (injection.getTarget() == null) {
                continue;
            }
            if (!injection.getTarget().isAssignableFrom(clazz)) {
                continue;
            }
            final String prefix;
            if (usePrefix) {
                prefix = injection.getTarget().getName() + "/";
            } else {
                prefix = "";
            }
            try {
                final Object value = lookup(beanContext, injection);
                objectRecipe.setProperty(prefix + injection.getName(), value);
            } catch (final NamingException e) {
                boolean found = false;
                if (webBeansContext != null) {
                    for (final WebContext w : appCtx.getWebContexts()) {
                        if (w.getWebBeansContext() == webBeansContext) {
                            final Object value = w.getBindings().get(injection.getJndiName());
                            if (value != null) {
                                objectRecipe.setProperty(prefix + injection.getName(), value);
                                found = true;
                            }
                            break;
                        }
                    }
                }
                if (!found) {
                    logger.warning("Injection data not found in JNDI context: jndiName='" + injection.getJndiName() + "', target=" + injection.getTarget().getName() + "/" + injection.getName());
                }
            }
        }
    }
}
Also used : BeanContext(org.apache.openejb.BeanContext) WebBeansContext(org.apache.webbeans.config.WebBeansContext) WebContext(org.apache.openejb.core.WebContext) NamingException(javax.naming.NamingException) Injection(org.apache.openejb.Injection) ResourceInjectionService(org.apache.webbeans.spi.ResourceInjectionService) NamingException(javax.naming.NamingException) IOException(java.io.IOException)

Example 25 with WebBeansContext

use of org.apache.webbeans.config.WebBeansContext in project tomee by apache.

the class CdiScanner method init.

@Override
public void init(final Object object) {
    if (!StartupObject.class.isInstance(object)) {
        return;
    }
    containerLoader = ParentClassLoaderFinder.Helper.get();
    final StartupObject startupObject = StartupObject.class.cast(object);
    final AppInfo appInfo = startupObject.getAppInfo();
    final ClassLoader classLoader = startupObject.getClassLoader();
    final ClassLoaderComparator comparator;
    if (classLoader instanceof ClassLoaderComparator) {
        comparator = (ClassLoaderComparator) classLoader;
    } else {
        comparator = new DefaultClassLoaderComparator(classLoader);
    }
    final WebBeansContext webBeansContext = startupObject.getWebBeansContext();
    final InterceptorsManager interceptorsManager = webBeansContext.getInterceptorsManager();
    // app beans
    for (final EjbJarInfo ejbJar : appInfo.ejbJars) {
        final BeansInfo beans = ejbJar.beans;
        if (beans == null || "false".equalsIgnoreCase(ejbJar.properties.getProperty("openejb.cdi.activated"))) {
            continue;
        }
        if (startupObject.isFromWebApp()) {
            // deploy only the related ejbmodule
            if (!ejbJar.moduleId.equals(startupObject.getWebContext().getId())) {
                continue;
            }
        } else if (ejbJar.webapp && !appInfo.webAppAlone) {
            continue;
        }
        if (appInfo.webAppAlone || !ejbJar.webapp) {
            // "manual" extension to avoid to add it through SPI mecanism
            classes.addAll(asList(TRANSACTIONAL_INTERCEPTORS));
            for (final Class<?> interceptor : TRANSACTIONAL_INTERCEPTORS) {
                interceptorsManager.addEnabledInterceptorClass(interceptor);
            }
        }
        // here for ears we need to skip classes in the parent classloader
        final ClassLoader scl = ClassLoader.getSystemClassLoader();
        final boolean filterByClassLoader = "true".equals(ejbJar.properties.getProperty(OPENEJB_CDI_FILTER_CLASSLOADER, SystemInstance.get().getProperty(OPENEJB_CDI_FILTER_CLASSLOADER, "true")));
        final BeanArchiveService beanArchiveService = webBeansContext.getBeanArchiveService();
        final boolean openejb = OpenEJBBeanInfoService.class.isInstance(beanArchiveService);
        final Map<BeansInfo.BDAInfo, BeanArchiveService.BeanArchiveInformation> infoByBda = new HashMap<>();
        for (final BeansInfo.BDAInfo bda : beans.bdas) {
            if (bda.uri != null) {
                try {
                    beansXml.add(bda.uri.toURL());
                } catch (final MalformedURLException e) {
                // no-op
                }
            }
            infoByBda.put(bda, handleBda(startupObject, classLoader, comparator, beans, scl, filterByClassLoader, beanArchiveService, openejb, bda));
        }
        for (final BeansInfo.BDAInfo bda : beans.noDescriptorBdas) {
            // infoByBda.put() not needed since we know it means annotated
            handleBda(startupObject, classLoader, comparator, beans, scl, filterByClassLoader, beanArchiveService, openejb, bda);
        }
        if (startupObject.getBeanContexts() != null) {
            for (final BeanContext bc : startupObject.getBeanContexts()) {
                final String name = bc.getBeanClass().getName();
                if (BeanContext.Comp.class.getName().equals(name)) {
                    continue;
                }
                boolean cdi = false;
                for (final BeansInfo.BDAInfo bda : beans.bdas) {
                    final BeanArchiveService.BeanArchiveInformation info = infoByBda.get(bda);
                    if (info.getBeanDiscoveryMode() == BeanArchiveService.BeanDiscoveryMode.NONE) {
                        continue;
                    }
                    if (bda.managedClasses.contains(name)) {
                        classes.add(load(name, classLoader));
                        cdi = true;
                        break;
                    }
                }
                if (!cdi) {
                    for (final BeansInfo.BDAInfo bda : beans.noDescriptorBdas) {
                        if (bda.managedClasses.contains(name)) {
                            classes.add(load(name, classLoader));
                            break;
                        }
                    }
                }
            }
        }
        if ("true".equalsIgnoreCase(SystemInstance.get().getProperty("openejb.cdi.debug", "false"))) {
            final Logger logger = Logger.getInstance(LogCategory.OPENEJB, CdiScanner.class.getName());
            logger.info("CDI beans for " + startupObject.getAppInfo().appId + (startupObject.getWebContext() != null ? " webcontext = " + startupObject.getWebContext().getContextRoot() : ""));
            final List<String> names = new ArrayList<>(classes.size());
            for (final Class<?> c : classes) {
                names.add(c.getName());
            }
            Collections.sort(names);
            for (final String c : names) {
                logger.info("    " + c);
            }
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) ClassLoaderComparator(org.apache.openejb.util.classloader.ClassLoaderComparator) DefaultClassLoaderComparator(org.apache.openejb.util.classloader.DefaultClassLoaderComparator) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Logger(org.apache.openejb.util.Logger) WebBeansContext(org.apache.webbeans.config.WebBeansContext) BeansInfo(org.apache.openejb.assembler.classic.BeansInfo) DefaultClassLoaderComparator(org.apache.openejb.util.classloader.DefaultClassLoaderComparator) BeanArchiveService(org.apache.webbeans.spi.BeanArchiveService) AppInfo(org.apache.openejb.assembler.classic.AppInfo) BeanContext(org.apache.openejb.BeanContext) InterceptorsManager(org.apache.webbeans.intercept.InterceptorsManager) EjbJarInfo(org.apache.openejb.assembler.classic.EjbJarInfo)

Aggregations

WebBeansContext (org.apache.webbeans.config.WebBeansContext)39 AppContext (org.apache.openejb.AppContext)11 BeanContext (org.apache.openejb.BeanContext)10 WebContext (org.apache.openejb.core.WebContext)9 Context (javax.naming.Context)8 OpenEJBException (org.apache.openejb.OpenEJBException)8 BeanManagerImpl (org.apache.webbeans.container.BeanManagerImpl)8 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)6 Properties (java.util.Properties)6 NamingException (javax.naming.NamingException)6 ServletContext (javax.servlet.ServletContext)6 OpenEJBRuntimeException (org.apache.openejb.OpenEJBRuntimeException)6 InitialContext (javax.naming.InitialContext)5 ContextsService (org.apache.webbeans.spi.ContextsService)5 MalformedURLException (java.net.MalformedURLException)4 CreationalContext (javax.enterprise.context.spi.CreationalContext)4 InjectionProcessor (org.apache.openejb.InjectionProcessor)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3