Search in sources :

Example 1 with Injection

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

the class Assembler method createApplication.

private AppContext createApplication(final AppInfo appInfo, ClassLoader classLoader, final boolean start) throws OpenEJBException, IOException, NamingException {
    try {
        try {
            mergeServices(appInfo);
        } catch (final URISyntaxException e) {
            logger.info("Can't merge resources.xml services and appInfo.properties");
        }
        // The path is used in the UrlCache, command line deployer, JNDI name templates, tomcat integration and a few other places
        if (appInfo.appId == null) {
            throw new IllegalArgumentException("AppInfo.appId cannot be null");
        }
        if (appInfo.path == null) {
            appInfo.path = appInfo.appId;
        }
        Extensions.addExtensions(classLoader, appInfo.eventClassesNeedingAppClassloader);
        logger.info("createApplication.start", appInfo.path);
        final Context containerSystemContext = containerSystem.getJNDIContext();
        // To start out, ensure we don't already have any beans deployed with duplicate IDs.  This
        // is a conflict we can't handle.
        final List<String> used = getDuplicates(appInfo);
        if (used.size() > 0) {
            StringBuilder message = new StringBuilder(logger.error("createApplication.appFailedDuplicateIds", appInfo.path));
            for (final String id : used) {
                logger.error("createApplication.deploymentIdInUse", id);
                message.append("\n    ").append(id);
            }
            throw new DuplicateDeploymentIdException(message.toString());
        }
        final ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
        try {
            Thread.currentThread().setContextClassLoader(classLoader);
            for (final ContainerInfo container : appInfo.containers) {
                createContainer(container);
            }
        } finally {
            Thread.currentThread().setContextClassLoader(oldCl);
        }
        // Construct the global and app jndi contexts for this app
        final InjectionBuilder injectionBuilder = new InjectionBuilder(classLoader);
        final Set<Injection> injections = new HashSet<>();
        injections.addAll(injectionBuilder.buildInjections(appInfo.globalJndiEnc));
        injections.addAll(injectionBuilder.buildInjections(appInfo.appJndiEnc));
        final JndiEncBuilder globalBuilder = new JndiEncBuilder(appInfo.globalJndiEnc, injections, appInfo.appId, null, GLOBAL_UNIQUE_ID, classLoader, appInfo.properties);
        final Map<String, Object> globalBindings = globalBuilder.buildBindings(JndiEncBuilder.JndiScope.global);
        final Context globalJndiContext = globalBuilder.build(globalBindings);
        final JndiEncBuilder appBuilder = new JndiEncBuilder(appInfo.appJndiEnc, injections, appInfo.appId, null, appInfo.appId, classLoader, appInfo.properties);
        final Map<String, Object> appBindings = appBuilder.buildBindings(JndiEncBuilder.JndiScope.app);
        final Context appJndiContext = appBuilder.build(appBindings);
        final boolean cdiActive = shouldStartCdi(appInfo);
        try {
            // Generate the cmp2/cmp1 concrete subclasses
            final CmpJarBuilder cmpJarBuilder = new CmpJarBuilder(appInfo, classLoader);
            final File generatedJar = cmpJarBuilder.getJarFile();
            if (generatedJar != null) {
                classLoader = ClassLoaderUtil.createClassLoader(appInfo.path, new URL[] { generatedJar.toURI().toURL() }, classLoader);
            }
            final AppContext appContext = new AppContext(appInfo.appId, SystemInstance.get(), classLoader, globalJndiContext, appJndiContext, appInfo.standaloneModule);
            for (final Entry<Object, Object> entry : appInfo.properties.entrySet()) {
                if (!Module.class.isInstance(entry.getValue())) {
                    appContext.getProperties().put(entry.getKey(), entry.getValue());
                }
            }
            appContext.getInjections().addAll(injections);
            appContext.getBindings().putAll(globalBindings);
            appContext.getBindings().putAll(appBindings);
            containerSystem.addAppContext(appContext);
            appContext.set(AsynchronousPool.class, AsynchronousPool.create(appContext));
            final Map<String, LazyValidatorFactory> lazyValidatorFactories = new HashMap<>();
            final Map<String, LazyValidator> lazyValidators = new HashMap<>();
            final boolean isGeronimo = SystemInstance.get().hasProperty("openejb.geronimo");
            // try to not create N times the same validator for a single app
            final Map<ComparableValidationConfig, ValidatorFactory> validatorFactoriesByConfig = new HashMap<>();
            if (!isGeronimo) {
                // Bean Validation
                // ValidatorFactory needs to be put in the map sent to the entity manager factory
                // so it has to be constructed before
                final List<CommonInfoObject> vfs = listCommonInfoObjectsForAppInfo(appInfo);
                final Map<String, ValidatorFactory> validatorFactories = new HashMap<>();
                for (final CommonInfoObject info : vfs) {
                    if (info.validationInfo == null) {
                        continue;
                    }
                    final ComparableValidationConfig conf = new ComparableValidationConfig(info.validationInfo.providerClassName, info.validationInfo.messageInterpolatorClass, info.validationInfo.traversableResolverClass, info.validationInfo.constraintFactoryClass, info.validationInfo.parameterNameProviderClass, info.validationInfo.version, info.validationInfo.propertyTypes, info.validationInfo.constraintMappings, info.validationInfo.executableValidationEnabled, info.validationInfo.validatedTypes);
                    ValidatorFactory factory = validatorFactoriesByConfig.get(conf);
                    if (factory == null) {
                        try {
                            // lazy cause of CDI :(
                            final LazyValidatorFactory handler = new LazyValidatorFactory(classLoader, info.validationInfo);
                            factory = (ValidatorFactory) Proxy.newProxyInstance(appContext.getClassLoader(), VALIDATOR_FACTORY_INTERFACES, handler);
                            lazyValidatorFactories.put(info.uniqueId, handler);
                        } catch (final ValidationException ve) {
                            logger.warning("can't build the validation factory for module " + info.uniqueId, ve);
                            continue;
                        }
                        validatorFactoriesByConfig.put(conf, factory);
                    } else {
                        lazyValidatorFactories.put(info.uniqueId, LazyValidatorFactory.class.cast(Proxy.getInvocationHandler(factory)));
                    }
                    validatorFactories.put(info.uniqueId, factory);
                }
                // validators bindings
                for (final Entry<String, ValidatorFactory> validatorFactory : validatorFactories.entrySet()) {
                    final String id = validatorFactory.getKey();
                    final ValidatorFactory factory = validatorFactory.getValue();
                    try {
                        containerSystemContext.bind(VALIDATOR_FACTORY_NAMING_CONTEXT + id, factory);
                        final Validator validator;
                        try {
                            final LazyValidator lazyValidator = new LazyValidator(factory);
                            validator = (Validator) Proxy.newProxyInstance(appContext.getClassLoader(), VALIDATOR_INTERFACES, lazyValidator);
                            lazyValidators.put(id, lazyValidator);
                        } catch (final Exception e) {
                            logger.error(e.getMessage(), e);
                            continue;
                        }
                        containerSystemContext.bind(VALIDATOR_NAMING_CONTEXT + id, validator);
                    } catch (final NameAlreadyBoundException e) {
                        throw new OpenEJBException("ValidatorFactory already exists for module " + id, e);
                    } catch (final Exception e) {
                        throw new OpenEJBException(e);
                    }
                }
                validatorFactories.clear();
            }
            // JPA - Persistence Units MUST be processed first since they will add ClassFileTransformers
            // to the class loader which must be added before any classes are loaded
            final Map<String, String> units = new HashMap<>();
            final PersistenceBuilder persistenceBuilder = new PersistenceBuilder(persistenceClassLoaderHandler);
            for (final PersistenceUnitInfo info : appInfo.persistenceUnits) {
                final ReloadableEntityManagerFactory factory;
                try {
                    factory = persistenceBuilder.createEntityManagerFactory(info, classLoader, validatorFactoriesByConfig, cdiActive);
                    containerSystem.getJNDIContext().bind(PERSISTENCE_UNIT_NAMING_CONTEXT + info.id, factory);
                    units.put(info.name, PERSISTENCE_UNIT_NAMING_CONTEXT + info.id);
                } catch (final NameAlreadyBoundException e) {
                    throw new OpenEJBException("PersistenceUnit already deployed: " + info.persistenceUnitRootUrl);
                } catch (final Exception e) {
                    throw new OpenEJBException(e);
                }
                factory.register();
            }
            logger.debug("Loaded persistence units: " + units);
            // Connectors
            for (final ConnectorInfo connector : appInfo.connectors) {
                final ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
                Thread.currentThread().setContextClassLoader(classLoader);
                try {
                    // todo add undeployment code for these
                    if (connector.resourceAdapter != null) {
                        createResource(null, connector.resourceAdapter);
                    }
                    for (final ResourceInfo outbound : connector.outbound) {
                        createResource(null, outbound);
                        // set it after as a marker but not as an attribute (no getOpenejb().setConnector(...))
                        outbound.properties.setProperty("openejb.connector", "true");
                    }
                    for (final MdbContainerInfo inbound : connector.inbound) {
                        createContainer(inbound);
                    }
                    for (final ResourceInfo adminObject : connector.adminObject) {
                        createResource(null, adminObject);
                    }
                } finally {
                    Thread.currentThread().setContextClassLoader(oldClassLoader);
                }
            }
            final List<BeanContext> allDeployments = initEjbs(classLoader, appInfo, appContext, injections, new ArrayList<>(), null);
            if ("true".equalsIgnoreCase(SystemInstance.get().getProperty(PROPAGATE_APPLICATION_EXCEPTIONS, appInfo.properties.getProperty(PROPAGATE_APPLICATION_EXCEPTIONS, "false")))) {
                propagateApplicationExceptions(appInfo, classLoader, allDeployments);
            }
            if (cdiActive) {
                new CdiBuilder().build(appInfo, appContext, allDeployments);
                ensureWebBeansContext(appContext);
                appJndiContext.bind("app/BeanManager", appContext.getBeanManager());
                appContext.getBindings().put("app/BeanManager", appContext.getBeanManager());
            } else {
                // ensure we can reuse it in tomcat to remove OWB filters
                appInfo.properties.setProperty("openejb.cdi.activated", "false");
            }
            // now cdi is started we can try to bind real validator factory and validator
            if (!isGeronimo) {
                for (final Entry<String, LazyValidator> lazyValidator : lazyValidators.entrySet()) {
                    final String id = lazyValidator.getKey();
                    final ValidatorFactory factory = lazyValidatorFactories.get(lazyValidator.getKey()).getFactory();
                    try {
                        final String factoryName = VALIDATOR_FACTORY_NAMING_CONTEXT + id;
                        containerSystemContext.unbind(factoryName);
                        containerSystemContext.bind(factoryName, factory);
                        final String validatoryName = VALIDATOR_NAMING_CONTEXT + id;
                        try {
                            // do it after factory cause of TCKs which expects validator to be created later
                            final Validator val = lazyValidator.getValue().getValidator();
                            containerSystemContext.unbind(validatoryName);
                            containerSystemContext.bind(validatoryName, val);
                        } catch (final Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                    } catch (final NameAlreadyBoundException e) {
                        throw new OpenEJBException("ValidatorFactory already exists for module " + id, e);
                    } catch (final Exception e) {
                        throw new OpenEJBException(e);
                    }
                }
            }
            startEjbs(start, allDeployments);
            // App Client
            for (final ClientInfo clientInfo : appInfo.clients) {
                // determine the injections
                final List<Injection> clientInjections = injectionBuilder.buildInjections(clientInfo.jndiEnc);
                // build the enc
                final JndiEncBuilder jndiEncBuilder = new JndiEncBuilder(clientInfo.jndiEnc, clientInjections, "Bean", clientInfo.moduleId, null, clientInfo.uniqueId, classLoader, new Properties());
                // then, we can set the client flag
                if (clientInfo.remoteClients.size() > 0 || clientInfo.localClients.size() == 0) {
                    jndiEncBuilder.setClient(true);
                }
                jndiEncBuilder.setUseCrossClassLoaderRef(false);
                final Context context = jndiEncBuilder.build(JndiEncBuilder.JndiScope.comp);
                // Debug.printContext(context);
                containerSystemContext.bind("openejb/client/" + clientInfo.moduleId, context);
                if (clientInfo.path != null) {
                    context.bind("info/path", clientInfo.path);
                }
                if (clientInfo.mainClass != null) {
                    context.bind("info/mainClass", clientInfo.mainClass);
                }
                if (clientInfo.callbackHandler != null) {
                    context.bind("info/callbackHandler", clientInfo.callbackHandler);
                }
                context.bind("info/injections", clientInjections);
                for (final String clientClassName : clientInfo.remoteClients) {
                    containerSystemContext.bind("openejb/client/" + clientClassName, clientInfo.moduleId);
                }
                for (final String clientClassName : clientInfo.localClients) {
                    containerSystemContext.bind("openejb/client/" + clientClassName, clientInfo.moduleId);
                    logger.getChildLogger("client").info("createApplication.createLocalClient", clientClassName, clientInfo.moduleId);
                }
            }
            // WebApp
            final SystemInstance systemInstance = SystemInstance.get();
            final WebAppBuilder webAppBuilder = systemInstance.getComponent(WebAppBuilder.class);
            if (webAppBuilder != null) {
                webAppBuilder.deployWebApps(appInfo, classLoader);
            }
            if (start) {
                final EjbResolver globalEjbResolver = systemInstance.getComponent(EjbResolver.class);
                globalEjbResolver.addAll(appInfo.ejbJars);
            }
            // bind all global values on global context
            bindGlobals(appContext.getBindings());
            validateCdiResourceProducers(appContext, appInfo);
            // deploy MBeans
            for (final String mbean : appInfo.mbeans) {
                deployMBean(appContext.getWebBeansContext(), classLoader, mbean, appInfo.jmx, appInfo.appId);
            }
            for (final EjbJarInfo ejbJarInfo : appInfo.ejbJars) {
                for (final String mbean : ejbJarInfo.mbeans) {
                    deployMBean(appContext.getWebBeansContext(), classLoader, mbean, appInfo.jmx, ejbJarInfo.moduleName);
                }
            }
            for (final ConnectorInfo connectorInfo : appInfo.connectors) {
                for (final String mbean : connectorInfo.mbeans) {
                    deployMBean(appContext.getWebBeansContext(), classLoader, mbean, appInfo.jmx, appInfo.appId + ".add-lib");
                }
            }
            postConstructResources(appInfo.resourceIds, classLoader, containerSystemContext, appContext);
            deployedApplications.put(appInfo.path, appInfo);
            resumePersistentSchedulers(appContext);
            systemInstance.fireEvent(new AssemblerAfterApplicationCreated(appInfo, appContext, allDeployments));
            logger.info("createApplication.success", appInfo.path);
            // required by spec EE.5.3.4
            if (setAppNamingContextReadOnly(allDeployments)) {
                logger.info("createApplication.naming", appInfo.path);
            }
            return appContext;
        } catch (final ValidationException | DeploymentException ve) {
            throw ve;
        } catch (final Throwable t) {
            try {
                destroyApplication(appInfo);
            } catch (final Exception e1) {
                logger.debug("createApplication.undeployFailed", e1, appInfo.path);
            }
            throw new OpenEJBException(messages.format("createApplication.failed", appInfo.path), t);
        }
    } finally {
        // cleanup there as well by safety cause we have multiple deployment mode (embedded, tomcat...)
        for (final WebAppInfo webApp : appInfo.webApps) {
            appInfo.properties.remove(webApp);
        }
    }
}
Also used : OpenEJBException(org.apache.openejb.OpenEJBException) HashMap(java.util.HashMap) HashSet(java.util.HashSet) ValidatorFactory(javax.validation.ValidatorFactory) Injection(org.apache.openejb.Injection) BeanContext(org.apache.openejb.BeanContext) CdiBuilder(org.apache.openejb.cdi.CdiBuilder) AssemblerAfterApplicationCreated(org.apache.openejb.assembler.classic.event.AssemblerAfterApplicationCreated) DeploymentException(javax.enterprise.inject.spi.DeploymentException) Module(org.apache.openejb.config.Module) File(java.io.File) ValidationException(javax.validation.ValidationException) URISyntaxException(java.net.URISyntaxException) SuperProperties(org.apache.openejb.util.SuperProperties) Properties(java.util.Properties) URL(java.net.URL) NameAlreadyBoundException(javax.naming.NameAlreadyBoundException) SystemInstance(org.apache.openejb.loader.SystemInstance) WebContext(org.apache.openejb.core.WebContext) SimpleBootstrapContext(org.apache.openejb.core.transaction.SimpleBootstrapContext) Context(javax.naming.Context) ServletContext(javax.servlet.ServletContext) MethodContext(org.apache.openejb.MethodContext) IvmContext(org.apache.openejb.core.ivm.naming.IvmContext) AppContext(org.apache.openejb.AppContext) InitialContext(javax.naming.InitialContext) WebBeansContext(org.apache.webbeans.config.WebBeansContext) BeanContext(org.apache.openejb.BeanContext) CreationalContext(javax.enterprise.context.spi.CreationalContext) DeploymentContext(org.apache.openejb.DeploymentContext) GeronimoBootstrapContext(org.apache.geronimo.connector.GeronimoBootstrapContext) BootstrapContext(javax.resource.spi.BootstrapContext) AppContext(org.apache.openejb.AppContext) InvalidObjectException(java.io.InvalidObjectException) NameAlreadyBoundException(javax.naming.NameAlreadyBoundException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ObjectStreamException(java.io.ObjectStreamException) ResourceAdapterInternalException(javax.resource.spi.ResourceAdapterInternalException) URISyntaxException(java.net.URISyntaxException) UndeployException(org.apache.openejb.UndeployException) DefinitionException(javax.enterprise.inject.spi.DefinitionException) ConstructionException(org.apache.xbean.recipe.ConstructionException) MBeanRegistrationException(javax.management.MBeanRegistrationException) InstanceNotFoundException(javax.management.InstanceNotFoundException) ValidationException(javax.validation.ValidationException) MalformedObjectNameException(javax.management.MalformedObjectNameException) DuplicateDeploymentIdException(org.apache.openejb.DuplicateDeploymentIdException) TimeoutException(java.util.concurrent.TimeoutException) NamingException(javax.naming.NamingException) OpenEJBException(org.apache.openejb.OpenEJBException) DeploymentException(javax.enterprise.inject.spi.DeploymentException) NoSuchApplicationException(org.apache.openejb.NoSuchApplicationException) MalformedURLException(java.net.MalformedURLException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) DuplicateDeploymentIdException(org.apache.openejb.DuplicateDeploymentIdException) Validator(javax.validation.Validator)

Example 2 with Injection

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

the class InjectionBuilder method buildInjections.

// TODO: check we can really skip the loadClass exception (TCKs)
public List<Injection> buildInjections(final JndiEncInfo jndiEnc) throws OpenEJBException {
    final List<Injection> injections = new ArrayList<>();
    for (final EnvEntryInfo info : jndiEnc.envEntries) {
        for (final InjectionInfo target : info.targets) {
            final Injection injection = injection(info.referenceName, target.propertyName, target.className);
            injections.add(injection);
        }
    }
    for (final EjbReferenceInfo info : jndiEnc.ejbReferences) {
        for (final InjectionInfo target : info.targets) {
            final Injection injection = injection(info.referenceName, target.propertyName, target.className);
            injections.add(injection);
        }
    }
    for (final EjbReferenceInfo info : jndiEnc.ejbLocalReferences) {
        for (final InjectionInfo target : info.targets) {
            final Injection injection = injection(info.referenceName, target.propertyName, target.className);
            injections.add(injection);
        }
    }
    for (final PersistenceUnitReferenceInfo info : jndiEnc.persistenceUnitRefs) {
        for (final InjectionInfo target : info.targets) {
            final Injection injection = injection(info.referenceName, target.propertyName, target.className);
            injections.add(injection);
        }
    }
    for (final PersistenceContextReferenceInfo info : jndiEnc.persistenceContextRefs) {
        for (final InjectionInfo target : info.targets) {
            final Injection injection = injection(info.referenceName, target.propertyName, target.className);
            injections.add(injection);
        }
    }
    for (final ResourceReferenceInfo info : jndiEnc.resourceRefs) {
        for (final InjectionInfo target : info.targets) {
            final Injection injection = injection(info.referenceName, target.propertyName, target.className);
            injections.add(injection);
        }
    }
    for (final ResourceEnvReferenceInfo info : jndiEnc.resourceEnvRefs) {
        for (final InjectionInfo target : info.targets) {
            final Injection injection = injection(info.referenceName, target.propertyName, target.className);
            injections.add(injection);
        }
    }
    for (final ServiceReferenceInfo info : jndiEnc.serviceRefs) {
        for (final InjectionInfo target : info.targets) {
            final Injection injection = injection(info.referenceName, target.propertyName, target.className);
            injections.add(injection);
        }
    }
    return injections;
}
Also used : ArrayList(java.util.ArrayList) Injection(org.apache.openejb.Injection)

Example 3 with Injection

use of org.apache.openejb.Injection 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;
}
Also used : ContainerSystem(org.apache.openejb.spi.ContainerSystem) OpenEJBException(org.apache.openejb.OpenEJBException) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) NamingException(javax.naming.NamingException) HashSet(java.util.HashSet) BeanContext(org.apache.openejb.BeanContext) ModuleContext(org.apache.openejb.ModuleContext) Context(javax.naming.Context) Duration(org.apache.openejb.util.Duration) Injection(org.apache.openejb.Injection) Method(java.lang.reflect.Method) BeanContext(org.apache.openejb.BeanContext) EntityManagerFactory(javax.persistence.EntityManagerFactory) TimedObject(javax.ejb.TimedObject)

