use of org.apache.openejb.BeanContext in project tomee by apache.
the class EnterpriseBeanBuilder method build.
public BeanContext build() throws OpenEJBException {
Class ejbClass = loadClass(bean.ejbClass, "classNotFound.ejbClass");
if (DynamicSubclass.isDynamic(ejbClass)) {
ejbClass = DynamicSubclass.createSubclass(ejbClass, moduleContext.getClassLoader());
}
Class home = null;
Class remote = null;
if (bean.home != null) {
home = loadClass(bean.home, "classNotFound.home");
remote = loadClass(bean.remote, "classNotFound.remote");
}
Class<?> proxy = null;
if (bean.proxy != null) {
proxy = loadClass(bean.proxy, "classNotFound.proxy");
}
Class<?> localhome = null;
Class<?> local = null;
if (bean.localHome != null) {
localhome = loadClass(bean.localHome, "classNotFound.localHome");
local = loadClass(bean.local, "classNotFound.local");
}
final List<Class> businessLocals = new ArrayList<>();
for (final String businessLocal : bean.businessLocal) {
businessLocals.add(loadClass(businessLocal, "classNotFound.businessLocal"));
}
final List<Class> businessRemotes = new ArrayList<>();
for (final String businessRemote : bean.businessRemote) {
businessRemotes.add(loadClass(businessRemote, "classNotFound.businessRemote"));
}
Class serviceEndpoint = null;
if (BeanType.STATELESS == ejbType || BeanType.SINGLETON == ejbType) {
if (bean.serviceEndpoint != null) {
serviceEndpoint = loadClass(bean.serviceEndpoint, "classNotFound.sei");
}
}
Class primaryKey = null;
if (ejbType.isEntity() && ((EntityBeanInfo) bean).primKeyClass != null) {
final String className = ((EntityBeanInfo) bean).primKeyClass;
primaryKey = loadClass(className, "classNotFound.primaryKey");
}
final String transactionType = bean.transactionType;
// determine the injections
final InjectionBuilder injectionBuilder = new InjectionBuilder(moduleContext.getClassLoader());
final List<Injection> injections = injectionBuilder.buildInjections(bean.jndiEnc);
final Set<Class<?>> relevantClasses = new HashSet<>();
Class c = ejbClass;
do {
relevantClasses.add(c);
c = c.getSuperclass();
} while (c != null && c != Object.class);
for (final Injection injection : moduleInjections) {
if (relevantClasses.contains(injection.getTarget())) {
injections.add(injection);
}
}
// build the enc
final JndiEncBuilder jndiEncBuilder = new JndiEncBuilder(bean.jndiEnc, injections, transactionType, moduleContext.getId(), null, moduleContext.getUniqueId(), moduleContext.getClassLoader(), moduleContext.getAppContext() == null ? moduleContext.getProperties() : moduleContext.getAppContext().getProperties());
final Context compJndiContext = jndiEncBuilder.build(JndiEncBuilder.JndiScope.comp);
bind(compJndiContext, "module", moduleContext.getModuleJndiContext());
bind(compJndiContext, "app", moduleContext.getAppContext().getAppJndiContext());
bind(compJndiContext, "global", moduleContext.getAppContext().getGlobalJndiContext());
final BeanContext deployment;
if (BeanType.MESSAGE_DRIVEN != ejbType) {
deployment = new BeanContext(bean.ejbDeploymentId, compJndiContext, moduleContext, ejbClass, home, remote, localhome, local, proxy, serviceEndpoint, businessLocals, businessRemotes, primaryKey, ejbType, bean.localbean && ejbType.isSession(), bean.passivable);
if (bean instanceof ManagedBeanInfo) {
deployment.setHidden(((ManagedBeanInfo) bean).hidden);
}
} else {
final MessageDrivenBeanInfo messageDrivenBeanInfo = (MessageDrivenBeanInfo) bean;
final Class mdbInterface = loadClass(messageDrivenBeanInfo.mdbInterface, "classNotFound.mdbInterface");
deployment = new BeanContext(bean.ejbDeploymentId, compJndiContext, moduleContext, ejbClass, mdbInterface, messageDrivenBeanInfo.activationProperties);
deployment.setDestinationId(messageDrivenBeanInfo.destinationId);
}
deployment.getProperties().putAll(bean.properties);
deployment.setEjbName(bean.ejbName);
deployment.setRunAs(bean.runAs);
deployment.setRunAsUser(bean.runAsUser);
deployment.getInjections().addAll(injections);
// ejbTimeout
deployment.setEjbTimeout(getTimeout(ejbClass, bean.timeoutMethod));
if (bean.statefulTimeout != null) {
deployment.setStatefulTimeout(new Duration(bean.statefulTimeout.time, TimeUnit.valueOf(bean.statefulTimeout.unit)));
}
if (bean instanceof StatefulBeanInfo) {
final StatefulBeanInfo statefulBeanInfo = (StatefulBeanInfo) bean;
for (final InitMethodInfo init : statefulBeanInfo.initMethods) {
final Method beanMethod = MethodInfoUtil.toMethod(ejbClass, init.beanMethod);
final List<Method> methods = new ArrayList<>();
if (home != null) {
methods.addAll(Arrays.asList(home.getMethods()));
}
if (localhome != null) {
methods.addAll(Arrays.asList(localhome.getMethods()));
}
for (final Method homeMethod : methods) {
if (init.createMethod != null && !init.createMethod.methodName.equals(homeMethod.getName())) {
continue;
}
if (!homeMethod.getName().startsWith("create")) {
continue;
}
if (paramsMatch(beanMethod, homeMethod)) {
deployment.mapMethods(homeMethod, beanMethod);
}
}
}
for (final RemoveMethodInfo removeMethod : statefulBeanInfo.removeMethods) {
if (removeMethod.beanMethod.methodParams == null) {
final MethodInfo methodInfo = new MethodInfo();
methodInfo.methodName = removeMethod.beanMethod.methodName;
methodInfo.methodParams = removeMethod.beanMethod.methodParams;
methodInfo.className = removeMethod.beanMethod.className;
final List<Method> methods = MethodInfoUtil.matchingMethods(methodInfo, ejbClass);
for (final Method method : methods) {
deployment.getRemoveMethods().add(method);
deployment.setRetainIfExeption(method, removeMethod.retainIfException);
}
} else {
final Method method = MethodInfoUtil.toMethod(ejbClass, removeMethod.beanMethod);
deployment.getRemoveMethods().add(method);
deployment.setRetainIfExeption(method, removeMethod.retainIfException);
}
}
final Map<EntityManagerFactory, BeanContext.EntityManagerConfiguration> extendedEntityManagerFactories = new HashMap<>();
for (final PersistenceContextReferenceInfo info : statefulBeanInfo.jndiEnc.persistenceContextRefs) {
if (info.extended) {
try {
final ContainerSystem containerSystem = SystemInstance.get().getComponent(ContainerSystem.class);
final Object o = containerSystem.getJNDIContext().lookup(PersistenceBuilder.getOpenEJBJndiName(info.unitId));
final EntityManagerFactory emf = EntityManagerFactory.class.cast(o);
extendedEntityManagerFactories.put(emf, new BeanContext.EntityManagerConfiguration(info.properties, JtaEntityManager.isJPA21(emf) && info.synchronizationType != null ? SynchronizationType.valueOf(info.synchronizationType) : null));
} catch (final NamingException e) {
throw new OpenEJBException("PersistenceUnit '" + info.unitId + "' not found for EXTENDED ref '" + info.referenceName + "'");
}
}
}
deployment.setExtendedEntityManagerFactories(new Index<>(extendedEntityManagerFactories));
}
if (ejbType.isSession() || ejbType.isMessageDriven()) {
deployment.setBeanManagedTransaction("Bean".equalsIgnoreCase(bean.transactionType));
}
if (ejbType.isSession()) {
// Allow dependsOn to work for all session beans
deployment.getDependsOn().addAll(bean.dependsOn);
}
if (ejbType == BeanType.SINGLETON) {
deployment.setBeanManagedConcurrency("Bean".equalsIgnoreCase(bean.concurrencyType));
deployment.setLoadOnStartup(bean.loadOnStartup);
}
if (ejbType.isEntity()) {
final EntityBeanInfo entity = (EntityBeanInfo) bean;
deployment.setCmp2(entity.cmpVersion == 2);
deployment.setIsReentrant(entity.reentrant.equalsIgnoreCase("true"));
if (ejbType == BeanType.CMP_ENTITY) {
Class cmpImplClass = null;
final String cmpImplClassName = CmpUtil.getCmpImplClassName(entity.abstractSchemaName, entity.ejbClass);
cmpImplClass = loadClass(cmpImplClassName, "classNotFound.cmpImplClass");
deployment.setCmpImplClass(cmpImplClass);
deployment.setAbstractSchemaName(entity.abstractSchemaName);
for (final QueryInfo query : entity.queries) {
if (query.remoteResultType) {
final StringBuilder methodSignature = new StringBuilder();
methodSignature.append(query.method.methodName);
if (query.method.methodParams != null && !query.method.methodParams.isEmpty()) {
methodSignature.append('(');
boolean first = true;
for (final String methodParam : query.method.methodParams) {
if (!first) {
methodSignature.append(",");
}
methodSignature.append(methodParam);
first = false;
}
methodSignature.append(')');
}
deployment.setRemoteQueryResults(methodSignature.toString());
}
}
if (entity.primKeyField != null) {
deployment.setPrimaryKeyField(entity.primKeyField);
}
}
}
deployment.createMethodMap();
// we could directly check the matching bean method.
if (ejbType == BeanType.STATELESS || ejbType == BeanType.SINGLETON || ejbType == BeanType.STATEFUL) {
for (final NamedMethodInfo methodInfo : bean.asynchronous) {
final Method method = MethodInfoUtil.toMethod(ejbClass, methodInfo);
deployment.getMethodContext(deployment.getMatchingBeanMethod(method)).setAsynchronous(true);
}
for (final String className : bean.asynchronousClasses) {
deployment.getAsynchronousClasses().add(loadClass(className, "classNotFound.ejbClass"));
}
deployment.createAsynchronousMethodSet();
}
for (final SecurityRoleReferenceInfo securityRoleReference : bean.securityRoleReferences) {
deployment.addSecurityRoleReference(securityRoleReference.roleName, securityRoleReference.roleLink);
}
return deployment;
}
use of org.apache.openejb.BeanContext in project tomee by apache.
the class LazyEjbReference method getObject.
public Object getObject() throws NamingException {
if (reference != null) {
return reference.getObject();
}
final SystemInstance systemInstance = SystemInstance.get();
final EjbResolver resolver = systemInstance.getComponent(EjbResolver.class);
final String deploymentId = resolver.resolve(info, moduleUri);
if (deploymentId == null) {
String key = "lazyEjbRefNotResolved";
if (info.getHome() != null) {
key += ".home";
}
final String message = messages.format(key, info.getName(), info.getEjbLink(), info.getHome(), info.getInterface());
throw new NameNotFoundException(message);
}
final ContainerSystem containerSystem = systemInstance.getComponent(ContainerSystem.class);
final BeanContext beanContext = containerSystem.getBeanContext(deploymentId);
if (beanContext == null) {
final String message = messages.format("deploymentNotFound", info.getName(), deploymentId);
throw new NameNotFoundException(message);
}
InterfaceType type = null;
switch(info.getRefType()) {
case LOCAL:
type = InterfaceType.BUSINESS_LOCAL;
break;
case REMOTE:
type = InterfaceType.BUSINESS_REMOTE;
break;
}
final String jndiName = "openejb/Deployment/" + JndiBuilder.format(deploymentId, info.getInterface(), type);
if (useCrossClassLoaderRef && isRemote(beanContext)) {
reference = new CrossClassLoaderJndiReference(jndiName);
} else {
reference = new IntraVmJndiReference(jndiName);
}
return reference.getObject();
}
use of org.apache.openejb.BeanContext in project tomee by apache.
the class OpenEJBLifecycle method startApplication.
@Override
public void startApplication(final Object startupObject) {
if (ServletContextEvent.class.isInstance(startupObject)) {
// TODO: check it is relevant
startServletContext(ServletContext.class.cast(getServletContext(startupObject)));
return;
} else if (!StartupObject.class.isInstance(startupObject)) {
logger.debug("startupObject is not of StartupObject type; ignored");
return;
}
final StartupObject stuff = (StartupObject) startupObject;
final ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
// Initalize Application Context
logger.info("OpenWebBeans Container is starting...");
final long begin = System.currentTimeMillis();
try {
Thread.currentThread().setContextClassLoader(stuff.getClassLoader());
final AppContext appContext = stuff.getAppContext();
if (stuff.getWebContext() == null) {
// do it before any other things to keep our singleton finder working
appContext.setWebBeansContext(webBeansContext);
}
// Load all plugins
webBeansContext.getPluginLoader().startUp();
// Get Plugin
final CdiPlugin cdiPlugin = (CdiPlugin) webBeansContext.getPluginLoader().getEjbPlugin();
cdiPlugin.setClassLoader(stuff.getClassLoader());
cdiPlugin.setWebBeansContext(webBeansContext);
// Configure EJB Deployments
cdiPlugin.configureDeployments(stuff.getBeanContexts());
// Resournce Injection Service
final CdiResourceInjectionService injectionService = (CdiResourceInjectionService) webBeansContext.getService(ResourceInjectionService.class);
// todo use startupObject allDeployments to find Comp in priority (otherwise we can keep N times comps and loose time at injection time
injectionService.setAppContext(stuff.getAppContext(), stuff.getBeanContexts() != null ? stuff.getBeanContexts() : Collections.<BeanContext>emptyList());
// Deploy the beans
CdiScanner cdiScanner = null;
try {
// Scanning process
logger.debug("Scanning classpaths for beans artifacts.");
if (CdiScanner.class.isInstance(scannerService)) {
cdiScanner = CdiScanner.class.cast(scannerService);
cdiScanner.setContext(webBeansContext);
cdiScanner.init(startupObject);
} else {
cdiScanner = new CdiScanner();
cdiScanner.setContext(webBeansContext);
cdiScanner.init(startupObject);
}
// Scan
this.scannerService.scan();
// just to let us write custom CDI Extension using our internals easily
CURRENT_APP_INFO.set(stuff.getAppInfo());
// before next event which can register custom beans (JAX-RS)
addInternalBeans();
SystemInstance.get().fireEvent(new WebBeansContextBeforeDeploy(webBeansContext));
// Deploy bean from XML. Also configures deployments, interceptors, decorators.
deployer.deploy(scannerService);
// fire app event and also starts SingletonContext and ApplicationContext
contextsService.init(startupObject);
} catch (final Exception e1) {
SystemInstance.get().getComponent(Assembler.class).logger.error("CDI Beans module deployment failed", e1);
throw new OpenEJBRuntimeException(e1);
} finally {
CURRENT_APP_INFO.remove();
}
final Collection<Class<?>> ejbs = new ArrayList<>(stuff.getBeanContexts().size());
for (final BeanContext bc : stuff.getBeanContexts()) {
ejbs.add(bc.getManagedClass());
final CdiEjbBean cdiEjbBean = bc.get(CdiEjbBean.class);
if (cdiEjbBean == null) {
continue;
}
if (AbstractProducer.class.isInstance(cdiEjbBean)) {
AbstractProducer.class.cast(cdiEjbBean).defineInterceptorStack(cdiEjbBean, cdiEjbBean.getAnnotatedType(), cdiEjbBean.getWebBeansContext());
}
bc.mergeOWBAndOpenEJBInfo();
bc.set(InterceptorResolutionService.BeanInterceptorInfo.class, InjectionTargetImpl.class.cast(cdiEjbBean.getInjectionTarget()).getInterceptorInfo());
cdiEjbBean.initInternals();
}
// Start actual starting on sub-classes
if (beanManager instanceof WebappBeanManager) {
((WebappBeanManager) beanManager).afterStart();
}
for (final Class<?> clazz : cdiScanner.getStartupClasses()) {
if (ejbs.contains(clazz)) {
logger.debug("Skipping " + clazz.getName() + ", already registered as an EJB.");
continue;
}
starts(beanManager, clazz);
}
} finally {
Thread.currentThread().setContextClassLoader(oldCl);
// cleanup threadlocal used to enrich cdi context manually
OptimizedLoaderService.ADDITIONAL_EXTENSIONS.remove();
}
logger.info("OpenWebBeans Container has started, it took {0} ms.", Long.toString(System.currentTimeMillis() - begin));
}
use of org.apache.openejb.BeanContext 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<>(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<>();
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;
}
}
use of org.apache.openejb.BeanContext in project tomee by apache.
the class CdiPlugin method defineSessionBean.
@Override
public <T> Bean<T> defineSessionBean(final Class<T> clazz, final BeanAttributes<T> attributes, final AnnotatedType<T> annotatedType) {
final BeanContext bc = findBeanContext(webBeansContext, clazz);
final Class<?> superClass = bc.getManagedClass().getSuperclass();
if (annotatedType.isAnnotationPresent(Specializes.class)) {
if (superClass != Object.class && !isSessionBean(superClass)) {
throw new DefinitionException("You can only specialize another EJB: " + clazz);
}
final BeanContext parentBc = findBeanContext(webBeansContext, superClass);
final List<Class> businessLocalInterfaces = new ArrayList<>(parentBc.getBusinessLocalInterfaces());
for (final Class<?> api : bc.getBusinessLocalInterfaces()) {
businessLocalInterfaces.removeAll(GenericsUtil.getTypeClosure(api));
}
if (!businessLocalInterfaces.isEmpty()) {
throw new DefinitionException("You can only specialize another EJB with at least the same API: " + clazz);
}
}
final CdiEjbBean<T> bean = new OpenEJBBeanBuilder<>(bc, webBeansContext, annotatedType, attributes).createBean(clazz, !annotatedType.isAnnotationPresent(Vetoed.class));
bc.set(CdiEjbBean.class, bean);
bc.set(CurrentCreationalContext.class, new CurrentCreationalContext());
validateDisposeMethods(bean);
validateScope(bean);
final Set<ObserverMethod<?>> observerMethods;
if (bean.isEnabled()) {
observerMethods = new ObserverMethodsBuilder<>(webBeansContext, bean.getAnnotatedType()).defineObserverMethods(bean, true);
} else {
observerMethods = new HashSet<>();
}
final WebBeansUtil webBeansUtil = webBeansContext.getWebBeansUtil();
final Set<ProducerFieldBean<?>> producerFields = new ProducerFieldBeansBuilder(bean.getWebBeansContext(), bean.getAnnotatedType()).defineProducerFields(bean);
final Set<ProducerMethodBean<?>> producerMethods = new ProducerMethodBeansBuilder(bean.getWebBeansContext(), bean.getAnnotatedType()).defineProducerMethods(bean, producerFields);
final Map<ProducerMethodBean<?>, AnnotatedMethod<?>> annotatedMethods = new HashMap<>();
for (final ProducerMethodBean<?> producerMethod : producerMethods) {
final AnnotatedMethod<?> method = webBeansContext.getAnnotatedElementFactory().newAnnotatedMethod(producerMethod.getCreatorMethod(), annotatedType);
webBeansUtil.inspectDeploymentErrorStack("There are errors that are added by ProcessProducer event observers for " + "ProducerMethods. Look at logs for further details");
annotatedMethods.put(producerMethod, method);
}
final Map<ProducerFieldBean<?>, AnnotatedField<?>> annotatedFields = new HashMap<>();
for (final ProducerFieldBean<?> producerField : producerFields) {
if (!Modifier.isStatic(producerField.getCreatorField().getModifiers())) {
throw new DefinitionException("In an EJB all producer fields should be static");
}
webBeansUtil.inspectDeploymentErrorStack("There are errors that are added by ProcessProducer event observers for" + " ProducerFields. Look at logs for further details");
annotatedFields.put(producerField, webBeansContext.getAnnotatedElementFactory().newAnnotatedField(producerField.getCreatorField(), webBeansContext.getAnnotatedElementFactory().newAnnotatedType(producerField.getBeanClass())));
}
final Map<ObserverMethod<?>, AnnotatedMethod<?>> observerMethodsMap = new HashMap<>();
for (final ObserverMethod<?> observerMethod : observerMethods) {
final ObserverMethodImpl<?> impl = (ObserverMethodImpl<?>) observerMethod;
final AnnotatedMethod<?> method = impl.getObserverMethod();
observerMethodsMap.put(observerMethod, method);
}
validateProduceMethods(bean, producerMethods);
validateObserverMethods(bean, observerMethodsMap);
final BeanManagerImpl beanManager = webBeansContext.getBeanManagerImpl();
// Fires ProcessManagedBean
final GProcessSessionBean event = new GProcessSessionBean(Bean.class.cast(bean), annotatedType, bc.getEjbName(), bean.getEjbType());
beanManager.fireEvent(event, true);
event.setStarted();
webBeansUtil.inspectDeploymentErrorStack("There are errors that are added by ProcessSessionBean event observers for managed beans. Look at logs for further details");
// Fires ProcessProducerMethod
webBeansUtil.fireProcessProducerMethodBeanEvent(annotatedMethods, annotatedType);
webBeansUtil.inspectDeploymentErrorStack("There are errors that are added by ProcessProducerMethod event observers for producer method beans. Look at logs for further details");
// Fires ProcessProducerField
webBeansUtil.fireProcessProducerFieldBeanEvent(annotatedFields);
webBeansUtil.inspectDeploymentErrorStack("There are errors that are added by ProcessProducerField event observers for producer field beans. Look at logs for further details");
if (!webBeansUtil.isAnnotatedTypeDecoratorOrInterceptor(annotatedType)) {
for (final ProducerMethodBean<?> producerMethod : producerMethods) {
beanManager.addBean(producerMethod);
}
for (final ProducerFieldBean<?> producerField : producerFields) {
beanManager.addBean(producerField);
}
}
beanManager.addBean(bean);
return bean;
}
Aggregations