use of org.apache.openejb.BeanContext in project tomee by apache.
the class TomcatWebAppBuilder method startInternal.
/**
* {@inheritDoc}
*/
// @Override
private void startInternal(final StandardContext standardContext) {
if (isIgnored(standardContext)) {
return;
}
if (shouldNotDeploy(standardContext)) {
return;
}
final CoreContainerSystem cs = getContainerSystem();
final Assembler a = getAssembler();
if (a == null) {
LOGGER.warning("OpenEJB has not been initialized so war will not be scanned for nested modules " + standardContext.getPath());
return;
}
AppContext appContext = null;
// Look for context info, maybe context is already scanned
ContextInfo contextInfo = getContextInfo(standardContext);
ClassLoader classLoader = standardContext.getLoader().getClassLoader();
// bind jta before the app starts to ensure we have it in CDI
final Thread thread = Thread.currentThread();
final ClassLoader originalLoader = thread.getContextClassLoader();
thread.setContextClassLoader(classLoader);
final String listenerName = standardContext.getNamingContextListener().getName();
ContextAccessController.setWritable(listenerName, standardContext.getNamingToken());
try {
final Context comp = Context.class.cast(ContextBindings.getClassLoader().lookup("comp"));
// bind TransactionManager
final TransactionManager transactionManager = SystemInstance.get().getComponent(TransactionManager.class);
safeBind(comp, "TransactionManager", transactionManager);
// bind TransactionSynchronizationRegistry
final TransactionSynchronizationRegistry synchronizationRegistry = SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class);
safeBind(comp, "TransactionSynchronizationRegistry", synchronizationRegistry);
} catch (final NamingException e) {
// no-op
} finally {
thread.setContextClassLoader(originalLoader);
ContextAccessController.setReadOnly(listenerName);
}
if (contextInfo == null) {
final AppModule appModule = loadApplication(standardContext);
appModule.getProperties().put("loader.from", "tomcat");
final boolean skipTomeeResourceWrapping = !"true".equalsIgnoreCase(SystemInstance.get().getProperty("tomee.tomcat.resource.wrap", "true"));
if (!skipTomeeResourceWrapping && OpenEJBNamingResource.class.isInstance(standardContext.getNamingResources())) {
// we can get the same resource twice as in tomcat
final Collection<String> importedNames = new ArrayList<>();
// add them to the app as resource
final boolean forceDataSourceWrapping = "true".equalsIgnoreCase(SystemInstance.get().getProperty("tomee.tomcat.datasource.wrap", "false"));
final OpenEJBNamingResource nr = (OpenEJBNamingResource) standardContext.getNamingResources();
for (final ResourceBase resource : nr.getTomcatResources()) {
final String name = resource.getName();
// already init (org.apache.catalina.core.NamingContextListener.addResource())
// skip wrapping to ensure resource consistency
final boolean isDataSource = DataSource.class.getName().equals(resource.getType());
final boolean isAlreadyCreated = ContextResource.class.isInstance(resource) && ContextResource.class.cast(resource).getSingleton() && isDataSource;
if (!importedNames.contains(name)) {
importedNames.add(name);
} else {
continue;
}
boolean found = false;
for (final ResourceInfo r : SystemInstance.get().getComponent(OpenEjbConfiguration.class).facilities.resources) {
if (r.id.equals(name)) {
nr.removeResource(name);
found = true;
LOGGER.warning(name + " resource was defined in both tomcat and tomee so removing tomcat one");
break;
}
}
if (!found) {
final Resource newResource;
if (forceDataSourceWrapping || (!isAlreadyCreated && isDataSource)) {
// we forward it to TomEE datasources
newResource = new Resource(name, resource.getType());
boolean jta = false;
final Properties properties = newResource.getProperties();
final Iterator<String> params = resource.listProperties();
while (params.hasNext()) {
final String paramName = params.next();
final String paramValue = (String) resource.getProperty(paramName);
// handling some param name conversion to OpenEJB style
if ("driverClassName".equals(paramName)) {
properties.setProperty("JdbcDriver", paramValue);
} else if ("url".equals(paramName)) {
properties.setProperty("JdbcUrl", paramValue);
} else {
properties.setProperty(paramName, paramValue);
}
if ("JtaManaged".equalsIgnoreCase(paramName)) {
jta = Boolean.parseBoolean(paramValue);
}
}
if (!jta) {
properties.setProperty("JtaManaged", "false");
}
} else {
// custom type, let it be created
newResource = new Resource(name, resource.getType(), "org.apache.tomee:ProvidedByTomcat");
final Properties properties = newResource.getProperties();
properties.setProperty("jndiName", newResource.getId());
properties.setProperty("appName", getId(standardContext));
properties.setProperty("factory", (String) resource.getProperty("factory"));
final Reference reference = createReference(resource);
if (reference != null) {
properties.put("reference", reference);
}
}
appModule.getResources().add(newResource);
}
}
}
if (appModule != null) {
try {
contextInfo = addContextInfo(Contexts.getHostname(standardContext), standardContext);
// ensure to do it before an exception can be thrown
contextInfo.standardContext = standardContext;
contextInfo.appInfo = configurationFactory.configureApplication(appModule);
final Boolean autoDeploy = DeployerEjb.AUTO_DEPLOY.get();
contextInfo.appInfo.autoDeploy = autoDeploy == null || autoDeploy;
DeployerEjb.AUTO_DEPLOY.remove();
if (!appModule.isWebapp()) {
classLoader = appModule.getClassLoader();
} else {
final ClassLoader loader = standardContext.getLoader().getClassLoader();
if (loader instanceof TomEEWebappClassLoader) {
final TomEEWebappClassLoader tomEEWebappClassLoader = (TomEEWebappClassLoader) loader;
for (final URL url : appModule.getWebModules().iterator().next().getAddedUrls()) {
tomEEWebappClassLoader.addURL(url);
}
}
}
setFinderOnContextConfig(standardContext, appModule);
servletContextHandler.getContexts().put(classLoader, standardContext.getServletContext());
try {
appContext = a.createApplication(contextInfo.appInfo, classLoader);
} finally {
servletContextHandler.getContexts().remove(classLoader);
}
// todo add watched resources to context
eagerInitOfLocalBeanProxies(appContext.getBeanContexts(), classLoader);
} catch (final Exception e) {
LOGGER.error("Unable to deploy collapsed ear in war " + standardContext, e);
undeploy(standardContext, contextInfo);
// just to force tomee to start without EE part
if (System.getProperty(TomEESystemConfig.TOMEE_EAT_EXCEPTION_PROP) == null) {
final TomEERuntimeException tre = new TomEERuntimeException(e);
final DeploymentExceptionManager dem = SystemInstance.get().getComponent(DeploymentExceptionManager.class);
dem.saveDeploymentException(contextInfo.appInfo, tre);
throw tre;
}
return;
}
}
} else {
contextInfo.standardContext = standardContext;
if (contextInfo.module != null && contextInfo.module.getFinder() != null) {
// TODO: make it more explicit or less hacky not using properties
final OpenEJBContextConfig openEJBContextConfig = findOpenEJBContextConfig(standardContext);
if (openEJBContextConfig != null) {
openEJBContextConfig.finder(contextInfo.module.getFinder(), contextInfo.module.getClassLoader());
}
}
}
final String id = getId(standardContext);
WebAppInfo webAppInfo = null;
// appInfo is null when deployment fails
if (contextInfo.appInfo != null) {
for (final WebAppInfo w : contextInfo.appInfo.webApps) {
if (id.equals(getId(w.host, w.contextRoot, contextInfo.version)) || id.equals(getId(w.host, w.moduleId, contextInfo.version))) {
if (webAppInfo == null) {
webAppInfo = w;
} else if (w.host != null && w.host.equals(Contexts.getHostname(standardContext))) {
webAppInfo = w;
}
break;
}
}
if (appContext == null) {
appContext = cs.getAppContext(contextInfo.appInfo.appId);
}
}
if (webAppInfo != null) {
if (appContext == null) {
appContext = getContainerSystem().getAppContext(contextInfo.appInfo.appId);
}
// ensure matching (see getId() usage)
webAppInfo.host = Contexts.getHostname(standardContext);
webAppInfo.contextRoot = standardContext.getPath();
// save jsf stuff
final Map<String, Set<String>> scannedJsfClasses = new HashMap<>();
for (final ClassListInfo info : webAppInfo.jsfAnnotatedClasses) {
scannedJsfClasses.put(info.name, info.list);
}
jsfClasses.put(classLoader, scannedJsfClasses);
try {
// determine the injections
final Set<Injection> injections = new HashSet<>();
injections.addAll(appContext.getInjections());
if (!contextInfo.appInfo.webAppAlone) {
updateInjections(injections, classLoader, false);
for (final BeanContext bean : appContext.getBeanContexts()) {
// TODO: how if the same class in multiple webapps?
updateInjections(bean.getInjections(), classLoader, true);
}
}
injections.addAll(new InjectionBuilder(classLoader).buildInjections(webAppInfo.jndiEnc));
// merge OpenEJB jndi into Tomcat jndi
final TomcatJndiBuilder jndiBuilder = new TomcatJndiBuilder(standardContext, webAppInfo, injections);
NamingUtil.setCurrentContext(standardContext);
try {
jndiBuilder.mergeJndi();
} finally {
NamingUtil.setCurrentContext(null);
}
// create EMF included in this webapp when nested in an ear
for (final PersistenceUnitInfo unitInfo : contextInfo.appInfo.persistenceUnits) {
if (unitInfo.webappName != null && unitInfo.webappName.equals(webAppInfo.moduleId)) {
try {
final ReloadableEntityManagerFactory remf = (ReloadableEntityManagerFactory) SystemInstance.get().getComponent(ContainerSystem.class).getJNDIContext().lookup(Assembler.PERSISTENCE_UNIT_NAMING_CONTEXT + unitInfo.id);
remf.overrideClassLoader(classLoader);
remf.createDelegate();
} catch (final NameNotFoundException nnfe) {
LOGGER.warning("Can't find " + unitInfo.id + " persistence unit");
}
}
}
// add WebDeploymentInfo to ContainerSystem
final WebContext webContext = new WebContext(appContext);
webContext.setServletContext(standardContext.getServletContext());
webContext.setJndiEnc(new InitialContext());
webContext.setClassLoader(classLoader);
webContext.setId(webAppInfo.moduleId);
webContext.setContextRoot(webAppInfo.contextRoot);
webContext.setHost(webAppInfo.host);
webContext.setBindings(new HashMap<String, Object>());
webContext.getInjections().addAll(injections);
appContext.getWebContexts().add(webContext);
cs.addWebContext(webContext);
standardContext.getServletContext().setAttribute("openejb.web.context", webContext);
if (!contextInfo.appInfo.webAppAlone) {
final List<BeanContext> beanContexts = assembler.initEjbs(classLoader, contextInfo.appInfo, appContext, injections, new ArrayList<BeanContext>(), webAppInfo.moduleId);
OpenEJBLifecycle.CURRENT_APP_INFO.set(contextInfo.appInfo);
servletContextHandler.getContexts().put(classLoader, standardContext.getServletContext());
try {
new CdiBuilder().build(contextInfo.appInfo, appContext, beanContexts, webContext);
} catch (final Exception e) {
final DeploymentExceptionManager dem = SystemInstance.get().getComponent(DeploymentExceptionManager.class);
if (dem != null) {
dem.saveDeploymentException(contextInfo.appInfo, e);
}
throw e;
} finally {
servletContextHandler.getContexts().remove(classLoader);
OpenEJBLifecycle.CURRENT_APP_INFO.remove();
}
assembler.startEjbs(true, beanContexts);
assembler.bindGlobals(appContext.getBindings());
eagerInitOfLocalBeanProxies(beanContexts, standardContext.getLoader().getClassLoader());
deployWebServicesIfEjbCreatedHere(contextInfo.appInfo, beanContexts);
}
// jndi bindings
webContext.getBindings().putAll(appContext.getBindings());
webContext.getBindings().putAll(getJndiBuilder(classLoader, webAppInfo, injections, appContext.getProperties()).buildBindings(JndiEncBuilder.JndiScope.comp));
final JavaeeInstanceManager instanceManager = new JavaeeInstanceManager(standardContext, webContext);
standardContext.setInstanceManager(instanceManager);
instanceManagers.put(classLoader, instanceManager);
standardContext.getServletContext().setAttribute(InstanceManager.class.getName(), standardContext.getInstanceManager());
} catch (final Exception e) {
LOGGER.error("Error merging Java EE JNDI entries in to war " + standardContext.getPath() + ": Exception: " + e.getMessage(), e);
if (System.getProperty(TomEESystemConfig.TOMEE_EAT_EXCEPTION_PROP) == null) {
final DeploymentExceptionManager dem = SystemInstance.get().getComponent(DeploymentExceptionManager.class);
if (dem != null && dem.getDeploymentException(contextInfo.appInfo) != null) {
if (RuntimeException.class.isInstance(e)) {
throw RuntimeException.class.cast(e);
}
throw new TomEERuntimeException(e);
}
}
}
final WebBeansContext webBeansContext = appContext.getWebBeansContext();
if (webBeansContext != null && webBeansContext.getBeanManagerImpl().isInUse()) {
OpenEJBLifecycle.initializeServletContext(standardContext.getServletContext(), webBeansContext);
}
}
// router
final URL routerConfig = RouterValve.configurationURL(standardContext.getServletContext());
if (routerConfig != null) {
final RouterValve filter = new RouterValve();
filter.setPrefix(standardContext.getName());
filter.setConfigurationPath(routerConfig);
standardContext.getPipeline().addValve(filter);
}
// register realm to have it in TomcatSecurityService
final Realm realm = standardContext.getRealm();
realms.put(standardContext.getName(), realm);
}
use of org.apache.openejb.BeanContext in project tomee by apache.
the class ApplicationComposers method deployApp.
public void deployApp(final Object inputTestInstance) throws Exception {
final ClassFinder testClassFinder = fixFakeClassFinder(inputTestInstance);
final ClassLoader loader = testClass.getClassLoader();
AppModule appModule = new AppModule(loader, testClass.getSimpleName());
// Add the test case as an @ManagedBean
final ManagedBean testBean;
{
final EjbJar ejbJar = new EjbJar();
final OpenejbJar openejbJar = new OpenejbJar();
testBean = ejbJar.addEnterpriseBean(new ManagedBean(testClass.getSimpleName(), testClass.getName(), true));
testBean.localBean();
testBean.setTransactionType(TransactionType.BEAN);
final EjbDeployment ejbDeployment = openejbJar.addEjbDeployment(testBean);
ejbDeployment.setDeploymentId(testClass.getName());
final EjbModule ejbModule = new EjbModule(ejbJar, openejbJar);
ejbModule.getProperties().setProperty("openejb.cdi.activated", "false");
final FinderFactory.OpenEJBAnnotationFinder finder = new FinderFactory.OpenEJBAnnotationFinder(new ClassesArchive(ancestors(testClass)));
ejbModule.setFinder(finder);
if (finder.findMetaAnnotatedFields(Inject.class).size() + finder.findMetaAnnotatedMethods(Inject.class).size() > 0) {
// "activate" cdi to avoid WARNINGs
ejbModule.setBeans(new Beans());
}
appModule.getEjbModules().add(ejbModule);
}
final Map<String, URL> additionalDescriptors = descriptorsToMap(testClass.getAnnotation(org.apache.openejb.junit.Descriptors.class));
final Map<String, URL> additionalDescriptorsNew = descriptorsToMap(testClass.getAnnotation(Descriptors.class));
additionalDescriptors.putAll(additionalDescriptorsNew);
Application application = null;
int webModulesNb = 0;
final Jars globalJarsAnnotation = testClass.getAnnotation(Jars.class);
// Invoke the @Module producer methods to build out the AppModule
int moduleNumber = 0;
// we dont consider resources.xml to set an app as standalone or not
int notBusinessModuleNumber = 0;
final Map<Object, List<Method>> moduleMethods = new HashMap<>();
findAnnotatedMethods(moduleMethods, Module.class);
findAnnotatedMethods(moduleMethods, org.apache.openejb.junit.Module.class);
for (final Map.Entry<Object, List<Method>> methods : moduleMethods.entrySet()) {
moduleNumber += methods.getValue().size();
for (final Method method : methods.getValue()) {
final Object obj = method.invoke(methods.getKey());
final Jars jarsAnnotation = method.getAnnotation(Jars.class);
final Classes classesAnnotation = method.getAnnotation(Classes.class);
final org.apache.openejb.junit.Classes classesAnnotationOld = method.getAnnotation(org.apache.openejb.junit.Classes.class);
final boolean defaultConfig = method.getAnnotation(Default.class) != null;
Class<?>[] classes = null;
String[] excludes = null;
Class<?>[] cdiInterceptors = null;
Class<?>[] cdiAlternatives = null;
Class<?>[] cdiStereotypes = null;
Class<?>[] cdiDecorators = null;
boolean cdi = false;
boolean innerClassesAsBean = false;
if (classesAnnotation != null) {
classes = classesAnnotation.value();
excludes = classesAnnotation.excludes();
innerClassesAsBean = classesAnnotation.innerClassesAsBean();
cdiInterceptors = classesAnnotation.cdiInterceptors();
cdiDecorators = classesAnnotation.cdiDecorators();
cdiAlternatives = classesAnnotation.cdiAlternatives();
cdiStereotypes = classesAnnotation.cdiStereotypes();
cdi = isCdi(classesAnnotation.cdi(), cdiInterceptors, cdiAlternatives, cdiStereotypes, cdiDecorators);
} else if (classesAnnotationOld != null) {
classes = classesAnnotationOld.value();
}
if (obj instanceof WebApp) {
// will add the ejbmodule too
final WebApp webApp = WebApp.class.cast(obj);
if (webApp.getContextRoot() == null && classesAnnotation != null) {
webApp.contextRoot(classesAnnotation.context());
}
webModulesNb++;
addWebApp(appModule, testBean, additionalDescriptors, method.getAnnotation(Descriptors.class), method.getAnnotation(JaxrsProviders.class), webApp, globalJarsAnnotation, jarsAnnotation, classes, excludes, cdiInterceptors, cdiAlternatives, cdiDecorators, cdiStereotypes, cdi, innerClassesAsBean, defaultConfig);
} else if (obj instanceof WebModule) {
// will add the ejbmodule too
webModulesNb++;
final WebModule webModule = (WebModule) obj;
webModule.getAltDDs().putAll(additionalDescriptors);
webModule.getAltDDs().putAll(descriptorsToMap(method.getAnnotation(Descriptors.class)));
final EjbModule ejbModule = DeploymentLoader.addWebModule(webModule, appModule);
ejbModule.getProperties().put(CdiScanner.OPENEJB_CDI_FILTER_CLASSLOADER, "false");
if (cdi) {
ejbModule.setBeans(beans(new Beans(), cdiDecorators, cdiInterceptors, cdiAlternatives, cdiStereotypes));
}
Collection<File> files = findFiles(jarsAnnotation);
if (defaultConfig) {
(files == null ? files = new LinkedList<>() : files).add(jarLocation(testClass));
}
webModule.setFinder(finderFromClasses(webModule, classes, files, excludes));
ejbModule.setFinder(webModule.getFinder());
} else if (obj instanceof EjbModule) {
final EjbModule ejbModule = (EjbModule) obj;
ejbModule.getAltDDs().putAll(additionalDescriptors);
ejbModule.getAltDDs().putAll(descriptorsToMap(method.getAnnotation(Descriptors.class)));
ejbModule.initAppModule(appModule);
appModule.getEjbModules().add(ejbModule);
if (cdi) {
ejbModule.setBeans(beans(new Beans(), cdiDecorators, cdiInterceptors, cdiAlternatives, cdiStereotypes));
}
Collection<File> files = findFiles(jarsAnnotation);
if (defaultConfig) {
(files == null ? files = new LinkedList<>() : files).add(jarLocation(testClass));
}
ejbModule.setFinder(finderFromClasses(ejbModule, classes, files, excludes));
} else if (obj instanceof EjbJar) {
final EjbJar ejbJar = (EjbJar) obj;
setId(ejbJar, method);
final EjbModule ejbModule = new EjbModule(ejbJar);
ejbModule.getAltDDs().putAll(additionalDescriptors);
ejbModule.getAltDDs().putAll(descriptorsToMap(method.getAnnotation(Descriptors.class)));
appModule.getEjbModules().add(ejbModule);
if (cdi) {
ejbModule.setBeans(beans(new Beans(), cdiDecorators, cdiInterceptors, cdiAlternatives, cdiStereotypes));
}
Collection<File> files = findFiles(jarsAnnotation);
if (defaultConfig) {
(files == null ? files = new LinkedList<>() : files).add(jarLocation(testClass));
}
ejbModule.setFinder(finderFromClasses(ejbModule, classes, files, excludes));
} else if (obj instanceof EnterpriseBean) {
final EnterpriseBean bean = (EnterpriseBean) obj;
final EjbJar ejbJar = new EjbJar(method.getName());
ejbJar.addEnterpriseBean(bean);
final EjbModule ejbModule = new EjbModule(ejbJar);
final Beans beans = new Beans();
beans.addManagedClass(bean.getEjbClass());
ejbModule.setBeans(beans);
appModule.getEjbModules().add(ejbModule);
if (cdi) {
ejbModule.setBeans(beans(new Beans(), cdiDecorators, cdiInterceptors, cdiAlternatives, cdiStereotypes));
}
Collection<File> files = findFiles(jarsAnnotation);
if (defaultConfig) {
(files == null ? files = new LinkedList<>() : files).add(jarLocation(testClass));
}
ejbModule.setFinder(finderFromClasses(ejbModule, classes, files, excludes));
} else if (obj instanceof Application) {
application = (Application) obj;
setId(application, method);
} else if (obj instanceof Connector) {
final Connector connector = (Connector) obj;
setId(connector, method);
appModule.getConnectorModules().add(new ConnectorModule(connector));
} else if (obj instanceof Persistence) {
final Persistence persistence = (Persistence) obj;
appModule.addPersistenceModule(new PersistenceModule(appModule, implicitRootUrl(method.getAnnotation(PersistenceRootUrl.class)), persistence));
notBusinessModuleNumber++;
} else if (obj instanceof PersistenceUnit) {
final PersistenceUnit unit = (PersistenceUnit) obj;
appModule.addPersistenceModule(new PersistenceModule(appModule, implicitRootUrl(method.getAnnotation(PersistenceRootUrl.class)), new Persistence(unit)));
notBusinessModuleNumber++;
} else if (obj instanceof Beans) {
final Beans beans = (Beans) obj;
final EjbModule ejbModule = new EjbModule(new EjbJar(method.getName()));
ejbModule.setBeans(beans);
appModule.getEjbModules().add(ejbModule);
if (cdi) {
ejbModule.setBeans(beans(beans, cdiDecorators, cdiInterceptors, cdiAlternatives, cdiStereotypes));
}
Collection<File> files = findFiles(jarsAnnotation);
if (defaultConfig) {
(files == null ? files = new LinkedList<>() : files).add(jarLocation(testClass));
}
ejbModule.setFinder(finderFromClasses(ejbModule, classes, files, excludes));
} else if (obj instanceof Class[]) {
final Class[] beans = (Class[]) obj;
final EjbModule ejbModule = new EjbModule(new EjbJar(method.getName()));
ejbModule.setFinder(new AnnotationFinder(new ClassesArchive(beans)).link());
ejbModule.setBeans(new Beans());
appModule.getEjbModules().add(ejbModule);
} else if (obj instanceof Class) {
final Class bean = (Class) obj;
final EjbModule ejbModule = new EjbModule(new EjbJar(method.getName()));
ejbModule.setFinder(new AnnotationFinder(new ClassesArchive(bean)).link());
ejbModule.setBeans(new Beans());
appModule.getEjbModules().add(ejbModule);
} else if (obj instanceof IAnnotationFinder) {
final EjbModule ejbModule = new EjbModule(new EjbJar(method.getName()));
ejbModule.setFinder((IAnnotationFinder) obj);
ejbModule.setBeans(new Beans());
appModule.getEjbModules().add(ejbModule);
} else if (obj instanceof ClassesArchive) {
final EjbModule ejbModule = new EjbModule(new EjbJar(method.getName()));
ejbModule.setFinder(new AnnotationFinder((Archive) obj).link());
ejbModule.setBeans(new Beans());
appModule.getEjbModules().add(ejbModule);
} else if (obj instanceof Resources) {
final Resources asResources = Resources.class.cast(obj);
appModule.getResources().addAll(asResources.getResource());
appModule.getContainers().addAll(asResources.getContainer());
notBusinessModuleNumber++;
} else if (obj instanceof AppModule) {
// we can probably go further here
final AppModule module = (AppModule) obj;
module.getAltDDs().putAll(additionalDescriptors);
module.getAltDDs().putAll(descriptorsToMap(method.getAnnotation(Descriptors.class)));
if (module.getWebModules().size() > 0) {
webModulesNb++;
}
appModule.getEjbModules().addAll(module.getEjbModules());
appModule.getPersistenceModules().addAll(module.getPersistenceModules());
appModule.getAdditionalLibMbeans().addAll(module.getAdditionalLibMbeans());
appModule.getWebModules().addAll(module.getWebModules());
appModule.getConnectorModules().addAll(module.getConnectorModules());
appModule.getResources().addAll(module.getResources());
appModule.getServices().addAll(module.getServices());
appModule.getPojoConfigurations().putAll(module.getPojoConfigurations());
appModule.getAdditionalLibraries().addAll(module.getAdditionalLibraries());
appModule.getAltDDs().putAll(module.getAltDDs());
appModule.getProperties().putAll(module.getProperties());
} else {
moduleNumber--;
}
}
}
final Classes classClasses = testClass.getAnnotation(Classes.class);
if (classClasses != null) {
final WebApp webapp = new WebApp();
webapp.setContextRoot(classClasses.context());
addWebApp(appModule, testBean, additionalDescriptors, null, null, webapp, globalJarsAnnotation, null, classClasses.value(), classClasses.excludes(), classClasses.cdiInterceptors(), classClasses.cdiAlternatives(), classClasses.cdiDecorators(), classClasses.cdiStereotypes(), classClasses.cdi(), classClasses.innerClassesAsBean(), testClass.getAnnotation(Default.class) != null);
webModulesNb++;
moduleNumber++;
}
// Application is final in AppModule, which is fine, so we'll create a new one and move everything
if (application != null) {
final AppModule newModule = new AppModule(appModule.getClassLoader(), appModule.getModuleId(), application, false);
newModule.getClientModules().addAll(appModule.getClientModules());
newModule.addPersistenceModules(appModule.getPersistenceModules());
newModule.getEjbModules().addAll(appModule.getEjbModules());
newModule.getConnectorModules().addAll(appModule.getConnectorModules());
appModule = newModule;
}
// config for the app
for (final Map.Entry<Object, List<Method>> method : findAnnotatedMethods(new HashMap<>(), ApplicationConfiguration.class).entrySet()) {
for (final Method m : method.getValue()) {
final Object o = m.invoke(method.getKey());
if (Properties.class.isInstance(o)) {
appModule.getProperties().putAll(Properties.class.cast(o));
}
}
}
// copy ejb into beans if cdi is activated and init finder
for (final EjbModule ejb : appModule.getEjbModules()) {
final EnterpriseBean[] enterpriseBeans = ejb.getEjbJar().getEnterpriseBeans();
final Beans beans = ejb.getBeans();
if (beans != null && ejb.getEjbJar() != null) {
for (final EnterpriseBean bean : enterpriseBeans) {
boolean found = false;
for (final List<String> mc : beans.getManagedClasses().values()) {
if (mc.contains(bean.getEjbClass())) {
found = true;
break;
}
}
if (!found) {
beans.addManagedClass(bean.getEjbClass());
}
}
}
}
if (moduleNumber - notBusinessModuleNumber == 1 && webModulesNb == 1) {
appModule.setStandloneWebModule();
}
if (webModulesNb > 0 && SystemInstance.get().getComponent(WebAppBuilder.class) == null) {
SystemInstance.get().setComponent(WebAppBuilder.class, new LightweightWebAppBuilder());
}
final Context jndiContext = SystemInstance.get().getComponent(ContainerSystem.class).getJNDIContext();
for (final EnvEntry entry : testBean.getEnvEntry()) {
// set it in global jndi context since that's "app" entries and otherwise when we are no more in test bean context lookup fails
final String name = entry.getName();
final String jndi;
if (name.startsWith("java:") || name.startsWith("comp/env")) {
jndi = name;
} else {
jndi = "java:comp/env/" + name;
}
jndiContext.bind(jndi, entry.getEnvEntryValue());
}
appInfo = SystemInstance.get().getComponent(ConfigurationFactory.class).configureApplication(appModule);
appContext = assembler.createApplication(appInfo);
if (mockCdiContexts() && appContext.getWebBeansContext() != null) {
ScopeHelper.startContexts(appContext.getWebBeansContext().getContextsService(), servletContext, session);
}
final BeanContext context = SystemInstance.get().getComponent(ContainerSystem.class).getBeanContext(testClass.getName());
enrich(inputTestInstance, context);
JavaSecurityManagers.setSystemProperty(Context.INITIAL_CONTEXT_FACTORY, InitContextFactory.class.getName());
JavaSecurityManagers.setSystemProperty(OPENEJB_APPLICATION_COMPOSER_CONTEXT, appContext.getGlobalJndiContext());
final List<Field> fields = new ArrayList<>(testClassFinder.findAnnotatedFields(AppResource.class));
fields.addAll(testClassFinder.findAnnotatedFields(org.apache.openejb.junit.AppResource.class));
for (final Field field : fields) {
final Class<?> type = field.getType();
if (AppModule.class.isAssignableFrom(type)) {
field.setAccessible(true);
field.set(inputTestInstance, appModule);
} else if (Context.class.isAssignableFrom(type)) {
field.setAccessible(true);
field.set(inputTestInstance, new InitialContext(new Properties() {
{
setProperty(Context.INITIAL_CONTEXT_FACTORY, LocalInitialContextFactory.class.getName());
}
}));
} else if (ApplicationComposers.class.isAssignableFrom(type)) {
field.setAccessible(true);
field.set(inputTestInstance, this);
} else if (ContextProvider.class.isAssignableFrom(type)) {
RESTResourceFinder finder = SystemInstance.get().getComponent(RESTResourceFinder.class);
if (finder == null || !ContextProvider.class.isInstance(finder)) {
finder = new ContextProvider(finder);
SystemInstance.get().setComponent(RESTResourceFinder.class, finder);
}
field.setAccessible(true);
field.set(inputTestInstance, finder);
} else {
throw new IllegalArgumentException("can't find value for type " + type.getName());
}
}
previous = ThreadContext.enter(new ThreadContext(context, null, Operation.BUSINESS));
// switch back since next test will use another instance
testClassFinders.put(this, testClassFinder);
}
use of org.apache.openejb.BeanContext in project tomee by apache.
the class ModulePropertiesTest method assertContexts.
private void assertContexts(final ContainerSystem containerSystem) {
final BeanContext beanContext = containerSystem.getBeanContext("WidgetBean");
final ModuleContext moduleContext = beanContext.getModuleContext();
final AppContext appContext = moduleContext.getAppContext();
{
// Assert as Properties
// ModuleContext should have color property
assertProperty(moduleContext.getProperties(), "color", "orange");
// BeanContext and AppContext should not
assertNoProperty(beanContext.getProperties(), "color");
assertNoProperty(appContext.getProperties(), "color");
// Try all the above again with mixed case
assertProperty(moduleContext.getProperties(), "coLOr", "orange");
assertNoProperty(beanContext.getProperties(), "coLOr");
assertNoProperty(appContext.getProperties(), "coLOr");
}
{
// Assert as Options
// ModuleContext should have color option
assertOption(moduleContext.getOptions(), "color", "orange");
// BeanContext should inherit ModuleContext color
assertOption(beanContext.getOptions(), "color", "orange");
// AppContext should remain unpolluted
assertNoOption(appContext.getOptions(), "color");
// Try all the above again using mixed case
assertOption(moduleContext.getOptions(), "coLoR", "orange");
assertOption(beanContext.getOptions(), "coLoR", "orange");
assertNoOption(appContext.getOptions(), "coLoR");
}
}
use of org.apache.openejb.BeanContext in project tomee by apache.
the class MdbInstanceManager method discardInstance.
/**
* This method is called to release the semaphore in case of the business method
* throwing a system exception
*
* @param callContext ThreadContext
* @param bean Object
*/
public void discardInstance(final ThreadContext callContext, final Object bean) throws SystemException {
if (bean == null) {
throw new SystemException("Invalid arguments");
}
final Instance instance = Instance.class.cast(bean);
final BeanContext beanContext = callContext.getBeanContext();
final Data data = (Data) beanContext.getContainerData();
if (null != data) {
final Pool<Instance> pool = data.getPool();
pool.discard(instance.getPoolEntry());
}
}
use of org.apache.openejb.BeanContext in project tomee by apache.
the class MdbInstanceManager method freeInstance.
@SuppressWarnings("unchecked")
private void freeInstance(final ThreadContext callContext, final Instance instance) {
try {
callContext.setCurrentOperation(Operation.PRE_DESTROY);
final BeanContext beanContext = callContext.getBeanContext();
final Method remove = instance.bean instanceof SessionBean ? removeSessionBeanMethod : null;
final List<InterceptorData> callbackInterceptors = beanContext.getCallbackInterceptors();
final InterceptorStack interceptorStack = new InterceptorStack(instance.bean, remove, Operation.PRE_DESTROY, callbackInterceptors, instance.interceptors);
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 re) {
logger.error("The bean instance " + instance + " threw a system exception:" + re, re);
}
}
Aggregations