Example 4 with Injection

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

the class WsFactory method getObjectInstance.

@Override
public Object getObjectInstance(final Object object, final Name name, final Context context, final Hashtable environment) throws Exception {
    // ignore non resource-refs
    if (!(object instanceof ResourceRef)) {
        return null;
    }
    final Reference ref = (Reference) object;
    final Object value;
    if (NamingUtil.getProperty(ref, NamingUtil.JNDI_NAME) != null) {
        // lookup the value in JNDI
        value = super.getObjectInstance(object, name, context, environment);
    } else {
        // load service class which is used to construct the port
        final String serviceClassName = NamingUtil.getProperty(ref, NamingUtil.WS_CLASS);
        Class<? extends Service> serviceClass = Service.class;
        if (serviceClassName != null) {
            serviceClass = NamingUtil.loadClass(serviceClassName).asSubclass(Service.class);
            if (serviceClass == null) {
                throw new NamingException("Could not load service type class " + serviceClassName);
            }
        }
        // load the reference class which is the ultimate type of the port
        final Class<?> referenceClass = NamingUtil.loadClass(ref.getClassName());
        // if ref class is a subclass of Service, use it for the service class
        if (referenceClass != null && Service.class.isAssignableFrom(referenceClass)) {
            serviceClass = referenceClass.asSubclass(Service.class);
        }
        // PORT ID
        final String serviceId = NamingUtil.getProperty(ref, NamingUtil.WS_ID);
        // Service QName
        QName serviceQName = null;
        if (NamingUtil.getProperty(ref, NamingUtil.WS_QNAME) != null) {
            serviceQName = QName.valueOf(NamingUtil.getProperty(ref, NamingUtil.WS_QNAME));
        }
        // WSDL URL
        URL wsdlUrl = null;
        if (NamingUtil.getProperty(ref, NamingUtil.WSDL_URL) != null) {
            wsdlUrl = new URL(NamingUtil.getProperty(ref, NamingUtil.WSDL_URL));
        }
        // Port QName
        QName portQName = null;
        if (NamingUtil.getProperty(ref, NamingUtil.WS_PORT_QNAME) != null) {
            portQName = QName.valueOf(NamingUtil.getProperty(ref, NamingUtil.WS_PORT_QNAME));
        }
        // port refs
        List<PortRefData> portRefs = NamingUtil.getStaticValue(ref, "port-refs");
        if (portRefs == null) {
            portRefs = Collections.emptyList();
        }
        // HandlerChain
        List<HandlerChainData> handlerChains = NamingUtil.getStaticValue(ref, "handler-chains");
        if (handlerChains == null) {
            handlerChains = Collections.emptyList();
        }
        Collection<Injection> injections = NamingUtil.getStaticValue(ref, "injections");
        if (injections == null) {
            injections = Collections.emptyList();
        }
        final Properties properties = new Properties();
        properties.putAll(environment);
        final JaxWsServiceReference serviceReference = new JaxWsServiceReference(serviceId, serviceQName, serviceClass, portQName, referenceClass, wsdlUrl, portRefs, handlerChains, injections, properties);
        value = serviceReference.getObject();
    }
    return value;
}
Also used : HandlerChainData(org.apache.openejb.core.webservices.HandlerChainData) Reference(javax.naming.Reference) JaxWsServiceReference(org.apache.openejb.core.ivm.naming.JaxWsServiceReference) QName(javax.xml.namespace.QName) Service(javax.xml.ws.Service) Injection(org.apache.openejb.Injection) Properties(java.util.Properties) URL(java.net.URL) JaxWsServiceReference(org.apache.openejb.core.ivm.naming.JaxWsServiceReference) ResourceRef(org.apache.naming.ResourceRef) NamingException(javax.naming.NamingException) PortRefData(org.apache.openejb.core.webservices.PortRefData)

Example 5 with Injection

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

the class TomcatWebAppBuilder method updateInjections.

private static void updateInjections(final Collection<Injection> injections, final ClassLoader classLoader, final boolean keepInjection) {
    final Iterator<Injection> it = injections.iterator();
    final List<Injection> newOnes = new ArrayList<>();
    while (it.hasNext()) {
        final Injection injection = it.next();
        if (injection.getTarget() == null) {
            try {
                final Class<?> target = classLoader.loadClass(injection.getClassname());
                if (keepInjection) {
                    final Injection added = new Injection(injection.getJndiName(), injection.getName(), target);
                    newOnes.add(added);
                } else {
                    injection.setTarget(target);
                }
            } catch (final ClassNotFoundException cnfe) {
            // ignored
            }
        }
    }
    if (!newOnes.isEmpty()) {
        injections.addAll(newOnes);
    }
}
Also used : ArrayList(java.util.ArrayList) Injection(org.apache.openejb.Injection)

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