Search in sources :

Example 6 with CreationalContext

use of javax.enterprise.context.spi.CreationalContext in project tomee by apache.

the class OpenEJBBeanBuilder method getInstance.

@Override
protected A getInstance(final CreationalContext<A> creationalContext) {
    final List<Class> classes = beanContext.getBusinessLocalInterfaces();
    final CurrentCreationalContext currentCreationalContext = beanContext.get(CurrentCreationalContext.class);
    final CreationalContext existing = currentCreationalContext.get();
    currentCreationalContext.set(creationalContext);
    try {
        if (classes.size() == 0 && beanContext.isLocalbean()) {
            final BeanContext.BusinessLocalBeanHome home = beanContext.getBusinessLocalBeanHome();
            return (A) home.create();
        } else {
            final Class<?> mainInterface = classes.get(0);
            final List<Class> interfaces = ProxyInterfaceResolver.getInterfaces(beanContext.getBeanClass(), mainInterface, classes);
            final BeanContext.BusinessLocalHome home = beanContext.getBusinessLocalHome(interfaces, mainInterface);
            return (A) home.create();
        }
    } finally {
        currentCreationalContext.set(existing);
    }
}
Also used : CreationalContext(javax.enterprise.context.spi.CreationalContext) BeanContext(org.apache.openejb.BeanContext)

Example 7 with CreationalContext

use of javax.enterprise.context.spi.CreationalContext in project tomee by apache.

the class CdiEjbBean method createEjb.

protected T createEjb(final CreationalContext<T> creationalContext) {
    final CurrentCreationalContext currentCreationalContext = beanContext.get(CurrentCreationalContext.class);
    final CreationalContext existing = currentCreationalContext.get();
    currentCreationalContext.set(creationalContext);
    try {
        final T instance;
        if (homeLocalBean != null) {
            instance = (T) homeLocalBean.create();
        } else if (home != null) {
            instance = (T) home.create();
        } else if (remote != null) {
            instance = (T) remote.create();
        } else {
            // shouldn't be called for an MDB
            throw new IllegalStateException("no interface to proxy for ejb " + beanContext.getEjbName() + ", is this is a MDB maybe you shouldn't use a scope?");
        }
        if (isDependentAndStateful) {
            CreationalContextImpl.class.cast(creationalContext).addDependent(this, instance);
        }
        return instance;
    } finally {
        currentCreationalContext.set(existing);
    }
}
Also used : CreationalContext(javax.enterprise.context.spi.CreationalContext) CreationalContextImpl(org.apache.webbeans.context.creational.CreationalContextImpl)

Example 8 with CreationalContext

use of javax.enterprise.context.spi.CreationalContext in project tomee by apache.

the class CdiPlugin method getSessionBeanProxy.

