Search in sources :

Example 11 with TransactionPolicy

use of org.apache.openejb.core.transaction.TransactionPolicy in project tomee by apache.

the class BaseContext method getRollbackOnly.

public boolean getRollbackOnly() throws IllegalStateException {
    doCheck(Call.getRollbackOnly);
    final ThreadContext threadContext = ThreadContext.getThreadContext();
    final BeanContext di = threadContext.getBeanContext();
    if (di.isBeanManagedTransaction()) {
        throw new IllegalStateException("bean-managed transaction beans can not access the getRollbackOnly() method: deploymentId=" + di.getDeploymentID());
    }
    final TransactionPolicy txPolicy = threadContext.getTransactionPolicy();
    if (txPolicy == null) {
        throw new IllegalStateException("ThreadContext does not contain a TransactionEnvironment");
    }
    if (txPolicy.getTransactionType() == TransactionType.Never || txPolicy.getTransactionType() == TransactionType.NotSupported || txPolicy.getTransactionType() == TransactionType.Supports) {
        throw new IllegalStateException("getRollbackOnly accessible only from MANDATORY, REQUIRED, or REQUIRES_NEW");
    }
    return txPolicy.isRollbackOnly();
}
Also used : BeanContext(org.apache.openejb.BeanContext) TransactionPolicy(org.apache.openejb.core.transaction.TransactionPolicy)

Example 12 with TransactionPolicy

use of org.apache.openejb.core.transaction.TransactionPolicy in project tomee by apache.

the class CmpContainer method findEJBObject.

private Object findEJBObject(final Method callMethod, final Object[] args, final ThreadContext callContext, final InterfaceType interfaceType) throws OpenEJBException {
    final BeanContext beanContext = callContext.getBeanContext();
    final TransactionPolicy txPolicy = createTransactionPolicy(beanContext.getTransactionType(callMethod, interfaceType), callContext);
    try {
        final List<Object> results = cmpEngine.queryBeans(callContext, callMethod, args);
        final KeyGenerator kg = beanContext.getKeyGenerator();
        // single ProxyInfo object is returned.
        if (callMethod.getReturnType() == Collection.class || callMethod.getReturnType() == Enumeration.class) {
            final List<ProxyInfo> proxies = new ArrayList<ProxyInfo>();
            for (final Object value : results) {
                final EntityBean bean = (EntityBean) value;
                if (value == null) {
                    proxies.add(null);
                } else {
                    // get the primary key
                    final Object primaryKey = kg.getPrimaryKey(bean);
                    // create a new ProxyInfo based on the deployment info and primary key and add it to the vector
                    proxies.add(new ProxyInfo(beanContext, primaryKey));
                }
            }
            if (callMethod.getReturnType() == Enumeration.class) {
                return new Enumerator(proxies);
            } else {
                return proxies;
            }
        } else {
            if (results.size() != 1) {
                throw new ObjectNotFoundException("A Enteprise bean with deployment_id = " + beanContext.getDeploymentID() + (args != null && args.length >= 1 ? " and primarykey = " + args[0] : "") + " Does not exist");
            }
            // create a new ProxyInfo based on the deployment info and primary key
            final EntityBean bean = (EntityBean) results.get(0);
            if (bean == null) {
                return null;
            } else {
                final Object primaryKey = kg.getPrimaryKey(bean);
                return new ProxyInfo(beanContext, primaryKey);
            }
        }
    } catch (final FinderException fe) {
        handleApplicationException(txPolicy, fe, false);
    } catch (final Throwable e) {
        // handle reflection exception
        handleSystemException(txPolicy, e, callContext);
    } finally {
        afterInvoke(txPolicy, callContext);
    }
    throw new AssertionError("Should not get here");
}
Also used : Enumeration(java.util.Enumeration) ArrayList(java.util.ArrayList) TransactionPolicy(org.apache.openejb.core.transaction.TransactionPolicy) EjbTransactionUtil.createTransactionPolicy(org.apache.openejb.core.transaction.EjbTransactionUtil.createTransactionPolicy) BeanContext(org.apache.openejb.BeanContext) ProxyInfo(org.apache.openejb.ProxyInfo) FinderException(javax.ejb.FinderException) Enumerator(org.apache.openejb.util.Enumerator) EntityBean(javax.ejb.EntityBean) ObjectNotFoundException(javax.ejb.ObjectNotFoundException) Collection(java.util.Collection) EJBLocalObject(javax.ejb.EJBLocalObject) EJBObject(javax.ejb.EJBObject)

