Search in sources :

Example 1 with BeanContext

use of org.apache.openejb.BeanContext in project tomee by apache.

the class OpenEJBDeployableContainer method deploy.

@Override
public ProtocolMetaData deploy(final Archive<?> archive) throws DeploymentException {
    final DeploymentInfo info;
    try {
        final Closeables cl = new Closeables();
        closeablesProducer.set(cl);
        info = quickDeploy(archive, testClass.get(), cl);
        // container rules (CDI) which is not the case with this solution
        if (archive.getName().endsWith(".war")) {
            final List<BeanContext> beanContexts = info.appCtx.getBeanContexts();
            if (beanContexts.size() > 1) {
                final Iterator<BeanContext> it = beanContexts.iterator();
                while (it.hasNext()) {
                    final BeanContext next = it.next();
                    if (ModuleTestContext.class.isInstance(next.getModuleContext()) && BeanContext.Comp.class != next.getBeanClass()) {
                        for (final BeanContext b : beanContexts) {
                            if (b.getModuleContext() != next.getModuleContext()) {
                                ModuleTestContext.class.cast(next.getModuleContext()).setModuleJndiContextOverride(b.getModuleContext().getModuleJndiContext());
                                break;
                            }
                        }
                        break;
                    }
                }
            }
        }
        servletContextProducer.set(info.appServletContext);
        sessionProducer.set(info.appSession);
        appInfoProducer.set(info.appInfo);
        appContextProducer.set(info.appCtx);
        final ClassLoader loader = info.appCtx.getWebContexts().isEmpty() ? info.appCtx.getClassLoader() : info.appCtx.getWebContexts().iterator().next().getClassLoader();
        final ClassLoader classLoader = loader == null ? info.appCtx.getClassLoader() : loader;
        TestObserver.ClassLoaders classLoaders = this.classLoader.get();
        if (classLoaders == null) {
            classLoaders = new TestObserver.ClassLoaders();
            this.classLoader.set(classLoaders);
        }
        classLoaders.register(archive.getName(), classLoader);
    } catch (final Exception e) {
        throw new DeploymentException("can't deploy " + archive.getName(), e);
    }
    // if service manager is started allow @ArquillianResource URL injection
    if (PROPERTIES.containsKey(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE)) {
        final ProtocolMetaData metaData = ServiceManagers.protocolMetaData(appInfoProducer.get());
        HTTPContext http = null;
        for (final WebAppInfo webapp : info.appInfo.webApps) {
            for (final ServletInfo servletInfo : webapp.servlets) {
                if (http == null) {
                    http = HTTPContext.class.cast(metaData.getContexts().iterator().next());
                    http.add(new Servlet(servletInfo.servletName, webapp.contextRoot));
                }
            }
            for (final ClassListInfo classListInfo : webapp.webAnnotatedClasses) {
                for (final String path : classListInfo.list) {
                    if (!path.contains("!")) {
                        continue;
                    }
                    if (http == null) {
                        http = HTTPContext.class.cast(metaData.getContexts().iterator().next());
                    }
                    http.add(new Servlet(path.substring(path.lastIndexOf('!') + 2).replace(".class", "").replace("/", "."), webapp.contextRoot));
                }
            }
        }
        if (metaData != null) {
            return metaData;
        }
    }
    return new ProtocolMetaData();
}
Also used : HTTPContext(org.jboss.arquillian.container.spi.client.protocol.metadata.HTTPContext) TestObserver(org.apache.openejb.arquillian.common.TestObserver) NamingException(javax.naming.NamingException) LifecycleException(org.jboss.arquillian.container.spi.client.container.LifecycleException) IOException(java.io.IOException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) DeploymentException(org.jboss.arquillian.container.spi.client.container.DeploymentException) ClassListInfo(org.apache.openejb.assembler.classic.ClassListInfo) ServletInfo(org.apache.openejb.assembler.classic.ServletInfo) BeanContext(org.apache.openejb.BeanContext) ModuleTestContext(org.apache.openejb.ModuleTestContext) WebAppInfo(org.apache.openejb.assembler.classic.WebAppInfo) Servlet(org.jboss.arquillian.container.spi.client.protocol.metadata.Servlet) DeploymentException(org.jboss.arquillian.container.spi.client.container.DeploymentException) ProtocolMetaData(org.jboss.arquillian.container.spi.client.protocol.metadata.ProtocolMetaData)

Example 2 with BeanContext

use of org.apache.openejb.BeanContext in project tomee by apache.

the class OpenEJBEnricher method enrich.

