use of org.apache.openejb.BeanContext in project tomee by apache.
the class OpenEJBDeployableContainer method deploy.
@Override
public ProtocolMetaData deploy(final Archive<?> archive) throws DeploymentException {
final DeploymentInfo info;
try {
final Closeables cl = new Closeables();
closeablesProducer.set(cl);
info = quickDeploy(archive, testClass.get(), cl);
// container rules (CDI) which is not the case with this solution
if (archive.getName().endsWith(".war")) {
final List<BeanContext> beanContexts = info.appCtx.getBeanContexts();
if (beanContexts.size() > 1) {
final Iterator<BeanContext> it = beanContexts.iterator();
while (it.hasNext()) {
final BeanContext next = it.next();
if (ModuleTestContext.class.isInstance(next.getModuleContext()) && BeanContext.Comp.class != next.getBeanClass()) {
for (final BeanContext b : beanContexts) {
if (b.getModuleContext() != next.getModuleContext()) {
ModuleTestContext.class.cast(next.getModuleContext()).setModuleJndiContextOverride(b.getModuleContext().getModuleJndiContext());
break;
}
}
break;
}
}
}
}
servletContextProducer.set(info.appServletContext);
sessionProducer.set(info.appSession);
appInfoProducer.set(info.appInfo);
appContextProducer.set(info.appCtx);
final ClassLoader loader = info.appCtx.getWebContexts().isEmpty() ? info.appCtx.getClassLoader() : info.appCtx.getWebContexts().iterator().next().getClassLoader();
final ClassLoader classLoader = loader == null ? info.appCtx.getClassLoader() : loader;
TestObserver.ClassLoaders classLoaders = this.classLoader.get();
if (classLoaders == null) {
classLoaders = new TestObserver.ClassLoaders();
this.classLoader.set(classLoaders);
}
classLoaders.register(archive.getName(), classLoader);
} catch (final Exception e) {
throw new DeploymentException("can't deploy " + archive.getName(), e);
}
// if service manager is started allow @ArquillianResource URL injection
if (PROPERTIES.containsKey(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE)) {
final ProtocolMetaData metaData = ServiceManagers.protocolMetaData(appInfoProducer.get());
HTTPContext http = null;
for (final WebAppInfo webapp : info.appInfo.webApps) {
for (final ServletInfo servletInfo : webapp.servlets) {
if (http == null) {
http = HTTPContext.class.cast(metaData.getContexts().iterator().next());
http.add(new Servlet(servletInfo.servletName, webapp.contextRoot));
}
}
for (final ClassListInfo classListInfo : webapp.webAnnotatedClasses) {
for (final String path : classListInfo.list) {
if (!path.contains("!")) {
continue;
}
if (http == null) {
http = HTTPContext.class.cast(metaData.getContexts().iterator().next());
}
http.add(new Servlet(path.substring(path.lastIndexOf('!') + 2).replace(".class", "").replace("/", "."), webapp.contextRoot));
}
}
}
if (metaData != null) {
return metaData;
}
}
return new ProtocolMetaData();
}
use of org.apache.openejb.BeanContext in project tomee by apache.
the class OpenEJBEnricher method enrich.
public static void enrich(final Object testInstance, final AppContext appCtx) {
// don't rely on arquillian since this enrichment should absolutely be done before the following ones
new MockitoEnricher().enrich(testInstance);
AppContext ctx = appCtx;
if (ctx == null) {
ctx = AppFinder.findAppContextOrWeb(Thread.currentThread().getContextClassLoader(), AppFinder.AppContextTransformer.INSTANCE);
if (ctx == null) {
return;
}
}
final BeanContext context = SystemInstance.get().getComponent(ContainerSystem.class).getBeanContext(ctx.getId() + "_" + testInstance.getClass().getName());
final WebBeansContext appWBC = ctx.getWebBeansContext();
final BeanManagerImpl bm = appWBC == null ? null : appWBC.getBeanManagerImpl();
boolean ok = false;
for (final WebContext web : ctx.getWebContexts()) {
final WebBeansContext webBeansContext = web.getWebBeansContext();
if (webBeansContext == null) {
continue;
}
final BeanManagerImpl webAppBm = webBeansContext.getBeanManagerImpl();
if (webBeansContext != appWBC && webAppBm.isInUse()) {
try {
doInject(testInstance, context, webAppBm);
ok = true;
break;
} catch (final Exception e) {
// no-op, try next
}
}
}
if (bm != null && bm.isInUse() && !ok) {
try {
doInject(testInstance, context, bm);
} catch (final Exception e) {
LOGGER.log(Level.SEVERE, "Failed injection on: " + testInstance.getClass(), e);
if (RuntimeException.class.isInstance(e)) {
throw RuntimeException.class.cast(e);
}
throw new OpenEJBRuntimeException(e);
}
}
if (context != null) {
final ThreadContext callContext = new ThreadContext(context, null, Operation.INJECTION);
final ThreadContext oldContext = ThreadContext.enter(callContext);
try {
final InjectionProcessor processor = new InjectionProcessor<>(testInstance, context.getInjections(), context.getJndiContext());
processor.createInstance();
} catch (final OpenEJBException e) {
// ignored
} finally {
ThreadContext.exit(oldContext);
}
}
}
use of org.apache.openejb.BeanContext in project tomee by apache.
the class TomEEInjectionEnricher method getAppContext.
private AppContext getAppContext(final Class<?> clazz) {
final String clazzName = clazz.getName();
final ContainerSystem containerSystem = SystemInstance.get().getComponent(ContainerSystem.class);
if (deployment != null && deployment.get() != null) {
final BeanContext context = containerSystem.getBeanContext(deployment.get().getDescription().getName() + "_" + clazzName);
if (context != null) {
return context.getModuleContext().getAppContext();
}
}
final List<AppContext> appContexts = containerSystem.getAppContexts();
final ClassLoader loader = clazz.getClassLoader();
for (final AppContext app : appContexts) {
final BeanContext context = containerSystem.getBeanContext(app.getId() + "_" + clazzName);
if (context != null) {
// in embedded mode we have deployment so we dont go here were AppLoader would just be everywhere
if (context.getBeanClass().getClassLoader() == loader) {
return app;
}
}
}
if (deployment != null && deployment.get() != null && deployment.get().getDescription().testable() && !isJunitComponent(clazz)) /*app context will be found by classloader, no need to log anything there*/
{
Logger.getLogger(TomEEInjectionEnricher.class.getName()).log(Level.WARNING, "Failed to find AppContext for: " + clazzName);
}
return null;
}
use of org.apache.openejb.BeanContext in project tomee by apache.
the class Assembler method initEjbs.
public List<BeanContext> initEjbs(final ClassLoader classLoader, final AppInfo appInfo, final AppContext appContext, final Set<Injection> injections, final List<BeanContext> allDeployments, final String webappId) throws OpenEJBException {
final String globalTimersOn = SystemInstance.get().getProperty(OPENEJB_TIMERS_ON, "true");
final EjbJarBuilder ejbJarBuilder = new EjbJarBuilder(props, appContext);
for (final EjbJarInfo ejbJar : appInfo.ejbJars) {
if (isSkip(appInfo, webappId, ejbJar)) {
continue;
}
final HashMap<String, BeanContext> deployments = ejbJarBuilder.build(ejbJar, injections, classLoader);
final JaccPermissionsBuilder jaccPermissionsBuilder = new JaccPermissionsBuilder();
final PolicyContext policyContext = jaccPermissionsBuilder.build(ejbJar, deployments);
jaccPermissionsBuilder.install(policyContext);
final TransactionPolicyFactory transactionPolicyFactory = createTransactionPolicyFactory(ejbJar, classLoader);
for (final BeanContext beanContext : deployments.values()) {
beanContext.setTransactionPolicyFactory(transactionPolicyFactory);
}
final MethodTransactionBuilder methodTransactionBuilder = new MethodTransactionBuilder();
methodTransactionBuilder.build(deployments, ejbJar.methodTransactions);
final MethodConcurrencyBuilder methodConcurrencyBuilder = new MethodConcurrencyBuilder();
methodConcurrencyBuilder.build(deployments, ejbJar.methodConcurrency);
for (final BeanContext beanContext : deployments.values()) {
containerSystem.addDeployment(beanContext);
}
// bind ejbs into global jndi
jndiBuilder.build(ejbJar, deployments);
// setup timers/asynchronous methods - must be after transaction attributes are set
for (final BeanContext beanContext : deployments.values()) {
if (beanContext.getComponentType() != BeanType.STATEFUL) {
final Method ejbTimeout = beanContext.getEjbTimeout();
boolean timerServiceRequired = false;
if (ejbTimeout != null) {
// If user set the tx attribute to RequiresNew change it to Required so a new transaction is not started
if (beanContext.getTransactionType(ejbTimeout) == TransactionType.RequiresNew) {
beanContext.setMethodTransactionAttribute(ejbTimeout, TransactionType.Required);
}
timerServiceRequired = true;
}
for (final Iterator<Map.Entry<Method, MethodContext>> it = beanContext.iteratorMethodContext(); it.hasNext(); ) {
final Map.Entry<Method, MethodContext> entry = it.next();
final MethodContext methodContext = entry.getValue();
if (methodContext.getSchedules().size() > 0) {
timerServiceRequired = true;
final Method method = entry.getKey();
// TODO Need ?
if (beanContext.getTransactionType(method) == TransactionType.RequiresNew) {
beanContext.setMethodTransactionAttribute(method, TransactionType.Required);
}
}
}
if (timerServiceRequired && "true".equalsIgnoreCase(appInfo.properties.getProperty(OPENEJB_TIMERS_ON, globalTimersOn))) {
// Create the timer
final EjbTimerServiceImpl timerService = new EjbTimerServiceImpl(beanContext, newTimerStore(beanContext));
// Load auto-start timers
final TimerStore timerStore = timerService.getTimerStore();
for (final Iterator<Map.Entry<Method, MethodContext>> it = beanContext.iteratorMethodContext(); it.hasNext(); ) {
final Map.Entry<Method, MethodContext> entry = it.next();
final MethodContext methodContext = entry.getValue();
for (final ScheduleData scheduleData : methodContext.getSchedules()) {
timerStore.createCalendarTimer(timerService, (String) beanContext.getDeploymentID(), null, entry.getKey(), scheduleData.getExpression(), scheduleData.getConfig(), true);
}
}
beanContext.setEjbTimerService(timerService);
} else {
beanContext.setEjbTimerService(new NullEjbTimerServiceImpl());
}
}
// TODO ???
for (final Iterator<Entry<Method, MethodContext>> it = beanContext.iteratorMethodContext(); it.hasNext(); ) {
final Entry<Method, MethodContext> entry = it.next();
if (entry.getValue().isAsynchronous() && beanContext.getTransactionType(entry.getKey()) == TransactionType.RequiresNew) {
beanContext.setMethodTransactionAttribute(entry.getKey(), TransactionType.Required);
}
}
// if local bean or mdb generate proxy class now to avoid bottleneck on classloader later
if (beanContext.isLocalbean() && !beanContext.getComponentType().isMessageDriven() && !beanContext.isDynamicallyImplemented()) {
final List<Class> interfaces = new ArrayList<>(3);
interfaces.add(Serializable.class);
interfaces.add(IntraVmProxy.class);
final BeanType type = beanContext.getComponentType();
if (BeanType.STATEFUL.equals(type) || BeanType.MANAGED.equals(type)) {
interfaces.add(BeanContext.Removable.class);
}
beanContext.set(BeanContext.ProxyClass.class, new BeanContext.ProxyClass(beanContext, interfaces.toArray(new Class<?>[interfaces.size()])));
}
}
// process application exceptions
for (final ApplicationExceptionInfo exceptionInfo : ejbJar.applicationException) {
try {
final Class exceptionClass = classLoader.loadClass(exceptionInfo.exceptionClass);
for (final BeanContext beanContext : deployments.values()) {
beanContext.addApplicationException(exceptionClass, exceptionInfo.rollback, exceptionInfo.inherited);
}
} catch (final ClassNotFoundException e) {
logger.error("createApplication.invalidClass", e, exceptionInfo.exceptionClass, e.getMessage());
}
}
allDeployments.addAll(deployments.values());
}
final List<BeanContext> ejbs = sort(allDeployments);
for (final BeanContext b : ejbs) {
// otherwise for ears we have duplicated beans
if (appContext.getBeanContexts().contains(b)) {
continue;
}
appContext.getBeanContexts().add(b);
}
return ejbs;
}
use of org.apache.openejb.BeanContext in project tomee by apache.
the class Assembler method validateCdiResourceProducers.
private void validateCdiResourceProducers(final AppContext appContext, final AppInfo info) {
if (appContext.getWebBeansContext() == null) {
return;
}
// validate @Produces @Resource/@PersistenceX/@EJB once all is bound to JNDI - best case - or with our model
if (appContext.isStandaloneModule() && !appContext.getProperties().containsKey("openejb.cdi.skip-resource-validation")) {
final Map<String, Object> bindings = appContext.getWebContexts().isEmpty() ? appContext.getBindings() : appContext.getWebContexts().iterator().next().getBindings();
if (bindings != null && appContext.getWebBeansContext() != null && appContext.getWebBeansContext().getBeanManagerImpl().isInUse()) {
for (final Bean<?> bean : appContext.getWebBeansContext().getBeanManagerImpl().getBeans()) {
if (ResourceBean.class.isInstance(bean)) {
final ResourceReference reference = ResourceBean.class.cast(bean).getReference();
String jndi = reference.getJndiName().replace("java:", "");
if (reference.getJndiName().startsWith("java:/")) {
jndi = jndi.substring(1);
}
Object lookup = bindings.get(jndi);
if (lookup == null && reference.getAnnotation(EJB.class) != null) {
final CdiPlugin plugin = CdiPlugin.class.cast(appContext.getWebBeansContext().getPluginLoader().getEjbPlugin());
if (!plugin.isSessionBean(reference.getResourceType())) {
// local beans are here and access is O(1) instead of O(n)
boolean ok = false;
for (final BeanContext bc : appContext.getBeanContexts()) {
if (bc.getBusinessLocalInterfaces().contains(reference.getResourceType()) || bc.getBusinessRemoteInterfaces().contains(reference.getResourceType())) {
ok = true;
break;
}
}
if (!ok) {
throw new DefinitionException("EJB " + reference.getJndiName() + " in " + reference.getOwnerClass() + " can't be cast to " + reference.getResourceType());
}
}
}
if (Reference.class.isInstance(lookup)) {
try {
lookup = Reference.class.cast(lookup).getContent();
} catch (final Exception e) {
// surely too early, let's try some known locations
if (JndiUrlReference.class.isInstance(lookup)) {
checkBuiltInResourceTypes(reference, JndiUrlReference.class.cast(lookup).getJndiName());
}
continue;
}
} else if (lookup == null) {
// TODO: better validation with lookups in tomee, should be in TWAB surely but would split current code
final Resource r = Resource.class.cast(reference.getAnnotation(Resource.class));
if (r != null) {
if (!r.lookup().isEmpty()) {
checkBuiltInResourceTypes(reference, r.lookup());
} else if (!r.name().isEmpty()) {
final String name = "comp/env/" + r.name();
boolean done = false;
for (final WebAppInfo w : info.webApps) {
for (final EnvEntryInfo e : w.jndiEnc.envEntries) {
if (name.equals(e.referenceName)) {
if (e.type != null && !reference.getResourceType().getName().equals(e.type)) {
throw new DefinitionException("Env Entry " + reference.getJndiName() + " in " + reference.getOwnerClass() + " can't be cast to " + reference.getResourceType());
}
done = true;
break;
}
}
if (done) {
break;
}
}
}
}
}
if (lookup != null && !reference.getResourceType().isInstance(lookup)) {
throw new DefinitionException("Resource " + reference.getJndiName() + " in " + reference.getOwnerClass() + " can't be cast, instance is " + lookup);
}
}
}
}
}
}
Aggregations