Example 13 with TransactionPolicy

use of org.apache.openejb.core.transaction.TransactionPolicy 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)

Example 14 with TransactionPolicy

use of org.apache.openejb.core.transaction.TransactionPolicy in project tomee by apache.

the class SingletonContainer method _invoke.

protected Object _invoke(final Method callMethod, final Method runMethod, final Object[] args, final Instance instance, final ThreadContext callContext, final InterfaceType callType) throws OpenEJBException {
    final BeanContext beanContext = callContext.getBeanContext();
    final Duration accessTimeout = getAccessTimeout(beanContext, runMethod);
    final boolean read = javax.ejb.LockType.READ.equals(beanContext.getConcurrencyAttribute(runMethod));
    final Lock lock = aquireLock(read, accessTimeout, instance, runMethod);
    Object returnValue;
    try {
        final TransactionPolicy txPolicy = createTransactionPolicy(beanContext.getTransactionType(callMethod, callType), callContext);
        returnValue = null;
        try {
            if (callType == InterfaceType.SERVICE_ENDPOINT) {
                callContext.setCurrentOperation(Operation.BUSINESS_WS);
                returnValue = invokeWebService(args, beanContext, runMethod, instance);
            } else {
                final List<InterceptorData> interceptors = beanContext.getMethodInterceptors(runMethod);
                final InterceptorStack interceptorStack = new InterceptorStack(instance.bean, runMethod, callType == InterfaceType.TIMEOUT ? Operation.TIMEOUT : Operation.BUSINESS, interceptors, instance.interceptors);
                returnValue = interceptorStack.invoke(args);
            }
        } catch (final Throwable e) {
            // handle reflection exception
            final ExceptionType type = beanContext.getExceptionType(e);
            if (type == ExceptionType.SYSTEM) {
                /* System Exception ****************************/
                // The bean instance is not put into the pool via instanceManager.poolInstance
                // and therefore the instance will be garbage collected and destroyed.
                // For this reason the discardInstance method of the StatelessInstanceManager
                // does nothing.
                handleSystemException(txPolicy, e, callContext);
            } else {
                /* Application Exception ***********************/
                handleApplicationException(txPolicy, e, type == ExceptionType.APPLICATION_ROLLBACK);
            }
        } finally {
            afterInvoke(txPolicy, callContext);
        }
    } finally {
        lock.unlock();
    }
    return returnValue;
}
Also used : BeanContext(org.apache.openejb.BeanContext) ExceptionType(org.apache.openejb.core.ExceptionType) InterceptorData(org.apache.openejb.core.interceptor.InterceptorData) InterceptorStack(org.apache.openejb.core.interceptor.InterceptorStack) TransactionPolicy(org.apache.openejb.core.transaction.TransactionPolicy) EjbTransactionUtil.createTransactionPolicy(org.apache.openejb.core.transaction.EjbTransactionUtil.createTransactionPolicy) Duration(org.apache.openejb.util.Duration) EJBObject(javax.ejb.EJBObject) EJBLocalObject(javax.ejb.EJBLocalObject) Lock(java.util.concurrent.locks.Lock)

Example 15 with TransactionPolicy

use of org.apache.openejb.core.transaction.TransactionPolicy in project tomee by apache.

the class SingletonInstanceManager method freeInstance.

