Search in sources :

Example 11 with Injection

use of org.apache.openejb.Injection in project tomee by apache.

the class RESTService method afterApplicationCreated.

/**
 * Deployment of JAX-RS services starts in response to a AfterApplicationCreated event
 * after normal deployment is done
 * @param appInfo the ear (real or auto-created) in which the webapp is contained
 * @param webApp the webapp containing EJB or Pojo rest services to deploy
 */
public void afterApplicationCreated(final AppInfo appInfo, final WebAppInfo webApp) {
    if ("false".equalsIgnoreCase(appInfo.properties.getProperty("openejb.jaxrs.on", "true"))) {
        return;
    }
    final WebContext webContext = containerSystem.getWebContextByHost(webApp.moduleId, webApp.host != null ? webApp.host : virtualHost);
    if (webContext == null) {
        return;
    }
    if (!deployedWebApps.add(webApp)) {
        return;
    }
    final Map<String, EJBRestServiceInfo> restEjbs = getRestEjbs(appInfo, webApp.moduleId);
    final ClassLoader classLoader = getClassLoader(webContext.getClassLoader());
    final Collection<Injection> injections = webContext.getInjections();
    final WebBeansContext owbCtx;
    if (webContext.getWebbeansContext() != null) {
        owbCtx = webContext.getWebbeansContext();
    } else {
        owbCtx = webContext.getAppContext().getWebBeansContext();
    }
    Context context = webContext.getJndiEnc();
    if (context == null) {
        // usually true since it is set in org.apache.tomee.catalina.TomcatWebAppBuilder.afterStart() and lookup(comp) fails
        context = webContext.getAppContext().getAppJndiContext();
    }
    final ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(classLoader);
    final Collection<Object> additionalProviders = new HashSet<>();
    addAppProvidersIfNeeded(appInfo, webApp, classLoader, additionalProviders);
    // done lazily
    Collection<IdPropertiesInfo> pojoConfigurations = null;
    try {
        boolean deploymentWithApplication = "true".equalsIgnoreCase(appInfo.properties.getProperty(OPENEJB_USE_APPLICATION_PROPERTY, APPLICATION_DEPLOYMENT));
        if (deploymentWithApplication) {
            Class<?> appClazz;
            for (final String app : webApp.restApplications) {
                Application application;
                boolean appSkipped = false;
                String prefix = "/";
                try {
                    appClazz = classLoader.loadClass(app);
                    application = Application.class.cast(appClazz.newInstance());
                    if (owbCtx != null && owbCtx.getBeanManagerImpl().isInUse()) {
                        try {
                            webContext.inject(application);
                        } catch (final Exception e) {
                        // not important since not required by the spec
                        }
                    }
                } catch (final Exception e) {
                    throw new OpenEJBRestRuntimeException("can't create class " + app, e);
                }
                application = wrapApplication(appInfo, application);
                final Set<Class<?>> classes = new HashSet<>(application.getClasses());
                final Set<Object> singletons = application.getSingletons();
                if (classes.size() + singletons.size() == 0) {
                    appSkipped = true;
                } else {
                    for (final Class<?> clazz : classes) {
                        if (isProvider(clazz)) {
                            additionalProviders.add(clazz);
                        } else if (!hasEjbAndIsNotAManagedBean(restEjbs, clazz.getName())) {
                            pojoConfigurations = PojoUtil.findPojoConfig(pojoConfigurations, appInfo, webApp);
                            if (PojoUtil.findConfiguration(pojoConfigurations, clazz.getName()) != null) {
                                deploymentWithApplication = false;
                                logOldDeploymentUsage(clazz.getName());
                            }
                        }
                    }
                    if (deploymentWithApplication) {
                        // don't do it if we detected we should use old deployment
                        for (final Object o : singletons) {
                            final Class<?> clazz = o.getClass();
                            if (isProvider(clazz)) {
                                additionalProviders.add(o);
                            } else if (!hasEjbAndIsNotAManagedBean(restEjbs, clazz.getName())) {
                                pojoConfigurations = PojoUtil.findPojoConfig(pojoConfigurations, appInfo, webApp);
                                if (PojoUtil.findConfiguration(pojoConfigurations, clazz.getName()) != null) {
                                    deploymentWithApplication = false;
                                    logOldDeploymentUsage(clazz.getName());
                                }
                            }
                        }
                    }
                }
                if (deploymentWithApplication) {
                    // don't do it if we detected we should use old deployment
                    final String path = appPrefix(webApp, appClazz);
                    if (path != null) {
                        prefix += path + wildcard;
                    } else {
                        prefix += wildcard;
                    }
                }
                if (deploymentWithApplication) {
                    // don't do it if we detected we should use old deployment
                    if (appSkipped || application == null) {
                        application = !InternalApplication.class.isInstance(application) ? new InternalApplication(application) : application;
                        for (final String clazz : webApp.restClass) {
                            try {
                                final Class<?> loaded = classLoader.loadClass(clazz);
                                if (!isProvider(loaded)) {
                                    pojoConfigurations = PojoUtil.findPojoConfig(pojoConfigurations, appInfo, webApp);
                                    if (PojoUtil.findConfiguration(pojoConfigurations, loaded.getName()) != null) {
                                        deploymentWithApplication = false;
                                        logOldDeploymentUsage(loaded.getName());
                                        break;
                                    }
                                    application.getClasses().add(loaded);
                                } else {
                                    additionalProviders.add(loaded);
                                }
                            } catch (final Exception e) {
                                throw new OpenEJBRestRuntimeException("can't load class " + clazz, e);
                            }
                        }
                        if (deploymentWithApplication) {
                            addEjbToApplication(application, restEjbs);
                            if (!prefix.endsWith(wildcard)) {
                                prefix += wildcard;
                            }
                        }
                    }
                    if (!application.getClasses().isEmpty() || !application.getSingletons().isEmpty()) {
                        pojoConfigurations = PojoUtil.findPojoConfig(pojoConfigurations, appInfo, webApp);
                        deployApplication(appInfo, webApp.contextRoot, restEjbs, classLoader, injections, owbCtx, context, additionalProviders, pojoConfigurations, application, prefix);
                    }
                }
                if (!deploymentWithApplication) {
                    fullServletDeployment(appInfo, webApp, webContext, restEjbs, classLoader, injections, owbCtx, context, additionalProviders, pojoConfigurations);
                }
            }
            if (webApp.restApplications.isEmpty()) {
                final Application application = new InternalApplication(null);
                for (final String clazz : webApp.restClass) {
                    try {
                        final Class<?> loaded = classLoader.loadClass(clazz);
                        if (!isProvider(loaded)) {
                            pojoConfigurations = PojoUtil.findPojoConfig(pojoConfigurations, appInfo, webApp);
                            if (PojoUtil.findConfiguration(pojoConfigurations, loaded.getName()) != null) {
                                deploymentWithApplication = false;
                                logOldDeploymentUsage(loaded.getName());
                                break;
                            }
                            application.getClasses().add(loaded);
                        } else {
                            additionalProviders.add(loaded);
                        }
                    } catch (final Exception e) {
                        throw new OpenEJBRestRuntimeException("can't load class " + clazz, e);
                    }
                }
                addEjbToApplication(application, restEjbs);
                if (deploymentWithApplication) {
                    if (!application.getClasses().isEmpty() || !application.getSingletons().isEmpty()) {
                        final String path = appPrefix(webApp, application.getClass());
                        final String prefix;
                        if (path != null) {
                            prefix = "/" + path + wildcard;
                        } else {
                            prefix = "/" + wildcard;
                        }
                        pojoConfigurations = PojoUtil.findPojoConfig(pojoConfigurations, appInfo, webApp);
                        deployApplication(appInfo, webApp.contextRoot, restEjbs, classLoader, injections, owbCtx, context, additionalProviders, pojoConfigurations, application, prefix);
                    }
                } else {
                    fullServletDeployment(appInfo, webApp, webContext, restEjbs, classLoader, injections, owbCtx, context, additionalProviders, pojoConfigurations);
                }
            }
        } else {
            fullServletDeployment(appInfo, webApp, webContext, restEjbs, classLoader, injections, owbCtx, context, additionalProviders, pojoConfigurations);
        }
    } finally {
        Thread.currentThread().setContextClassLoader(oldLoader);
    }
}
Also used : WebContext(org.apache.openejb.core.WebContext) WebBeansContext(org.apache.webbeans.config.WebBeansContext) AppContext(org.apache.openejb.AppContext) BeanContext(org.apache.openejb.BeanContext) Context(javax.naming.Context) WebContext(org.apache.openejb.core.WebContext) Injection(org.apache.openejb.Injection) URISyntaxException(java.net.URISyntaxException) UncheckedIOException(java.io.UncheckedIOException) ServiceException(org.apache.openejb.server.ServiceException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) WebBeansContext(org.apache.webbeans.config.WebBeansContext) IdPropertiesInfo(org.apache.openejb.assembler.classic.IdPropertiesInfo) MetaAnnotatedClass(org.apache.xbean.finder.MetaAnnotatedClass) Application(javax.ws.rs.core.Application) HashSet(java.util.HashSet)