@Override
public Object getSessionBeanProxy(final Bean<?> inBean, final Class<?> interfce, final CreationalContext<?> creationalContext) {
    Object instance = cacheProxies.get(inBean);
    if (instance != null) {
        return instance;
    }
    synchronized (inBean) {
        // singleton for the app so safe to sync on it
        instance = cacheProxies.get(inBean);
        if (instance != null) {
            return instance;
        }
        final Class<? extends Annotation> scopeClass = inBean.getScope();
        final CdiEjbBean<Object> cdiEjbBean = (CdiEjbBean<Object>) inBean;
        final CreationalContext<Object> cc = (CreationalContext<Object>) creationalContext;
        if (scopeClass == null || Dependent.class == scopeClass) {
            // no need to add any layer, null = @New
            return cdiEjbBean.createEjb(cc);
        }
        // only stateful normally
        final InstanceBean<Object> bean = new InstanceBean<Object>(cdiEjbBean);
        if (webBeansContext.getBeanManagerImpl().isNormalScope(scopeClass)) {
            final BeanContext beanContext = cdiEjbBean.getBeanContext();
            final Provider provider = webBeansContext.getNormalScopeProxyFactory().getInstanceProvider(beanContext.getClassLoader(), cdiEjbBean);
            if (!beanContext.isLocalbean()) {
                final List<Class> interfaces = new ArrayList<Class>();
                final InterfaceType type = beanContext.getInterfaceType(interfce);
                if (type != null) {
                    interfaces.addAll(beanContext.getInterfaces(type));
                } else {
                    // can happen when looked up from impl instead of API in OWB -> default to business local
                    interfaces.addAll(beanContext.getInterfaces(InterfaceType.BUSINESS_LOCAL));
                }
                interfaces.add(Serializable.class);
                interfaces.add(IntraVmProxy.class);
                if (BeanType.STATEFUL.equals(beanContext.getComponentType()) || BeanType.MANAGED.equals(beanContext.getComponentType())) {
                    interfaces.add(BeanContext.Removable.class);
                }
                try {
                    instance = ProxyManager.newProxyInstance(interfaces.toArray(new Class<?>[interfaces.size()]), new InvocationHandler() {

                        @Override
                        public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
                            try {
                                return method.invoke(provider.get(), args);
                            } catch (final InvocationTargetException ite) {
                                throw ite.getCause();
                            }
                        }
                    });
                } catch (final IllegalAccessException e) {
                    throw new OpenEJBRuntimeException(e);
                }
            } else {
                final NormalScopeProxyFactory normalScopeProxyFactory = webBeansContext.getNormalScopeProxyFactory();
                final Class<?> proxyClass = normalScopeProxyFactory.createProxyClass(beanContext.getClassLoader(), beanContext.getBeanClass());
                instance = normalScopeProxyFactory.createProxyInstance(proxyClass, provider);
            }
            cacheProxies.put(inBean, instance);
        } else {
            final Context context = webBeansContext.getBeanManagerImpl().getContext(scopeClass);
            instance = context.get(bean, cc);
        }
        bean.setOwbProxy(instance);
        return instance;
    }
}
Also used : WebBeansContext(org.apache.webbeans.config.WebBeansContext) BeanContext(org.apache.openejb.BeanContext) Context(javax.enterprise.context.spi.Context) CreationalContext(javax.enterprise.context.spi.CreationalContext) NormalScopeProxyFactory(org.apache.webbeans.proxy.NormalScopeProxyFactory) ArrayList(java.util.ArrayList) Dependent(javax.enterprise.context.Dependent) ObserverMethod(javax.enterprise.inject.spi.ObserverMethod) Method(java.lang.reflect.Method) AnnotatedMethod(javax.enterprise.inject.spi.AnnotatedMethod) InvocationHandler(java.lang.reflect.InvocationHandler) InvocationTargetException(java.lang.reflect.InvocationTargetException) Provider(javax.inject.Provider) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) CreationalContext(javax.enterprise.context.spi.CreationalContext) BeanContext(org.apache.openejb.BeanContext) InterfaceType(org.apache.openejb.InterfaceType)

Example 9 with CreationalContext

use of javax.enterprise.context.spi.CreationalContext in project tomee by apache.

the class Assembler method deployMBean.

@SuppressWarnings("unchecked")
private void deployMBean(final WebBeansContext wc, final ClassLoader cl, final String mbeanClass, final Properties appMbeans, final String id) {
    if (LocalMBeanServer.isJMXActive()) {
        final Class<?> clazz;
        try {
            clazz = cl.loadClass(mbeanClass);
        } catch (final ClassNotFoundException e) {
            throw new OpenEJBRuntimeException(e);
        }
        // cdi can be off so init with null bean in this case
        final Bean<?> bean;
        final BeanManager bm;
        if (wc == null) {
            bm = null;
            bean = null;
        } else {
            bm = wc.getBeanManagerImpl();
            final Set<Bean<?>> beans = bm.getBeans(clazz);
            bean = bm.resolve(beans);
        }
        // create the MBean instance with cdi if possible or manually otherwise
        final Object instance;
        final CreationalContext creationalContext;
        if (bean == null) {
            try {
                instance = clazz.newInstance();
            } catch (final InstantiationException e) {
                logger.error("the mbean " + mbeanClass + " can't be registered because it can't be instantiated", e);
                return;
            } catch (final IllegalAccessException e) {
                logger.error("the mbean " + mbeanClass + " can't be registered because it can't be accessed", e);
                return;
            }
            creationalContext = null;
        } else {
            creationalContext = bm.createCreationalContext(bean);
            instance = bm.getReference(bean, clazz, creationalContext);
        }
        final MBeanServer server = LocalMBeanServer.get();
        try {
            final MBean annotation = clazz.getAnnotation(MBean.class);
            final ObjectName leaf = annotation == null || annotation.objectName().isEmpty() ? new ObjectNameBuilder("openejb.user.mbeans").set("application", id).set("group", clazz.getPackage().getName()).set("name", clazz.getSimpleName()).build() : new ObjectName(annotation.objectName());
            server.registerMBean(new DynamicMBeanWrapper(wc, instance), leaf);
            appMbeans.put(mbeanClass, leaf.getCanonicalName());
            if (creationalContext != null && (bean.getScope() == null || Dependent.class.equals(bean.getScope()))) {
                creationalContextForAppMbeans.put(leaf, creationalContext);
            }
            logger.info("Deployed MBean(" + leaf.getCanonicalName() + ")");
        } catch (final Exception e) {
            logger.error("the mbean " + mbeanClass + " can't be registered", e);
        }
    }
}
Also used : MBean(org.apache.openejb.api.jmx.MBean) Dependent(javax.enterprise.context.Dependent) 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) ResourceBean(org.apache.webbeans.component.ResourceBean) MBean(org.apache.openejb.api.jmx.MBean) Bean(javax.enterprise.inject.spi.Bean) ObjectName(javax.management.ObjectName) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) CreationalContext(javax.enterprise.context.spi.CreationalContext) ObjectNameBuilder(org.apache.openejb.monitoring.ObjectNameBuilder) DynamicMBeanWrapper(org.apache.openejb.monitoring.DynamicMBeanWrapper) BeanManager(javax.enterprise.inject.spi.BeanManager) LocalMBeanServer(org.apache.openejb.monitoring.LocalMBeanServer) MBeanServer(javax.management.MBeanServer)

