use of org.apache.openejb.ProxyInfo in project tomee by apache.
the class EntityContainer method createEJBObject.
protected ProxyInfo createEJBObject(final Method callMethod, final Object[] args, final ThreadContext callContext, final InterfaceType type) throws OpenEJBException {
final BeanContext beanContext = callContext.getBeanContext();
callContext.setCurrentOperation(Operation.CREATE);
/*
* According to section 9.1.5.1 of the EJB 1.1 specification, the "ejbPostCreate(...)
* method executes in the same transaction context as the previous ejbCreate(...) method."
*
* For this reason the TransactionScopeHandler methods usally preformed by the invoke( )
* operation must be handled here along with the call explicitly.
* This ensures that the afterInvoke() is not processed between the ejbCreate and ejbPostCreate methods to
* ensure that the ejbPostCreate executes in the same transaction context of the ejbCreate.
* This would otherwise not be possible if container-managed transactions were used because
* the TransactionScopeManager would attempt to commit the transaction immediately after the ejbCreate
* and before the ejbPostCreate had a chance to execute. Once the ejbPostCreate method execute the
* super classes afterInvoke( ) method will be executed committing the transaction if its a CMT.
*/
final TransactionPolicy txPolicy = createTransactionPolicy(beanContext.getTransactionType(callMethod, type), callContext);
EntityBean bean = null;
Object primaryKey = null;
try {
// Get new ready instance
bean = instanceManager.obtainInstance(callContext);
// Obtain the proper ejbCreate() method
final Method ejbCreateMethod = beanContext.getMatchingBeanMethod(callMethod);
// invoke the ejbCreate which returns the primary key
primaryKey = ejbCreateMethod.invoke(bean, args);
didCreateBean(callContext, bean);
// determine post create callback method
final Method ejbPostCreateMethod = beanContext.getMatchingPostCreateMethod(ejbCreateMethod);
// create a new context containing the pk for the post create call
final ThreadContext postCreateContext = new ThreadContext(beanContext, primaryKey);
postCreateContext.setCurrentOperation(Operation.POST_CREATE);
final ThreadContext oldContext = ThreadContext.enter(postCreateContext);
try {
// Invoke the ejbPostCreate method on the bean instance
ejbPostCreateMethod.invoke(bean, args);
// According to section 9.1.5.1 of the EJB 1.1 specification, the "ejbPostCreate(...)
// method executes in the same transaction context as the previous ejbCreate(...) method."
//
// The bean is first insterted using db.create( ) and then after ejbPostCreate( ) its
// updated using db.update(). This protocol allows for visablity of the bean after ejbCreate
// within the current trasnaction.
} finally {
ThreadContext.exit(oldContext);
}
// update pool
instanceManager.poolInstance(callContext, bean, primaryKey);
} catch (final Throwable e) {
handleException(txPolicy, e, callContext, bean);
} finally {
afterInvoke(txPolicy, callContext);
}
return new ProxyInfo(beanContext, primaryKey);
}
use of org.apache.openejb.ProxyInfo in project tomee by apache.
the class EntityContainer method findMethod.
protected Object findMethod(final Method callMethod, final Object[] args, final ThreadContext callContext, final InterfaceType type) throws OpenEJBException {
final BeanContext beanContext = callContext.getBeanContext();
callContext.setCurrentOperation(Operation.FIND);
final Method runMethod = beanContext.getMatchingBeanMethod(callMethod);
Object returnValue = invoke(type, callMethod, runMethod, args, callContext);
/*
* Find operations return either a single primary key or a collection of primary keys.
* The primary keys are converted to ProxyInfo objects.
*/
if (returnValue instanceof Collection) {
final Iterator keys = ((Collection) returnValue).iterator();
final Vector<ProxyInfo> proxies = new Vector<>();
while (keys.hasNext()) {
final Object primaryKey = keys.next();
proxies.addElement(new ProxyInfo(beanContext, primaryKey));
}
returnValue = proxies;
} else if (returnValue instanceof Enumeration) {
final Enumeration keys = (Enumeration) returnValue;
final Vector<ProxyInfo> proxies = new Vector<>();
while (keys.hasMoreElements()) {
final Object primaryKey = keys.nextElement();
proxies.addElement(new ProxyInfo(beanContext, primaryKey));
}
returnValue = new ArrayEnumeration<>(proxies);
} else {
returnValue = new ProxyInfo(beanContext, returnValue);
}
return returnValue;
}
use of org.apache.openejb.ProxyInfo 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<>();
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");
}
use of org.apache.openejb.ProxyInfo in project tomee by apache.
the class StatefulContainer method createEJBObject.
protected ProxyInfo createEJBObject(final BeanContext beanContext, final Method callMethod, final Object[] args, final InterfaceType interfaceType) throws OpenEJBException {
// generate a new primary key
final Object primaryKey = newPrimaryKey();
final ThreadContext createContext = new ThreadContext(beanContext, primaryKey);
final ThreadContext oldCallContext = ThreadContext.enter(createContext);
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(createContext, beanContext, oldBc);
}
}
// Security check
checkAuthorization(callMethod, interfaceType);
// Create the extended entity managers for this instance
final Index<EntityManagerFactory, JtaEntityManagerRegistry.EntityManagerTracker> entityManagers = createEntityManagers(beanContext);
// Register the newly created entity managers
if (entityManagers != null) {
try {
entityManagerRegistry.addEntityManagers((String) beanContext.getDeploymentID(), primaryKey, entityManagers);
} catch (final EntityManagerAlreadyRegisteredException e) {
throw new EJBException(e);
}
}
createContext.setCurrentOperation(Operation.CREATE);
createContext.setCurrentAllowedStates(null);
// Start transaction
final TransactionPolicy txPolicy = EjbTransactionUtil.createTransactionPolicy(createContext.getBeanContext().getTransactionType(callMethod, interfaceType), createContext);
Instance instance = null;
try {
try {
final InstanceContext context = beanContext.newInstance();
// Wrap-up everthing into a object
instance = new Instance(beanContext, primaryKey, containerID, context.getBean(), context.getCreationalContext(), context.getInterceptors(), entityManagers, lockFactory.newLock(primaryKey.toString()));
} catch (final Throwable throwable) {
final ThreadContext callContext = ThreadContext.getThreadContext();
EjbTransactionUtil.handleSystemException(callContext.getTransactionPolicy(), throwable, callContext);
// should never be reached
throw new IllegalStateException(throwable);
}
// add to cache
if (isPassivable(beanContext)) {
// no need to cache it it will never expires
cache.add(primaryKey, instance);
}
// instance starts checked-out
checkedOutInstances.put(primaryKey, instance);
// Register for synchronization callbacks
registerSessionSynchronization(instance, createContext);
// Invoke create for legacy beans
if (!callMethod.getDeclaringClass().equals(BeanContext.BusinessLocalHome.class) && !callMethod.getDeclaringClass().equals(BeanContext.BusinessRemoteHome.class) && !callMethod.getDeclaringClass().equals(BeanContext.BusinessLocalBeanHome.class)) {
// Setup for business invocation
final Method createOrInit = beanContext.getMatchingBeanMethod(callMethod);
createContext.set(Method.class, createOrInit);
// Initialize interceptor stack
final InterceptorStack interceptorStack = new InterceptorStack(instance.bean, createOrInit, Operation.CREATE, new ArrayList<>(), new HashMap<>());
// Invoke
if (args == null) {
interceptorStack.invoke();
} else {
interceptorStack.invoke(args);
}
}
} catch (final Throwable e) {
handleException(createContext, txPolicy, e);
} finally {
// un register EntityManager
unregisterEntityManagers(instance, createContext);
afterInvoke(createContext, txPolicy, instance);
}
return new ProxyInfo(beanContext, primaryKey);
} finally {
if (runAs != null) {
try {
securityService.associate(runAs);
} catch (final LoginException e) {
// no-op
}
}
ThreadContext.exit(oldCallContext);
}
}
use of org.apache.openejb.ProxyInfo in project tomee by apache.
the class JndiRequestHandler method doLookup.
private void doLookup(final JNDIRequest req, final JNDIResponse res, final String prefix) {
Object object;
final String name = req.getRequestString();
try {
if (name.equals("info/injections")) {
// noinspection unchecked
final List<Injection> injections = (List<Injection>) rootContext.lookup(prefix + name);
final InjectionMetaData metaData = new InjectionMetaData();
for (final Injection injection : injections) {
if (injection.getTarget() == null) {
continue;
}
metaData.addInjection(injection.getTarget().getName(), injection.getName(), injection.getJndiName());
}
res.setResponseCode(ResponseCodes.JNDI_INJECTIONS);
res.setResult(metaData);
return;
} else {
try {
object = rootContext.lookup(prefix + name);
} catch (NameNotFoundException nnfe) {
// fallback to resources
object = rootContext.lookup("openejb/Resource/" + name);
}
}
if (object instanceof Context) {
res.setResponseCode(ResponseCodes.JNDI_CONTEXT);
return;
} else if (object == null) {
throw new NullPointerException("lookup of '" + name + "' returned null");
} else if (object instanceof DataSource) {
if (DataSourceFactory.knows(object)) {
try {
final DbcpDataSource cf = new DbcpDataSource(object);
final DataSourceMetaData dataSourceMetaData = new DataSourceMetaData(cf.getDriverClassName(), cf.getUrl(), cf.getUsername(), cf.getPassword());
res.setResponseCode(ResponseCodes.JNDI_DATA_SOURCE);
res.setResult(dataSourceMetaData);
} catch (Exception e) {
res.setResponseCode(ResponseCodes.JNDI_ERROR);
res.setResult(new ThrowableArtifact(e));
}
return;
} else if (object instanceof Referenceable) {
res.setResponseCode(ResponseCodes.JNDI_REFERENCE);
res.setResult(((Referenceable) object).getReference());
return;
}
} else if (object instanceof ConnectionFactory) {
res.setResponseCode(ResponseCodes.JNDI_RESOURCE);
res.setResult(ConnectionFactory.class.getName());
return;
} else if (ORB_CLASS != null && ORB_CLASS.isInstance(object)) {
res.setResponseCode(ResponseCodes.JNDI_RESOURCE);
res.setResult(ORB_CLASS.getName());
return;
} else if (object instanceof ValidatorFactory) {
res.setResponseCode(ResponseCodes.JNDI_RESOURCE);
res.setResult(ValidatorFactory.class.getName());
return;
} else if (object instanceof Validator) {
res.setResponseCode(ResponseCodes.JNDI_RESOURCE);
res.setResult(Validator.class.getName());
return;
} else if (object instanceof Queue) {
res.setResponseCode(ResponseCodes.JNDI_RESOURCE);
res.setResult(Queue.class.getName());
return;
} else if (object instanceof Topic) {
res.setResponseCode(ResponseCodes.JNDI_RESOURCE);
res.setResult(Topic.class.getName());
return;
}
final ServiceRefData serviceRef;
if (object instanceof ServiceRefData) {
serviceRef = (ServiceRefData) object;
} else {
serviceRef = ServiceRefData.getServiceRefData(object);
}
if (serviceRef != null) {
final WsMetaData serviceMetaData = new WsMetaData();
// service class
String serviceClassName = null;
if (serviceRef.getServiceClass() != null) {
serviceClassName = serviceRef.getServiceClass().getName();
}
serviceMetaData.setServiceClassName(serviceClassName);
// reference class
String referenceClassName = null;
if (serviceRef.getReferenceClass() != null) {
referenceClassName = serviceRef.getReferenceClass().getName();
}
serviceMetaData.setReferenceClassName(referenceClassName);
// set service qname
if (serviceRef.getServiceQName() != null) {
serviceMetaData.setServiceQName(serviceRef.getServiceQName().toString());
}
// get the port addresses for this service
final PortAddressRegistry portAddressRegistry = SystemInstance.get().getComponent(PortAddressRegistry.class);
Set<PortAddress> portAddresses = null;
if (portAddressRegistry != null) {
portAddresses = portAddressRegistry.getPorts(serviceRef.getId(), serviceRef.getServiceQName(), referenceClassName);
}
// resolve the wsdl url
if (serviceRef.getWsdlURL() != null) {
serviceMetaData.setWsdlUrl(serviceRef.getWsdlURL().toExternalForm());
}
if (portAddresses.size() == 1) {
final PortAddress portAddress = portAddresses.iterator().next();
serviceMetaData.setWsdlUrl(portAddress.getAddress() + "?wsdl");
}
// add handler chains
for (final HandlerChainData handlerChain : serviceRef.getHandlerChains()) {
final HandlerChainMetaData handlerChainMetaData = new HandlerChainMetaData();
handlerChainMetaData.setServiceNamePattern(handlerChain.getServiceNamePattern());
handlerChainMetaData.setPortNamePattern(handlerChain.getPortNamePattern());
handlerChainMetaData.getProtocolBindings().addAll(handlerChain.getProtocolBindings());
for (final HandlerData handler : handlerChain.getHandlers()) {
final HandlerMetaData handlerMetaData = new HandlerMetaData();
handlerMetaData.setHandlerClass(handler.getHandlerClass().getName());
for (final Method method : handler.getPostConstruct()) {
final CallbackMetaData callbackMetaData = new CallbackMetaData();
callbackMetaData.setClassName(method.getDeclaringClass().getName());
callbackMetaData.setMethod(method.getName());
handlerMetaData.getPostConstruct().add(callbackMetaData);
}
for (final Method method : handler.getPreDestroy()) {
final CallbackMetaData callbackMetaData = new CallbackMetaData();
callbackMetaData.setClassName(method.getDeclaringClass().getName());
callbackMetaData.setMethod(method.getName());
handlerMetaData.getPreDestroy().add(callbackMetaData);
}
handlerChainMetaData.getHandlers().add(handlerMetaData);
}
serviceMetaData.getHandlerChains().add(handlerChainMetaData);
}
// add port refs
final Map<QName, PortRefMetaData> portsByQName = new HashMap<>();
for (final PortRefData portRef : serviceRef.getPortRefs()) {
final PortRefMetaData portRefMetaData = new PortRefMetaData();
portRefMetaData.setQName(portRef.getQName());
portRefMetaData.setServiceEndpointInterface(portRef.getServiceEndpointInterface());
portRefMetaData.setEnableMtom(portRef.isEnableMtom());
portRefMetaData.getProperties().putAll(portRef.getProperties());
portRefMetaData.getAddresses().addAll(portRef.getAddresses());
if (portRef.getQName() != null) {
portsByQName.put(portRef.getQName(), portRefMetaData);
}
serviceMetaData.getPortRefs().add(portRefMetaData);
}
// add PortRefMetaData for any portAddress not added above
for (final PortAddress portAddress : portAddresses) {
PortRefMetaData portRefMetaData = portsByQName.get(portAddress.getPortQName());
if (portRefMetaData == null) {
portRefMetaData = new PortRefMetaData();
portRefMetaData.setQName(portAddress.getPortQName());
portRefMetaData.setServiceEndpointInterface(portAddress.getServiceEndpointInterface());
portRefMetaData.getAddresses().add(portAddress.getAddress());
serviceMetaData.getPortRefs().add(portRefMetaData);
} else {
portRefMetaData.getAddresses().add(portAddress.getAddress());
if (portRefMetaData.getServiceEndpointInterface() == null) {
portRefMetaData.setServiceEndpointInterface(portAddress.getServiceEndpointInterface());
}
}
}
res.setResponseCode(ResponseCodes.JNDI_WEBSERVICE);
res.setResult(serviceMetaData);
return;
}
} catch (NameNotFoundException e) {
res.setResponseCode(ResponseCodes.JNDI_NOT_FOUND);
return;
} catch (NamingException e) {
res.setResponseCode(ResponseCodes.JNDI_NAMING_EXCEPTION);
res.setResult(new ThrowableArtifact(e));
return;
}
BaseEjbProxyHandler handler;
try {
handler = (BaseEjbProxyHandler) ProxyManager.getInvocationHandler(object);
} catch (Exception e) {
try {
final Field field = object.getClass().getDeclaredField("invocationHandler");
field.setAccessible(true);
handler = (BaseEjbProxyHandler) field.get(object);
} catch (Exception e1) {
// Not a proxy. See if it's serializable and send it
if (object instanceof java.io.Serializable) {
res.setResponseCode(ResponseCodes.JNDI_OK);
res.setResult(object);
return;
} else {
res.setResponseCode(ResponseCodes.JNDI_NAMING_EXCEPTION);
final NamingException namingException = new NamingException("Expected an ejb proxy, found unknown object: type=" + object.getClass().getName() + ", toString=" + object);
res.setResult(new ThrowableArtifact(namingException));
return;
}
}
}
final ProxyInfo proxyInfo = handler.getProxyInfo();
final BeanContext beanContext = proxyInfo.getBeanContext();
final String deploymentID = beanContext.getDeploymentID().toString();
updateServer(req, res, proxyInfo);
switch(proxyInfo.getInterfaceType()) {
case EJB_HOME:
{
res.setResponseCode(ResponseCodes.JNDI_EJBHOME);
final EJBMetaDataImpl metaData = new EJBMetaDataImpl(beanContext.getHomeInterface(), beanContext.getRemoteInterface(), beanContext.getPrimaryKeyClass(), beanContext.getComponentType().toString(), deploymentID, -1, convert(proxyInfo.getInterfaceType()), null, beanContext.getAsynchronousMethodSignatures());
metaData.loadProperties(beanContext.getProperties());
log(metaData);
res.setResult(metaData);
break;
}
case EJB_LOCAL_HOME:
{
res.setResponseCode(ResponseCodes.JNDI_NAMING_EXCEPTION);
final NamingException namingException = new NamingException("Not remotable: '" + name + "'. EJBLocalHome interfaces are not remotable as per the EJB specification.");
res.setResult(new ThrowableArtifact(namingException));
break;
}
case BUSINESS_REMOTE:
{
res.setResponseCode(ResponseCodes.JNDI_BUSINESS_OBJECT);
final EJBMetaDataImpl metaData = new EJBMetaDataImpl(null, null, beanContext.getPrimaryKeyClass(), beanContext.getComponentType().toString(), deploymentID, -1, convert(proxyInfo.getInterfaceType()), proxyInfo.getInterfaces(), beanContext.getAsynchronousMethodSignatures());
metaData.setPrimaryKey(proxyInfo.getPrimaryKey());
metaData.loadProperties(beanContext.getProperties());
log(metaData);
res.setResult(metaData);
break;
}
case BUSINESS_LOCAL:
{
res.setResponseCode(ResponseCodes.JNDI_NAMING_EXCEPTION);
final NamingException namingException = new NamingException("Not remotable: '" + name + "'. Business Local interfaces are not remotable as per the EJB specification. To disable this restriction, set the system property 'openejb.remotable.businessLocals=true' in the server.");
res.setResult(new ThrowableArtifact(namingException));
break;
}
case LOCALBEAN:
{
res.setResponseCode(ResponseCodes.JNDI_NAMING_EXCEPTION);
final NamingException namingException = new NamingException("Not remotable: '" + name + "'. LocalBean classes are not remotable as per the EJB specification.");
res.setResult(new ThrowableArtifact(namingException));
break;
}
default:
{
res.setResponseCode(ResponseCodes.JNDI_NAMING_EXCEPTION);
final NamingException namingException = new NamingException("Not remotable: '" + name + "'.");
res.setResult(new ThrowableArtifact(namingException));
}
}
}
Aggregations