public void freeInstance(final ThreadContext callContext) {
    final BeanContext beanContext = callContext.getBeanContext();
    final Data data = (Data) beanContext.getContainerData();
    final Future<Instance> instanceFuture = data.singleton.get();
    // Possible the instance was never created
    if (instanceFuture == null) {
        return;
    }
    final Instance instance;
    try {
        instance = instanceFuture.get();
    } catch (final InterruptedException e) {
        Thread.interrupted();
        logger.error("Singleton shutdown failed because the thread was interrupted: " + beanContext.getDeploymentID(), e);
        return;
    } catch (final ExecutionException e) {
        // Instance was never initialized
        return;
    }
    try {
        callContext.setCurrentOperation(Operation.PRE_DESTROY);
        callContext.setCurrentAllowedStates(null);
        final Method remove = instance.bean instanceof SessionBean ? beanContext.getCreateMethod() : null;
        final List<InterceptorData> callbackInterceptors = beanContext.getCallbackInterceptors();
        final InterceptorStack interceptorStack = new InterceptorStack(instance.bean, remove, Operation.PRE_DESTROY, callbackInterceptors, instance.interceptors);
        //Transaction Demarcation for Singleton PostConstruct method
        TransactionType transactionType;
        if (beanContext.getComponentType() == BeanType.SINGLETON) {
            final Set<Method> callbacks = callbackInterceptors.get(callbackInterceptors.size() - 1).getPreDestroy();
            if (callbacks.isEmpty()) {
                transactionType = TransactionType.RequiresNew;
            } else {
                transactionType = beanContext.getTransactionType(callbacks.iterator().next());
                if (transactionType == TransactionType.Required) {
                    transactionType = TransactionType.RequiresNew;
                }
            }
        } else {
            transactionType = beanContext.isBeanManagedTransaction() ? TransactionType.BeanManaged : TransactionType.NotSupported;
        }
        final TransactionPolicy transactionPolicy = EjbTransactionUtil.createTransactionPolicy(transactionType, callContext);
        try {
            //Call the chain
            final CdiEjbBean<Object> bean = beanContext.get(CdiEjbBean.class);
            if (bean != null) {
                // TODO: see if it should be called before or after next call
                bean.getInjectionTarget().preDestroy(instance.bean);
            }
            interceptorStack.invoke();
            if (instance.creationalContext != null) {
                instance.creationalContext.release();
            }
        } catch (final Throwable e) {
            //RollBack Transaction
            EjbTransactionUtil.handleSystemException(transactionPolicy, e, callContext);
        } finally {
            EjbTransactionUtil.afterInvoke(transactionPolicy, callContext);
        }
    } catch (final Throwable re) {
        logger.error("Singleton shutdown failed: " + beanContext.getDeploymentID(), re);
    }
}
Also used : TransactionType(org.apache.openejb.core.transaction.TransactionType) SystemInstance(org.apache.openejb.loader.SystemInstance) TransactionPolicy(org.apache.openejb.core.transaction.TransactionPolicy) InterceptorData(org.apache.openejb.core.interceptor.InterceptorData) Method(java.lang.reflect.Method) SessionBean(javax.ejb.SessionBean) BeanContext(org.apache.openejb.BeanContext) InterceptorData(org.apache.openejb.core.interceptor.InterceptorData) InterceptorStack(org.apache.openejb.core.interceptor.InterceptorStack) ExecutionException(java.util.concurrent.ExecutionException)

Aggregations

TransactionPolicy (org.apache.openejb.core.transaction.TransactionPolicy)38 BeanContext (org.apache.openejb.BeanContext)26 EjbTransactionUtil.createTransactionPolicy (org.apache.openejb.core.transaction.EjbTransactionUtil.createTransactionPolicy)17 Method (java.lang.reflect.Method)14 EJBLocalObject (javax.ejb.EJBLocalObject)11 EJBObject (javax.ejb.EJBObject)11 EntityBean (javax.ejb.EntityBean)11 ThreadContext (org.apache.openejb.core.ThreadContext)10 InterceptorData (org.apache.openejb.core.interceptor.InterceptorData)10 InterceptorStack (org.apache.openejb.core.interceptor.InterceptorStack)10 BeanTransactionPolicy (org.apache.openejb.core.transaction.BeanTransactionPolicy)10 JtaTransactionPolicy (org.apache.openejb.core.transaction.JtaTransactionPolicy)10 ApplicationException (org.apache.openejb.ApplicationException)8 SystemInstance (org.apache.openejb.loader.SystemInstance)7 OpenEJBException (org.apache.openejb.OpenEJBException)6 ProxyInfo (org.apache.openejb.ProxyInfo)6 SystemException (org.apache.openejb.SystemException)6 Operation (org.apache.openejb.core.Operation)6 SuspendedTransaction (org.apache.openejb.core.transaction.BeanTransactionPolicy.SuspendedTransaction)6 InvocationTargetException (java.lang.reflect.InvocationTargetException)5