use of org.apache.openejb.core.interceptor.InterceptorData in project tomee by apache.
the class ManagedContainer method removeEJBObject.
protected Object removeEJBObject(final BeanContext beanContext, final Object primKey, final Class callInterface, final Method callMethod, Object[] args, final InterfaceType interfaceType) throws OpenEJBException {
if (primKey == null) {
throw new NullPointerException("primKey is null");
}
final ThreadContext callContext = new ThreadContext(beanContext, primKey);
final ThreadContext oldCallContext = ThreadContext.enter(callContext);
try {
// Security check
final boolean internalRemove = BeanContext.Removable.class == callMethod.getDeclaringClass();
if (!internalRemove) {
checkAuthorization(callMethod, interfaceType);
}
// If a bean managed transaction is active, the bean can not be removed
if (interfaceType.isComponent()) {
final Instance instance = checkedOutInstances.get(primKey);
/**
* According to EJB 3.0 "4.4.4 Restrictions for Transactions" any remove methods
* from home or component interfaces must not be allowed if the bean instance is
* in a transaction. Unfortunately, the Java EE 5 TCK has tests that ignore the
* restrictions in 4.4.4 and expect beans in transactions can be removed via their
* home or component interface. The test to see if the bean instance implements
* javax.ejb.SessionBean is a workaround for passing the TCK while the tests in
* question can be challenged or the spec can be changed/updated.
*/
if (instance != null && instance.bean instanceof SessionBean) {
throw new ApplicationException(new RemoveException("A stateful EJB enrolled in a transaction can not be removed"));
}
}
// Start transaction
final TransactionPolicy txPolicy = EjbTransactionUtil.createTransactionPolicy(callContext.getBeanContext().getTransactionType(callMethod, interfaceType), callContext);
Object returnValue = null;
boolean retain = false;
Instance instance = null;
Method runMethod = null;
try {
// Obtain instance
instance = obtainInstance(primKey, callContext);
// Resume previous Bean transaction if there was one
if (txPolicy instanceof BeanTransactionPolicy) {
// Resume previous Bean transaction if there was one
final SuspendedTransaction suspendedTransaction = instance.getBeanTransaction();
if (suspendedTransaction != null) {
instance.setBeanTransaction(null);
final BeanTransactionPolicy beanTxEnv = (BeanTransactionPolicy) txPolicy;
beanTxEnv.resumeUserTransaction(suspendedTransaction);
}
}
if (!internalRemove) {
// Register the entity managers
registerEntityManagers(instance, callContext);
// Register for synchronization callbacks
registerSessionSynchronization(instance, callContext);
// Setup for remove invocation
callContext.setCurrentOperation(Operation.REMOVE);
callContext.setCurrentAllowedStates(null);
callContext.setInvokedInterface(callInterface);
runMethod = beanContext.getMatchingBeanMethod(callMethod);
callContext.set(Method.class, runMethod);
// Do not pass arguments on home.remove(remote) calls
final Class<?> declaringClass = callMethod.getDeclaringClass();
if (declaringClass.equals(EJBHome.class) || declaringClass.equals(EJBLocalHome.class)) {
args = new Object[] {};
}
// Initialize interceptor stack
final List<InterceptorData> interceptors = beanContext.getMethodInterceptors(runMethod);
final InterceptorStack interceptorStack = new InterceptorStack(instance.bean, runMethod, Operation.REMOVE, interceptors, instance.interceptors);
// Invoke
if (args == null) {
returnValue = interceptorStack.invoke();
} else {
returnValue = interceptorStack.invoke(args);
}
}
} catch (final InvalidateReferenceException e) {
throw new ApplicationException(e.getRootCause());
} catch (final Throwable e) {
if (interfaceType.isBusiness()) {
retain = beanContext.retainIfExeption(runMethod);
handleException(callContext, txPolicy, e);
} else {
try {
handleException(callContext, txPolicy, e);
} catch (final ApplicationException ae) {
// Don't throw application exceptions for non-business interface removes
}
}
} finally {
if (!retain) {
try {
callContext.setCurrentOperation(Operation.PRE_DESTROY);
final List<InterceptorData> callbackInterceptors = beanContext.getCallbackInterceptors();
final InterceptorStack interceptorStack = new InterceptorStack(instance.bean, null, Operation.PRE_DESTROY, callbackInterceptors, instance.interceptors);
interceptorStack.invoke();
} catch (final Throwable callbackException) {
final String logMessage = "An unexpected exception occured while invoking the preDestroy method on the removed Stateful SessionBean instance; " + callbackException.getClass().getName() + " " + callbackException.getMessage();
/* [1] Log the exception or error */
logger.error(logMessage);
} finally {
callContext.setCurrentOperation(Operation.REMOVE);
}
// todo destroy extended persistence contexts
discardInstance(callContext);
}
// Commit transaction
afterInvoke(callContext, txPolicy, instance);
}
return returnValue;
} finally {
ThreadContext.exit(oldCallContext);
}
}
use of org.apache.openejb.core.interceptor.InterceptorData in project tomee by apache.
the class InterceptorBindingBuilder method createInterceptorDatas.
private List<InterceptorData> createInterceptorDatas(final Method method, final String ejbName, final List<InterceptorBindingInfo> bindings) {
final List<InterceptorBindingInfo> methodBindings = processBindings(method, ejbName, bindings);
Collections.reverse(methodBindings);
final List<InterceptorData> methodInterceptors = new ArrayList<InterceptorData>();
for (final InterceptorBindingInfo info : methodBindings) {
final List<String> classes = info.interceptorOrder.size() > 0 ? info.interceptorOrder : info.interceptors;
for (final String interceptorClassName : classes) {
final InterceptorData interceptorData = interceptors.get(interceptorClassName);
if (interceptorData == null) {
logger.warning("InterceptorBinding references non-existent (undeclared) interceptor: " + interceptorClassName);
continue;
}
methodInterceptors.add(interceptorData);
}
}
return methodInterceptors;
}
use of org.apache.openejb.core.interceptor.InterceptorData in project tomee by apache.
the class BeanContext method setCallbackInterceptors.
public void setCallbackInterceptors(final List<InterceptorData> callbackInterceptors) {
//TODO shouldn't we remove the old callbackInterceptors from instanceScopedInterceptors before adding the new ones?
this.beanCallbackInterceptors.clear();
this.callbackInterceptors.clear();
for (final InterceptorData data : callbackInterceptors) {
if (data.getInterceptorClass().isAssignableFrom(getManagedClass())) {
this.beanCallbackInterceptors.add(data);
} else {
this.callbackInterceptors.add(data);
}
}
this.instanceScopedInterceptors.addAll(callbackInterceptors);
}
use of org.apache.openejb.core.interceptor.InterceptorData 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);
}
}
use of org.apache.openejb.core.interceptor.InterceptorData in project tomee by apache.
the class BeanContext method createInterceptorData.
private InterceptorData createInterceptorData(final Interceptor<?> i) {
final InterceptorData data;
if (CdiInterceptorBean.class.isInstance(i)) {
final CdiInterceptorBean cdiInterceptorBean = CdiInterceptorBean.class.cast(i);
data = new InterceptorData(i.getBeanClass());
data.getAroundInvoke().addAll(getInterceptionMethodAsListOrEmpty(cdiInterceptorBean, InterceptionType.AROUND_INVOKE));
data.getPostConstruct().addAll(getInterceptionMethodAsListOrEmpty(cdiInterceptorBean, InterceptionType.POST_CONSTRUCT));
data.getPreDestroy().addAll(getInterceptionMethodAsListOrEmpty(cdiInterceptorBean, InterceptionType.PRE_DESTROY));
data.getPostActivate().addAll(getInterceptionMethodAsListOrEmpty(cdiInterceptorBean, InterceptionType.POST_ACTIVATE));
data.getPrePassivate().addAll(getInterceptionMethodAsListOrEmpty(cdiInterceptorBean, InterceptionType.PRE_PASSIVATE));
data.getAroundTimeout().addAll(getInterceptionMethodAsListOrEmpty(cdiInterceptorBean, InterceptionType.AROUND_TIMEOUT));
/*
AfterBegin, BeforeCompletion and AfterCompletion are ignored since not handled by CDI
*/
} else {
// TODO: here we are not as good as in previous since we loose inheritance for instance
data = InterceptorData.scan(i.getBeanClass());
}
return data;
}
Aggregations