Example 12 with Injection

use of org.apache.openejb.Injection in project tomee by apache.

the class LightweightWebAppBuilder method deployWebApps.

@Override
public void deployWebApps(final AppInfo appInfo, final ClassLoader appClassLoader) throws Exception {
    final CoreContainerSystem cs = (CoreContainerSystem) SystemInstance.get().getComponent(ContainerSystem.class);
    final AppContext appContext = cs.getAppContext(appInfo.appId);
    if (appContext == null) {
        throw new OpenEJBRuntimeException("Can't find app context for " + appInfo.appId);
    }
    for (final WebAppInfo webAppInfo : appInfo.webApps) {
        ClassLoader classLoader = loaderByWebContext.get(webAppInfo.moduleId);
        if (classLoader == null) {
            classLoader = appClassLoader;
        }
        final Set<Injection> injections = new HashSet<>(appContext.getInjections());
        injections.addAll(new InjectionBuilder(classLoader).buildInjections(webAppInfo.jndiEnc));
        final List<BeanContext> beanContexts;
        if (!appInfo.webAppAlone) {
            // add module bindings in app
            final Assembler assembler = SystemInstance.get().getComponent(Assembler.class);
            beanContexts = assembler.initEjbs(classLoader, appInfo, appContext, injections, new ArrayList<>(), webAppInfo.moduleId);
            appContext.getBeanContexts().addAll(beanContexts);
        } else {
            beanContexts = null;
        }
        final Map<String, Object> bindings = new HashMap<>();
        bindings.putAll(appContext.getBindings());
        bindings.putAll(new JndiEncBuilder(webAppInfo.jndiEnc, injections, webAppInfo.moduleId, "Bean", null, webAppInfo.uniqueId, classLoader, appInfo.properties).buildBindings(JndiEncBuilder.JndiScope.comp));
        final WebContext webContext = new WebContext(appContext);
        webContext.setBindings(bindings);
        webContext.getBindings().putAll(new JndiEncBuilder(webAppInfo.jndiEnc, injections, webAppInfo.moduleId, "Bean", null, webAppInfo.uniqueId, classLoader, appInfo.properties).buildBindings(JndiEncBuilder.JndiScope.comp));
        webContext.setJndiEnc(WebInitialContext.create(bindings, appContext.getGlobalJndiContext()));
        webContext.setClassLoader(classLoader);
        webContext.setId(webAppInfo.moduleId);
        webContext.setContextRoot(webAppInfo.contextRoot);
        webContext.setHost(webAppInfo.host);
        webContext.getInjections().addAll(injections);
        webContext.setInitialContext(new EmbeddedInitialContext(webContext.getJndiEnc(), webContext.getBindings()));
        final ServletContext component = SystemInstance.get().getComponent(ServletContext.class);
        final ServletContextEvent sce = component == null ? new MockServletContextEvent() : new ServletContextEvent(new LightServletContext(component, webContext.getClassLoader()));
        servletContextEvents.put(webAppInfo, sce);
        webContext.setServletContext(sce.getServletContext());
        SystemInstance.get().fireEvent(new EmbeddedServletContextCreated(sce.getServletContext()));
        appContext.getWebContexts().add(webContext);
        cs.addWebContext(webContext);
        if (!appInfo.webAppAlone && hasCdi(appInfo)) {
            final Assembler assembler = SystemInstance.get().getComponent(Assembler.class);
            new CdiBuilder().build(appInfo, appContext, beanContexts, webContext);
            assembler.startEjbs(true, beanContexts);
        }
        // listeners
        for (final ListenerInfo listener : webAppInfo.listeners) {
            final Class<?> clazz = webContext.getClassLoader().loadClass(listener.classname);
            final Object instance = webContext.newInstance(clazz);
            if (ServletContextListener.class.isInstance(instance)) {
                switchServletContextIfNeeded(sce.getServletContext(), new Runnable() {

                    @Override
                    public void run() {
                        ((ServletContextListener) instance).contextInitialized(sce);
                    }
                });
            }
            List<Object> list = listeners.computeIfAbsent(webAppInfo, k -> new ArrayList<>());
            list.add(instance);
        }
        for (final ClassListInfo info : webAppInfo.webAnnotatedClasses) {
            final String url = info.name;
            for (final String filterPath : info.list) {
                final Class<?> clazz = loadFromUrls(webContext.getClassLoader(), url, filterPath);
                final WebListener annotation = clazz.getAnnotation(WebListener.class);
                if (annotation != null) {
                    final Object instance = webContext.newInstance(clazz);
                    if (ServletContextListener.class.isInstance(instance)) {
                        switchServletContextIfNeeded(sce.getServletContext(), new Runnable() {

                            @Override
                            public void run() {
                                ((ServletContextListener) instance).contextInitialized(sce);
                            }
                        });
                    }
                    List<Object> list = listeners.computeIfAbsent(webAppInfo, k -> new ArrayList<>());
                    list.add(instance);
                }
            }
        }
        final DeployedWebObjects deployedWebObjects = new DeployedWebObjects();
        deployedWebObjects.webContext = webContext;
        servletDeploymentInfo.put(webAppInfo, deployedWebObjects);
        if (webContext.getWebBeansContext() != null && webContext.getWebBeansContext().getBeanManagerImpl().isInUse()) {
            final Thread thread = Thread.currentThread();
            final ClassLoader old = thread.getContextClassLoader();
            thread.setContextClassLoader(webContext.getClassLoader());
            try {
                OpenEJBLifecycle.class.cast(webContext.getWebBeansContext().getService(ContainerLifecycle.class)).startServletContext(sce.getServletContext());
            } finally {
                thread.setContextClassLoader(old);
            }
        }
        if (addServletMethod == null) {
            // can't manage filter/servlets
            continue;
        }
        // register filters
        for (final FilterInfo info : webAppInfo.filters) {
            switchServletContextIfNeeded(sce.getServletContext(), new Runnable() {

                @Override
                public void run() {
                    for (final String mapping : info.mappings) {
                        final FilterConfig config = new SimpleFilterConfig(sce.getServletContext(), info.name, info.initParams);
                        try {
                            addFilterMethod.invoke(null, info.classname, webContext, mapping, config);
                            deployedWebObjects.filterMappings.add(mapping);
                        } catch (final Exception e) {
                            LOGGER.warning(e.getMessage(), e);
                        }
                    }
                }
            });
        }
        for (final ClassListInfo info : webAppInfo.webAnnotatedClasses) {
            final String url = info.name;
            for (final String filterPath : info.list) {
                final Class<?> clazz = loadFromUrls(webContext.getClassLoader(), url, filterPath);
                final WebFilter annotation = clazz.getAnnotation(WebFilter.class);
                if (annotation != null) {
                    final Properties initParams = new Properties();
                    for (final WebInitParam param : annotation.initParams()) {
                        initParams.put(param.name(), param.value());
                    }
                    final FilterConfig config = new SimpleFilterConfig(sce.getServletContext(), info.name, initParams);
                    for (final String[] mappings : asList(annotation.urlPatterns(), annotation.value())) {
                        switchServletContextIfNeeded(sce.getServletContext(), new Runnable() {

                            @Override
                            public void run() {
                                for (final String mapping : mappings) {
                                    try {
                                        addFilterMethod.invoke(null, clazz.getName(), webContext, mapping, config);
                                        deployedWebObjects.filterMappings.add(mapping);
                                    } catch (final Exception e) {
                                        LOGGER.warning(e.getMessage(), e);
                                    }
                                }
                            }
                        });
                    }
                }
            }
        }
        final Map<String, PortInfo> ports = new TreeMap<>();
        for (final PortInfo port : webAppInfo.portInfos) {
            ports.put(port.serviceLink, port);
        }
        // register servlets
        for (final ServletInfo info : webAppInfo.servlets) {
            if ("true".equalsIgnoreCase(appInfo.properties.getProperty("openejb.jaxrs.on", "true"))) {
                // skip jaxrs servlets
                boolean skip = false;
                for (final ParamValueInfo pvi : info.initParams) {
                    if ("javax.ws.rs.Application".equals(pvi.name) || Application.class.getName().equals(pvi.name)) {
                        skip = true;
                    }
                }
                if (skip) {
                    continue;
                }
                if (info.servletClass == null) {
                    try {
                        if (Application.class.isAssignableFrom(classLoader.loadClass(info.servletName))) {
                            continue;
                        }
                    } catch (final Exception e) {
                    // no-op
                    }
                }
            }
            // If POJO web services, it will be overriden with WsServlet
            if (ports.containsKey(info.servletName) || ports.containsKey(info.servletClass)) {
                continue;
            }
            // deploy
            for (final String mapping : info.mappings) {
                switchServletContextIfNeeded(sce.getServletContext(), new Runnable() {

                    @Override
                    public void run() {
                        try {
                            addServletMethod.invoke(null, info.servletClass, webContext, mapping);
                            deployedWebObjects.mappings.add(mapping);
                        } catch (final Exception e) {
                            LOGGER.warning(e.getMessage(), e);
                        }
                    }
                });
            }
        }
        for (final ClassListInfo info : webAppInfo.webAnnotatedClasses) {
            final String url = info.name;
            for (final String servletPath : info.list) {
                final Class<?> clazz = loadFromUrls(webContext.getClassLoader(), url, servletPath);
                final WebServlet annotation = clazz.getAnnotation(WebServlet.class);
                if (annotation != null) {
                    for (final String[] mappings : asList(annotation.urlPatterns(), annotation.value())) {
                        switchServletContextIfNeeded(sce.getServletContext(), new Runnable() {

                            @Override
                            public void run() {
                                for (final String mapping : mappings) {
                                    try {
                                        addServletMethod.invoke(null, clazz.getName(), webContext, mapping);
                                        deployedWebObjects.mappings.add(mapping);
                                    } catch (final Exception e) {
                                        LOGGER.warning(e.getMessage(), e);
                                    }
                                }
                            }
                        });
                    }
                }
            }
        }
        if (addDefaults != null && tryJsp()) {
            addDefaults.invoke(null, webContext);
            deployedWebObjects.mappings.add("*\\.jsp");
        }
    }
}
Also used : CoreContainerSystem(org.apache.openejb.core.CoreContainerSystem) ContainerSystem(org.apache.openejb.spi.ContainerSystem) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ServletInfo(org.apache.openejb.assembler.classic.ServletInfo) WebAppInfo(org.apache.openejb.assembler.classic.WebAppInfo) ParamValueInfo(org.apache.openejb.assembler.classic.ParamValueInfo) FilterConfig(javax.servlet.FilterConfig) HashSet(java.util.HashSet) InjectionBuilder(org.apache.openejb.assembler.classic.InjectionBuilder) CoreContainerSystem(org.apache.openejb.core.CoreContainerSystem) Injection(org.apache.openejb.Injection) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) BeanContext(org.apache.openejb.BeanContext) ListenerInfo(org.apache.openejb.assembler.classic.ListenerInfo) CdiBuilder(org.apache.openejb.cdi.CdiBuilder) Assembler(org.apache.openejb.assembler.classic.Assembler) OpenEJBLifecycle(org.apache.openejb.cdi.OpenEJBLifecycle) WebContext(org.apache.openejb.core.WebContext) MockServletContextEvent(org.apache.webbeans.web.lifecycle.test.MockServletContextEvent) Properties(java.util.Properties) ClassListInfo(org.apache.openejb.assembler.classic.ClassListInfo) PortInfo(org.apache.openejb.assembler.classic.PortInfo) WebServlet(javax.servlet.annotation.WebServlet) MockServletContext(org.apache.webbeans.web.lifecycle.test.MockServletContext) ServletContext(javax.servlet.ServletContext) FilterInfo(org.apache.openejb.assembler.classic.FilterInfo) WebFilter(javax.servlet.annotation.WebFilter) AppContext(org.apache.openejb.AppContext) TreeMap(java.util.TreeMap) NamingException(javax.naming.NamingException) NameNotFoundException(javax.naming.NameNotFoundException) MalformedURLException(java.net.MalformedURLException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) WebListener(javax.servlet.annotation.WebListener) JndiEncBuilder(org.apache.openejb.assembler.classic.JndiEncBuilder) WebInitParam(javax.servlet.annotation.WebInitParam) ServletContextEvent(javax.servlet.ServletContextEvent) MockServletContextEvent(org.apache.webbeans.web.lifecycle.test.MockServletContextEvent)

