use of javax.ejb.SessionBean in project tomee by apache.
the class StatefulContainer 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 CdiEjbBean cdiEjbBean = beanContext.get(CdiEjbBean.class);
if (cdiEjbBean != null) {
final Class scope = cdiEjbBean.getScope();
if (callMethod.getDeclaringClass() != BeanContext.Removable.class && scope != Dependent.class) {
throw new UnsupportedOperationException("Can not call EJB Stateful Bean Remove Method without scoped @Dependent. Found scope: @" + scope.getSimpleName());
}
}
final boolean internalRemove = BeanContext.Removable.class == callMethod.getDeclaringClass();
final ThreadContext callContext = new ThreadContext(beanContext, primKey);
final ThreadContext oldCallContext = ThreadContext.enter(callContext);
Object runAs = null;
try {
if (oldCallContext != null) {
final BeanContext oldBc = oldCallContext.getBeanContext();
if (oldBc.getRunAsUser() != null || oldBc.getRunAs() != null) {
runAs = AbstractSecurityService.class.cast(securityService).overrideWithRunAsContext(callContext, beanContext, oldBc);
}
}
// Security check
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, callMethod, beanContext.isPassivatingScope());
// 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
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);
}
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 (runAs != null) {
try {
securityService.associate(runAs);
} catch (final LoginException e) {
// no-op
}
}
if (!retain) {
try {
callContext.setCurrentOperation(Operation.PRE_DESTROY);
final List<InterceptorData> callbackInterceptors = beanContext.getCallbackInterceptors();
if (instance != null) {
final InterceptorStack interceptorStack = new InterceptorStack(instance.bean, null, Operation.PRE_DESTROY, callbackInterceptors, instance.interceptors);
interceptorStack.invoke();
}
} catch (final Throwable t) {
final String logMessage = "An unexpected exception occured while invoking the preDestroy method on the Stateful SessionBean instance: " + (null != instance ? instance.bean.getClass().getName() : beanContext.getBeanClass().getName());
logger.error(logMessage, t);
} finally {
callContext.setCurrentOperation(Operation.REMOVE);
}
discardInstance(primKey, instance);
}
// un register EntityManager
final Map<EntityManagerFactory, JtaEntityManagerRegistry.EntityManagerTracker> unregisteredEntityManagers = unregisterEntityManagers(instance, callContext);
// Commit transaction
afterInvoke(callContext, txPolicy, instance);
// Un register and close extended persistence contexts
/*
7.6.2 Container-managed Extended Persistence Context
A container-managed extended persistence context can only be initiated within the scope of a stateful
session bean. It exists from the point at which the stateful session bean that declares a dependency on an
entity manager of type PersistenceContextType.EXTENDED is created, and is said to be bound
to the stateful session bean. The dependency on the extended persistence context is declared by means
of the PersistenceContext annotation or persistence-context-ref deployment descriptor element.
The persistence context is closed by the container when the @Remove method of the stateful session
bean completes (or the stateful session bean instance is otherwise destroyed).
*/
closeEntityManagers(unregisteredEntityManagers);
}
return returnValue;
} finally {
ThreadContext.exit(oldCallContext);
}
}
use of javax.ejb.SessionBean in project tomee by apache.
the class SingletonInstanceManager method createInstance.
private Instance createInstance(final ThreadContext callContext, final BeanContext beanContext) throws ApplicationException {
try {
initializeDependencies(beanContext);
final InstanceContext context = beanContext.newInstance();
if (context.getBean() instanceof SessionBean) {
final Operation originalOperation = callContext.getCurrentOperation();
try {
callContext.setCurrentOperation(Operation.CREATE);
final Method create = beanContext.getCreateMethod();
final InterceptorStack ejbCreate = new InterceptorStack(context.getBean(), create, Operation.CREATE, new ArrayList<>(), new HashMap());
ejbCreate.invoke();
} finally {
callContext.setCurrentOperation(originalOperation);
}
}
final ReadWriteLock lock;
if (beanContext.isBeanManagedConcurrency()) {
// Bean-Managed Concurrency
lock = new BeanManagedLock();
} else {
// Container-Managed Concurrency
lock = new ReentrantReadWriteLock();
}
return new Instance(context.getBean(), context.getInterceptors(), context.getCreationalContext(), lock);
} catch (Throwable e) {
if (e instanceof InvocationTargetException) {
e = ((InvocationTargetException) e).getTargetException();
}
final String t = "The bean instance " + beanContext.getDeploymentID() + " threw a system exception:" + e;
logger.error(t, e);
throw new ApplicationException(new NoSuchEJBException("Singleton failed to initialize").initCause(e));
}
}
use of javax.ejb.SessionBean in project Payara by payara.
the class AsynchronousTask method createBeanInstance.
/**
* Create a new Session Bean and set Session Context.
*/
private SessionContextImpl createBeanInstance() throws Exception {
EjbInvocation ejbInv = null;
try {
SessionContextImpl context = (SessionContextImpl) createEjbInstanceAndContext();
Object ejb = context.getEJB();
Object sessionKey = uuidGenerator.createSessionKey();
createExtendedEMs(context, sessionKey);
// Need to do preInvoke because setSessionContext can access JNDI
ejbInv = super.createEjbInvocation(ejb, context);
invocationManager.preInvoke(ejbInv);
// the bean is not allowed to do EJBContext.getEJBObject here
if (ejb instanceof SessionBean) {
((SessionBean) ejb).setSessionContext(context);
}
// Perform injection right after where setSessionContext
// would be called. This is important since injection methods
// have the same "operations allowed" permissions as
// setSessionContext.
injectEjbInstance(context);
// Set the timestamp before inserting into bean store, else
// Recycler might go crazy and remove this bean!
context.touch();
// Add the EJB into the session store
// and get the instanceKey for this EJB instance.
// XXX The store operation could be avoided for local-only beans.
sessionBeanCache.put(sessionKey, context);
context.setInstanceKey(sessionKey);
_logger.log(FINE, () -> "[SFSBContainer] Created " + "session: " + sessionKey);
return context;
} catch (Exception ex) {
throw ex;
} catch (Throwable t) {
EJBException ejbEx = new EJBException();
ejbEx.initCause(t);
throw ejbEx;
} finally {
if (ejbInv != null) {
invocationManager.postInvoke(ejbInv);
}
}
}
Aggregations