public static void enrich(final Object testInstance, final AppContext appCtx) {
    // don't rely on arquillian since this enrichment should absolutely be done before the following ones
    new MockitoEnricher().enrich(testInstance);
    AppContext ctx = appCtx;
    if (ctx == null) {
        ctx = AppFinder.findAppContextOrWeb(Thread.currentThread().getContextClassLoader(), AppFinder.AppContextTransformer.INSTANCE);
        if (ctx == null) {
            return;
        }
    }
    final BeanContext context = SystemInstance.get().getComponent(ContainerSystem.class).getBeanContext(ctx.getId() + "_" + testInstance.getClass().getName());
    final WebBeansContext appWBC = ctx.getWebBeansContext();
    final BeanManagerImpl bm = appWBC == null ? null : appWBC.getBeanManagerImpl();
    boolean ok = false;
    for (final WebContext web : ctx.getWebContexts()) {
        final WebBeansContext webBeansContext = web.getWebBeansContext();
        if (webBeansContext == null) {
            continue;
        }
        final BeanManagerImpl webAppBm = webBeansContext.getBeanManagerImpl();
        if (webBeansContext != appWBC && webAppBm.isInUse()) {
            try {
                doInject(testInstance, context, webAppBm);
                ok = true;
                break;
            } catch (final Exception e) {
            // no-op, try next
            }
        }
    }
    if (bm != null && bm.isInUse() && !ok) {
        try {
            doInject(testInstance, context, bm);
        } catch (final Exception e) {
            LOGGER.log(Level.SEVERE, "Failed injection on: " + testInstance.getClass(), e);
            if (RuntimeException.class.isInstance(e)) {
                throw RuntimeException.class.cast(e);
            }
            throw new OpenEJBRuntimeException(e);
        }
    }
    if (context != null) {
        final ThreadContext callContext = new ThreadContext(context, null, Operation.INJECTION);
        final ThreadContext oldContext = ThreadContext.enter(callContext);
        try {
            final InjectionProcessor processor = new InjectionProcessor<>(testInstance, context.getInjections(), context.getJndiContext());
            processor.createInstance();
        } catch (final OpenEJBException e) {
        // ignored
        } finally {
            ThreadContext.exit(oldContext);
        }
    }
}
Also used : ContainerSystem(org.apache.openejb.spi.ContainerSystem) OpenEJBException(org.apache.openejb.OpenEJBException) WebContext(org.apache.openejb.core.WebContext) AppContext(org.apache.openejb.AppContext) ThreadContext(org.apache.openejb.core.ThreadContext) InjectionProcessor(org.apache.openejb.InjectionProcessor) OpenEJBException(org.apache.openejb.OpenEJBException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) BeanContext(org.apache.openejb.BeanContext) WebBeansContext(org.apache.webbeans.config.WebBeansContext) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) BeanManagerImpl(org.apache.webbeans.container.BeanManagerImpl) MockitoEnricher(org.apache.openejb.arquillian.common.mockito.MockitoEnricher)

Example 3 with BeanContext

use of org.apache.openejb.BeanContext in project tomee by apache.

the class TomEEInjectionEnricher method getAppContext.

private AppContext getAppContext(final Class<?> clazz) {
    final String clazzName = clazz.getName();
    final ContainerSystem containerSystem = SystemInstance.get().getComponent(ContainerSystem.class);
    if (deployment != null && deployment.get() != null) {
        final BeanContext context = containerSystem.getBeanContext(deployment.get().getDescription().getName() + "_" + clazzName);
        if (context != null) {
            return context.getModuleContext().getAppContext();
        }
    }
    final List<AppContext> appContexts = containerSystem.getAppContexts();
    final ClassLoader loader = clazz.getClassLoader();
    for (final AppContext app : appContexts) {
        final BeanContext context = containerSystem.getBeanContext(app.getId() + "_" + clazzName);
        if (context != null) {
            // in embedded mode we have deployment so we dont go here were AppLoader would just be everywhere
            if (context.getBeanClass().getClassLoader() == loader) {
                return app;
            }
        }
    }
    if (deployment != null && deployment.get() != null && deployment.get().getDescription().testable() && !isJunitComponent(clazz)) /*app context will be found by classloader, no need to log anything there*/
    {
        Logger.getLogger(TomEEInjectionEnricher.class.getName()).log(Level.WARNING, "Failed to find AppContext for: " + clazzName);
    }
    return null;
}
Also used : ContainerSystem(org.apache.openejb.spi.ContainerSystem) BeanContext(org.apache.openejb.BeanContext) AppContext(org.apache.openejb.AppContext)

Example 4 with BeanContext

use of org.apache.openejb.BeanContext in project tomee by apache.

the class Assembler method initEjbs.