Example 10 with CreationalContext

use of javax.enterprise.context.spi.CreationalContext in project tomee by apache.

the class BeanContext method newInstance.

@SuppressWarnings("unchecked")
public InstanceContext newInstance() throws Exception {
    final ThreadContext callContext = new ThreadContext(this, null, Operation.INJECTION);
    final ThreadContext oldContext = ThreadContext.enter(callContext);
    final boolean dynamicallyImplemented = isDynamicallyImplemented();
    final WebBeansContext webBeansContext = getWebBeansContext();
    if (dynamicallyImplemented) {
        if (!InvocationHandler.class.isAssignableFrom(getProxyClass())) {
            throw new OpenEJBException("proxy class can only be InvocationHandler");
        }
    }
    try {
        final Context ctx = getJndiEnc();
        final Class beanClass = getBeanClass();
        final CurrentCreationalContext<Object> currentCreationalContext = get(CurrentCreationalContext.class);
        CreationalContext<Object> creationalContext = currentCreationalContext != null ? currentCreationalContext.get() : null;
        final CdiEjbBean cdiEjbBean = get(CdiEjbBean.class);
        if (!CreationalContextImpl.class.isInstance(creationalContext) && webBeansContext != null) {
            if (creationalContext == null) {
                creationalContext = webBeansContext.getCreationalContextFactory().getCreationalContext(cdiEjbBean);
            } else {
                creationalContext = webBeansContext.getCreationalContextFactory().wrappedCreationalContext(creationalContext, cdiEjbBean);
            }
        }
        final Object rootInstance;
        if (cdiEjbBean != null && !dynamicallyImplemented && CdiEjbBean.EjbInjectionTargetImpl.class.isInstance(cdiEjbBean.getInjectionTarget())) {
            rootInstance = CdiEjbBean.EjbInjectionTargetImpl.class.cast(cdiEjbBean.getInjectionTarget()).createNewPojo(creationalContext);
        } else {
            // not a cdi bean
            rootInstance = getManagedClass().newInstance();
        }
        // Create bean instance
        Object beanInstance;
        final InjectionProcessor injectionProcessor;
        if (!dynamicallyImplemented) {
            injectionProcessor = new InjectionProcessor(rootInstance, getInjections(), InjectionProcessor.unwrap(ctx));
            beanInstance = injectionProcessor.createInstance();
            inject(beanInstance, creationalContext);
        } else {
            // update target
            final List<Injection> newInjections = new ArrayList<Injection>();
            for (final Injection injection : getInjections()) {
                if (beanClass.equals(injection.getTarget())) {
                    final Injection updated = new Injection(injection.getJndiName(), injection.getName(), proxyClass);
                    newInjections.add(updated);
                } else {
                    newInjections.add(injection);
                }
            }
            injections.clear();
            injections.addAll(newInjections);
            injectionProcessor = new InjectionProcessor(rootInstance, injections, InjectionProcessor.unwrap(ctx));
            final InvocationHandler handler = (InvocationHandler) injectionProcessor.createInstance();
            beanInstance = DynamicProxyImplFactory.newProxy(this, handler);
            inject(handler, creationalContext);
        }
        // Create interceptors
        final Map<String, Object> interceptorInstances = new LinkedHashMap<String, Object>();
        // Add the stats interceptor instance and other already created interceptor instances
        for (final InterceptorInstance interceptorInstance : this.getUserAndSystemInterceptors()) {
            final Class clazz = interceptorInstance.getData().getInterceptorClass();
            interceptorInstances.put(clazz.getName(), interceptorInstance.getInterceptor());
        }
        for (final InterceptorData interceptorData : this.getInstanceScopedInterceptors()) {
            if (interceptorData.getInterceptorClass().equals(beanClass)) {
                continue;
            }
            final Class clazz = interceptorData.getInterceptorClass();
            final Object iInstance;
            if (webBeansContext != null) {
                ConstructorInjectionBean interceptorConstructor = interceptorData.get(ConstructorInjectionBean.class);
                if (interceptorConstructor == null) {
                    synchronized (this) {
                        interceptorConstructor = interceptorData.get(ConstructorInjectionBean.class);
                        if (interceptorConstructor == null) {
                            interceptorConstructor = new ConstructorInjectionBean(webBeansContext, clazz, webBeansContext.getAnnotatedElementFactory().newAnnotatedType(clazz));
                            interceptorData.set(ConstructorInjectionBean.class, interceptorConstructor);
                        }
                    }
                }
                iInstance = interceptorConstructor.create(creationalContext);
            } else {
                iInstance = clazz.newInstance();
            }
            final InjectionProcessor interceptorInjector = new InjectionProcessor(iInstance, this.getInjections(), InjectionProcessor.unwrap(ctx));
            try {
                final Object interceptorInstance = interceptorInjector.createInstance();
                if (webBeansContext != null) {
                    try {
                        OWBInjector.inject(webBeansContext.getBeanManagerImpl(), interceptorInstance, creationalContext);
                    } catch (final Throwable t) {
                    // TODO handle this differently
                    // this is temporary till the injector can be rewritten
                    }
                }
                interceptorInstances.put(clazz.getName(), interceptorInstance);
            } catch (final ConstructionException e) {
                throw new Exception("Failed to create interceptor: " + clazz.getName(), e);
            }
        }
        interceptorInstances.put(beanClass.getName(), beanInstance);
        // Invoke post construct method
        callContext.setCurrentOperation(Operation.POST_CONSTRUCT);
        final List<InterceptorData> callbackInterceptors = this.getCallbackInterceptors();
        final InterceptorStack postConstruct = new InterceptorStack(beanInstance, null, Operation.POST_CONSTRUCT, callbackInterceptors, interceptorInstances);
        //Transaction Demarcation for Singleton PostConstruct method
        TransactionType transactionType;
        if (componentType == BeanType.SINGLETON || componentType == BeanType.STATEFUL) {
            final Set<Method> callbacks = callbackInterceptors.get(callbackInterceptors.size() - 1).getPostConstruct();
            if (callbacks.isEmpty()) {
                transactionType = TransactionType.RequiresNew;
            } else {
                // TODO: we should take the last one I think
                transactionType = getTransactionType(callbacks.iterator().next());
                if (transactionType == TransactionType.Required) {
                    transactionType = TransactionType.RequiresNew;
                }
            }
        } else {
            transactionType = isBeanManagedTransaction() ? TransactionType.BeanManaged : TransactionType.NotSupported;
        }
        final TransactionPolicy transactionPolicy = EjbTransactionUtil.createTransactionPolicy(transactionType, callContext);
        try {
            //Call the chain
            if (cdiEjbBean != null) {
                // call it, it has no postconstruct but extensions can add stuff here, TODO: see if it should be called before or after effective postconstruct
                cdiEjbBean.getInjectionTarget().postConstruct(beanInstance);
            }
            postConstruct.invoke();
        } catch (final Throwable e) {
            //RollBack Transaction
            EjbTransactionUtil.handleSystemException(transactionPolicy, e, callContext);
        } finally {
            EjbTransactionUtil.afterInvoke(transactionPolicy, callContext);
        }
        // handle cdi decorators
        if (cdiEjbBean != null) {
            final Class<?> proxyClass = Class.class.cast(Reflections.get(cdiEjbBean.getInjectionTarget(), "proxyClass"));
            if (proxyClass != null) {
                // means interception
                final InterceptorResolutionService.BeanInterceptorInfo interceptorInfo = cdiEjbBean.getBeanContext().get(InterceptorResolutionService.BeanInterceptorInfo.class);
                if (interceptorInfo.getDecorators() != null && !interceptorInfo.getDecorators().isEmpty()) {
                    final InterceptorDecoratorProxyFactory pf = webBeansContext.getInterceptorDecoratorProxyFactory();
                    // decorators
                    final Object instance = beanInstance;
                    final List<Decorator<?>> decorators = interceptorInfo.getDecorators();
                    final Map<Decorator<?>, Object> instances = new HashMap<Decorator<?>, Object>();
                    for (int i = decorators.size(); i > 0; i--) {
                        final Decorator<?> decorator = decorators.get(i - 1);
                        CreationalContextImpl.class.cast(creationalContext).putDelegate(beanInstance);
                        final Object decoratorInstance = decorator.create(CreationalContext.class.cast(creationalContext));
                        instances.put(decorator, decoratorInstance);
                        beanInstance = pf.createProxyInstance(proxyClass, instance, new DecoratorHandler(interceptorInfo, decorators, instances, i - 1, instance, cdiEjbBean.getId()));
                    }
                }
            }
        }
        return new InstanceContext(this, beanInstance, interceptorInstances, creationalContext);
    } finally {
        ThreadContext.exit(oldContext);
    }
}
Also used : TransactionType(org.apache.openejb.core.transaction.TransactionType) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) CdiEjbBean(org.apache.openejb.cdi.CdiEjbBean) ArrayList(java.util.ArrayList) CreationalContextImpl(org.apache.webbeans.context.creational.CreationalContextImpl) DecoratorHandler(org.apache.webbeans.intercept.DecoratorHandler) LinkedHashMap(java.util.LinkedHashMap) WebBeansContext(org.apache.webbeans.config.WebBeansContext) InstanceContext(org.apache.openejb.core.InstanceContext) WebBeansContext(org.apache.webbeans.config.WebBeansContext) CurrentCreationalContext(org.apache.openejb.cdi.CurrentCreationalContext) CreationalContext(javax.enterprise.context.spi.CreationalContext) Context(javax.naming.Context) InstanceContext(org.apache.openejb.core.InstanceContext) ThreadContext(org.apache.openejb.core.ThreadContext) InterceptorResolutionService(org.apache.webbeans.intercept.InterceptorResolutionService) ConstructorInjectionBean(org.apache.openejb.cdi.ConstructorInjectionBean) ThreadContext(org.apache.openejb.core.ThreadContext) TransactionPolicy(org.apache.openejb.core.transaction.TransactionPolicy) InterceptorInstance(org.apache.openejb.core.interceptor.InterceptorInstance) Method(java.lang.reflect.Method) AnnotatedMethod(javax.enterprise.inject.spi.AnnotatedMethod) InvocationHandler(java.lang.reflect.InvocationHandler) ApplicationException(javax.ejb.ApplicationException) ConstructionException(org.apache.xbean.recipe.ConstructionException) Decorator(javax.enterprise.inject.spi.Decorator) CurrentCreationalContext(org.apache.openejb.cdi.CurrentCreationalContext) CreationalContext(javax.enterprise.context.spi.CreationalContext) InterceptorData(org.apache.openejb.core.interceptor.InterceptorData) InterceptorStack(org.apache.openejb.core.interceptor.InterceptorStack) TimedObject(javax.ejb.TimedObject) EJBLocalObject(javax.ejb.EJBLocalObject) EJBObject(javax.ejb.EJBObject) ConstructionException(org.apache.xbean.recipe.ConstructionException) InterceptorDecoratorProxyFactory(org.apache.webbeans.proxy.InterceptorDecoratorProxyFactory)

Aggregations

CreationalContext (javax.enterprise.context.spi.CreationalContext)13 Bean (javax.enterprise.inject.spi.Bean)4 Context (javax.naming.Context)4 OpenEJBException (org.apache.openejb.OpenEJBException)4 WebBeansContext (org.apache.webbeans.config.WebBeansContext)4 Method (java.lang.reflect.Method)3 ArrayList (java.util.ArrayList)3 BeanManager (javax.enterprise.inject.spi.BeanManager)3 InitialContext (javax.naming.InitialContext)3 NamingException (javax.naming.NamingException)3 ServletContext (javax.servlet.ServletContext)3 AppContext (org.apache.openejb.AppContext)3 BeanContext (org.apache.openejb.BeanContext)3 IOException (java.io.IOException)2 InvalidObjectException (java.io.InvalidObjectException)2 ObjectStreamException (java.io.ObjectStreamException)2 InvocationHandler (java.lang.reflect.InvocationHandler)2 MalformedURLException (java.net.MalformedURLException)2 URISyntaxException (java.net.URISyntaxException)2 ExecutionException (java.util.concurrent.ExecutionException)2