Example 13 with Injection

use of org.apache.openejb.Injection in project tomee by apache.

the class EjbJarBuilder method build.

public HashMap<String, BeanContext> build(final EjbJarInfo ejbJar, final Collection<Injection> appInjections, final ClassLoader classLoader) throws OpenEJBException {
    final InjectionBuilder injectionBuilder = new InjectionBuilder(classLoader);
    final List<Injection> moduleInjections = injectionBuilder.buildInjections(ejbJar.moduleJndiEnc);
    moduleInjections.addAll(appInjections);
    final Context moduleJndiContext = new JndiEncBuilder(ejbJar.moduleJndiEnc, moduleInjections, null, ejbJar.moduleName, ejbJar.moduleUri, ejbJar.uniqueId, classLoader, context.getProperties()).build(JndiEncBuilder.JndiScope.module);
    final HashMap<String, BeanContext> deployments = new HashMap<>();
    final ModuleContext moduleContext = !ejbJar.properties.containsKey("openejb.test.module") ? new ModuleContext(ejbJar.moduleName, ejbJar.moduleUri, ejbJar.uniqueId, context, moduleJndiContext, classLoader) : new ModuleTestContext(ejbJar.moduleName, ejbJar.moduleUri, ejbJar.uniqueId, context, moduleJndiContext, classLoader);
    moduleContext.getProperties().putAll(ejbJar.properties);
    final InterceptorBindingBuilder interceptorBindingBuilder = new InterceptorBindingBuilder(classLoader, ejbJar);
    final MethodScheduleBuilder methodScheduleBuilder = new MethodScheduleBuilder();
    for (final EnterpriseBeanInfo ejbInfo : ejbJar.enterpriseBeans) {
        final ClassLoader loader = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(moduleContext.getClassLoader());
        try {
            final EnterpriseBeanBuilder deploymentBuilder = new EnterpriseBeanBuilder(ejbInfo, moduleContext, moduleInjections);
            final BeanContext bean = deploymentBuilder.build();
            interceptorBindingBuilder.build(bean, ejbInfo);
            methodScheduleBuilder.build(bean, ejbInfo);
            deployments.put(ejbInfo.ejbDeploymentId, bean);
            // TODO: replace with get() on application context or parent
            final Container container = (Container) props.get(ejbInfo.containerId);
            if (container == null) {
                throw new IllegalStateException("Container does not exist: " + ejbInfo.containerId + ".  Referenced by deployment: " + bean.getDeploymentID());
            }
            // Don't deploy to the container, yet. That will be done by deploy() once Assembler as finished configuring the DeploymentInfo
            bean.setContainer(container);
        } catch (final Throwable e) {
            throw new OpenEJBException("Error building bean '" + ejbInfo.ejbName + "'.  Exception: " + e.getClass() + ": " + e.getMessage(), e);
        } finally {
            Thread.currentThread().setContextClassLoader(loader);
        }
    }
    return deployments;
}
Also used : BeanContext(org.apache.openejb.BeanContext) ModuleTestContext(org.apache.openejb.ModuleTestContext) AppContext(org.apache.openejb.AppContext) Context(javax.naming.Context) ModuleContext(org.apache.openejb.ModuleContext) OpenEJBException(org.apache.openejb.OpenEJBException) HashMap(java.util.HashMap) Injection(org.apache.openejb.Injection) BeanContext(org.apache.openejb.BeanContext) ModuleTestContext(org.apache.openejb.ModuleTestContext) Container(org.apache.openejb.Container) ModuleContext(org.apache.openejb.ModuleContext)