public List<BeanContext> initEjbs(final ClassLoader classLoader, final AppInfo appInfo, final AppContext appContext, final Set<Injection> injections, final List<BeanContext> allDeployments, final String webappId) throws OpenEJBException {
    final String globalTimersOn = SystemInstance.get().getProperty(OPENEJB_TIMERS_ON, "true");
    final EjbJarBuilder ejbJarBuilder = new EjbJarBuilder(props, appContext);
    for (final EjbJarInfo ejbJar : appInfo.ejbJars) {
        if (isSkip(appInfo, webappId, ejbJar)) {
            continue;
        }
        final HashMap<String, BeanContext> deployments = ejbJarBuilder.build(ejbJar, injections, classLoader);
        final JaccPermissionsBuilder jaccPermissionsBuilder = new JaccPermissionsBuilder();
        final PolicyContext policyContext = jaccPermissionsBuilder.build(ejbJar, deployments);
        jaccPermissionsBuilder.install(policyContext);
        final TransactionPolicyFactory transactionPolicyFactory = createTransactionPolicyFactory(ejbJar, classLoader);
        for (final BeanContext beanContext : deployments.values()) {
            beanContext.setTransactionPolicyFactory(transactionPolicyFactory);
        }
        final MethodTransactionBuilder methodTransactionBuilder = new MethodTransactionBuilder();
        methodTransactionBuilder.build(deployments, ejbJar.methodTransactions);
        final MethodConcurrencyBuilder methodConcurrencyBuilder = new MethodConcurrencyBuilder();
        methodConcurrencyBuilder.build(deployments, ejbJar.methodConcurrency);
        for (final BeanContext beanContext : deployments.values()) {
            containerSystem.addDeployment(beanContext);
        }
        // bind ejbs into global jndi
        jndiBuilder.build(ejbJar, deployments);
        // setup timers/asynchronous methods - must be after transaction attributes are set
        for (final BeanContext beanContext : deployments.values()) {
            if (beanContext.getComponentType() != BeanType.STATEFUL) {
                final Method ejbTimeout = beanContext.getEjbTimeout();
                boolean timerServiceRequired = false;
                if (ejbTimeout != null) {
                    // If user set the tx attribute to RequiresNew change it to Required so a new transaction is not started
                    if (beanContext.getTransactionType(ejbTimeout) == TransactionType.RequiresNew) {
                        beanContext.setMethodTransactionAttribute(ejbTimeout, TransactionType.Required);
                    }
                    timerServiceRequired = true;
                }
                for (final Iterator<Map.Entry<Method, MethodContext>> it = beanContext.iteratorMethodContext(); it.hasNext(); ) {
                    final Map.Entry<Method, MethodContext> entry = it.next();
                    final MethodContext methodContext = entry.getValue();
                    if (methodContext.getSchedules().size() > 0) {
                        timerServiceRequired = true;
                        final Method method = entry.getKey();
                        // TODO Need ?
                        if (beanContext.getTransactionType(method) == TransactionType.RequiresNew) {
                            beanContext.setMethodTransactionAttribute(method, TransactionType.Required);
                        }
                    }
                }
                if (timerServiceRequired && "true".equalsIgnoreCase(appInfo.properties.getProperty(OPENEJB_TIMERS_ON, globalTimersOn))) {
                    // Create the timer
                    final EjbTimerServiceImpl timerService = new EjbTimerServiceImpl(beanContext, newTimerStore(beanContext));
                    // Load auto-start timers
                    final TimerStore timerStore = timerService.getTimerStore();
                    for (final Iterator<Map.Entry<Method, MethodContext>> it = beanContext.iteratorMethodContext(); it.hasNext(); ) {
                        final Map.Entry<Method, MethodContext> entry = it.next();
                        final MethodContext methodContext = entry.getValue();
                        for (final ScheduleData scheduleData : methodContext.getSchedules()) {
                            timerStore.createCalendarTimer(timerService, (String) beanContext.getDeploymentID(), null, entry.getKey(), scheduleData.getExpression(), scheduleData.getConfig(), true);
                        }
                    }
                    beanContext.setEjbTimerService(timerService);
                } else {
                    beanContext.setEjbTimerService(new NullEjbTimerServiceImpl());
                }
            }
            // TODO ???
            for (final Iterator<Entry<Method, MethodContext>> it = beanContext.iteratorMethodContext(); it.hasNext(); ) {
                final Entry<Method, MethodContext> entry = it.next();
                if (entry.getValue().isAsynchronous() && beanContext.getTransactionType(entry.getKey()) == TransactionType.RequiresNew) {
                    beanContext.setMethodTransactionAttribute(entry.getKey(), TransactionType.Required);
                }
            }
            // if local bean or mdb generate proxy class now to avoid bottleneck on classloader later
            if (beanContext.isLocalbean() && !beanContext.getComponentType().isMessageDriven() && !beanContext.isDynamicallyImplemented()) {
                final List<Class> interfaces = new ArrayList<>(3);
                interfaces.add(Serializable.class);
                interfaces.add(IntraVmProxy.class);
                final BeanType type = beanContext.getComponentType();
                if (BeanType.STATEFUL.equals(type) || BeanType.MANAGED.equals(type)) {
                    interfaces.add(BeanContext.Removable.class);
                }
                beanContext.set(BeanContext.ProxyClass.class, new BeanContext.ProxyClass(beanContext, interfaces.toArray(new Class<?>[interfaces.size()])));
            }
        }
        // process application exceptions
        for (final ApplicationExceptionInfo exceptionInfo : ejbJar.applicationException) {
            try {
                final Class exceptionClass = classLoader.loadClass(exceptionInfo.exceptionClass);
                for (final BeanContext beanContext : deployments.values()) {
                    beanContext.addApplicationException(exceptionClass, exceptionInfo.rollback, exceptionInfo.inherited);
                }
            } catch (final ClassNotFoundException e) {
                logger.error("createApplication.invalidClass", e, exceptionInfo.exceptionClass, e.getMessage());
            }
        }
        allDeployments.addAll(deployments.values());
    }
    final List<BeanContext> ejbs = sort(allDeployments);
    for (final BeanContext b : ejbs) {
        // otherwise for ears we have duplicated beans
        if (appContext.getBeanContexts().contains(b)) {
            continue;
        }
        appContext.getBeanContexts().add(b);
    }
    return ejbs;
}
Also used : ScheduleData(org.apache.openejb.core.timer.ScheduleData) ArrayList(java.util.ArrayList) TimerStore(org.apache.openejb.core.timer.TimerStore) MemoryTimerStore(org.apache.openejb.core.timer.MemoryTimerStore) Entry(java.util.Map.Entry) JtaTransactionPolicyFactory(org.apache.openejb.core.transaction.JtaTransactionPolicyFactory) TransactionPolicyFactory(org.apache.openejb.core.transaction.TransactionPolicyFactory) MethodContext(org.apache.openejb.MethodContext) NullEjbTimerServiceImpl(org.apache.openejb.core.timer.NullEjbTimerServiceImpl) Method(java.lang.reflect.Method) EjbTimerServiceImpl(org.apache.openejb.core.timer.EjbTimerServiceImpl) NullEjbTimerServiceImpl(org.apache.openejb.core.timer.NullEjbTimerServiceImpl) BeanContext(org.apache.openejb.BeanContext) BeanType(org.apache.openejb.BeanType) Map(java.util.Map) TreeMap(java.util.TreeMap) HashMap(java.util.HashMap)

Example 5 with BeanContext

use of org.apache.openejb.BeanContext 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(javax.annotation.Resource) DestroyableResource(org.apache.openejb.api.resource.DestroyableResource) JndiUrlReference(org.apache.openejb.core.ivm.naming.JndiUrlReference) 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) BeanContext(org.apache.openejb.BeanContext) ResourceReference(org.apache.webbeans.spi.api.ResourceReference) DefinitionException(javax.enterprise.inject.spi.DefinitionException)

Aggregations

BeanContext (org.apache.openejb.BeanContext)198 OpenEJBException (org.apache.openejb.OpenEJBException)40 ThreadContext (org.apache.openejb.core.ThreadContext)40 Method (java.lang.reflect.Method)38 ContainerSystem (org.apache.openejb.spi.ContainerSystem)28 ArrayList (java.util.ArrayList)27 AppContext (org.apache.openejb.AppContext)26 TransactionPolicy (org.apache.openejb.core.transaction.TransactionPolicy)26 NamingException (javax.naming.NamingException)24 InterceptorData (org.apache.openejb.core.interceptor.InterceptorData)23 Context (javax.naming.Context)22 ApplicationException (org.apache.openejb.ApplicationException)20 HashMap (java.util.HashMap)19 EJBLocalObject (javax.ejb.EJBLocalObject)18 EJBObject (javax.ejb.EJBObject)18 SystemException (org.apache.openejb.SystemException)18 OpenEJBRuntimeException (org.apache.openejb.OpenEJBRuntimeException)17 ModuleContext (org.apache.openejb.ModuleContext)16 EjbTransactionUtil.createTransactionPolicy (org.apache.openejb.core.transaction.EjbTransactionUtil.createTransactionPolicy)16 FinderException (javax.ejb.FinderException)14