Example 14 with Injection

use of org.apache.openejb.Injection in project tomee by apache.

the class CdiResourceInjectionService method fillInjectionProperties.

@SuppressWarnings("unchecked")
private void fillInjectionProperties(final ObjectRecipe objectRecipe, final Object managedBeanInstance) {
    final boolean usePrefix = true;
    final Class<?> clazz = managedBeanInstance.getClass();
    Collection<BeanContext> comps;
    WebBeansContext webBeansContext = null;
    if (ear) {
        // let it be contextual, ie use webapp context (env-entries...) to create ear libs interceptors...
        try {
            webBeansContext = WebBeansContext.currentInstance();
            comps = CdiResourceInjectionService.class.cast(webBeansContext.getService(ResourceInjectionService.class)).compContexts;
        } catch (final Exception e) {
            comps = compContexts;
        }
    } else {
        comps = compContexts;
    }
    for (final BeanContext beanContext : comps) {
        for (final Injection injection : beanContext.getInjections()) {
            if (injection.getTarget() == null) {
                continue;
            }
            if (!injection.getTarget().isAssignableFrom(clazz)) {
                continue;
            }
            final String prefix;
            if (usePrefix) {
                prefix = injection.getTarget().getName() + "/";
            } else {
                prefix = "";
            }
            try {
                final Object value = lookup(beanContext, injection);
                objectRecipe.setProperty(prefix + injection.getName(), value);
            } catch (final NamingException e) {
                boolean found = false;
                if (webBeansContext != null) {
                    for (final WebContext w : appCtx.getWebContexts()) {
                        if (w.getWebBeansContext() == webBeansContext) {
                            final Object value = w.getBindings().get(injection.getJndiName());
                            if (value != null) {
                                objectRecipe.setProperty(prefix + injection.getName(), value);
                                found = true;
                            }
                            break;
                        }
                    }
                }
                if (!found) {
                    logger.warning("Injection data not found in JNDI context: jndiName='" + injection.getJndiName() + "', target=" + injection.getTarget().getName() + "/" + injection.getName());
                }
            }
        }
    }
}
Also used : BeanContext(org.apache.openejb.BeanContext) WebBeansContext(org.apache.webbeans.config.WebBeansContext) WebContext(org.apache.openejb.core.WebContext) NamingException(javax.naming.NamingException) Injection(org.apache.openejb.Injection) ResourceInjectionService(org.apache.webbeans.spi.ResourceInjectionService) NamingException(javax.naming.NamingException) IOException(java.io.IOException)

Aggregations

Injection (org.apache.openejb.Injection)14 BeanContext (org.apache.openejb.BeanContext)9 NamingException (javax.naming.NamingException)8 ArrayList (java.util.ArrayList)7 Context (javax.naming.Context)7 HashMap (java.util.HashMap)6 AppContext (org.apache.openejb.AppContext)6 WebContext (org.apache.openejb.core.WebContext)6 HashSet (java.util.HashSet)5 IOException (java.io.IOException)4 MalformedURLException (java.net.MalformedURLException)4 URL (java.net.URL)4 Properties (java.util.Properties)4 OpenEJBException (org.apache.openejb.OpenEJBException)4 OpenEJBRuntimeException (org.apache.openejb.OpenEJBRuntimeException)4 WebBeansContext (org.apache.webbeans.config.WebBeansContext)4 NameNotFoundException (javax.naming.NameNotFoundException)3 ServletContext (javax.servlet.ServletContext)3 CdiBuilder (org.apache.openejb.cdi.CdiBuilder)3 File (java.io.File)2