Search in sources :

Example 6 with BeanContext

use of org.apache.openejb.BeanContext 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 7 with BeanContext

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

the class JndiBuilder method build.

public void build(final EjbJarInfo ejbJar, final HashMap<String, BeanContext> deployments) {
    final JndiNameStrategy strategy = createStrategy(ejbJar, deployments);
    for (final EnterpriseBeanInfo beanInfo : ejbJar.enterpriseBeans) {
        final BeanContext beanContext = deployments.get(beanInfo.ejbDeploymentId);
        strategy.begin(beanContext);
        try {
            bind(ejbJar, beanContext, beanInfo, strategy);
        } finally {
            strategy.end();
        }
    }
}
Also used : BeanContext(org.apache.openejb.BeanContext)

Example 8 with BeanContext

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

the class JndiBuilder method bind.

private void bind(final String name, final Reference ref, final Bindings bindings, final EnterpriseBeanInfo beanInfo, final Class intrface) throws NamingException {
    if (name.startsWith("openejb/local/") || name.startsWith("openejb/remote/") || name.startsWith("openejb/localbean/") || name.startsWith("openejb/global/")) {
        final String externalName = name.replaceFirst("openejb/[^/]+/", "");
        if (bindings.contains(name)) {
            // We bind under two sections of jndi, only warn once.. the user doesn't need to be bothered with that detail
            if (name.startsWith("openejb/local/")) {
                logger.debug("Duplicate: Jndi(name=" + externalName + ")");
            }
            return;
        }
        try {
            openejbContext.bind(name, ref);
            bindings.add(name);
            if (!beanInfo.jndiNames.contains(externalName)) {
                beanInfo.jndiNames.add(externalName);
                final JndiNameInfo nameInfo = new JndiNameInfo();
                nameInfo.intrface = intrface == null ? null : intrface.getName();
                nameInfo.name = externalName;
                beanInfo.jndiNamess.add(nameInfo);
                if (!embeddedEjbContainerApi && // filtering internal bean
                !(beanInfo instanceof ManagedBeanInfo && ((ManagedBeanInfo) beanInfo).hidden)) {
                    logger.info("Jndi(name=" + externalName + ") --> Ejb(deployment-id=" + beanInfo.ejbDeploymentId + ")");
                }
            }
        } catch (final NameAlreadyBoundException e) {
            final BeanContext deployment = findNameOwner(name);
            if (deployment != null) {
                logger.error("Jndi(name=" + externalName + ") cannot be bound to Ejb(deployment-id=" + beanInfo.ejbDeploymentId + ").  Name already taken by Ejb(deployment-id=" + deployment.getDeploymentID() + ")");
            } else {
                logger.error("Jndi(name=" + externalName + ") cannot be bound to Ejb(deployment-id=" + beanInfo.ejbDeploymentId + ").  Name already taken by another object in the system.");
            }
            // the name in the exception that it throws
            if (failOnCollision) {
                throw new NameAlreadyBoundException(externalName);
            }
        }
    } else {
        try {
            openejbContext.bind(name, ref);
            logger.debug("bound ejb at name: " + name + ", ref: " + ref);
            bindings.add(name);
        } catch (final NameAlreadyBoundException e) {
            logger.error("Jndi name could not be bound; it may be taken by another ejb.  Jndi(name=" + name + ")");
            // the name in the exception that it throws
            throw new NameAlreadyBoundException(name);
        }
    }
}
Also used : BeanContext(org.apache.openejb.BeanContext) NameAlreadyBoundException(javax.naming.NameAlreadyBoundException)

Example 9 with BeanContext

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

the class JndiBuilder method bind.

public void bind(final EjbJarInfo ejbJarInfo, final BeanContext bean, final EnterpriseBeanInfo beanInfo, final JndiNameStrategy strategy) {
    // and we shouldn't need it
    if (BeanContext.Comp.class.equals(bean.getBeanClass())) {
        return;
    }
    final Bindings bindings = new Bindings();
    bean.set(Bindings.class, bindings);
    Reference simpleNameRef = null;
    final Object id = bean.getDeploymentID();
    try {
        if (bean.isLocalbean()) {
            final Class beanClass = bean.getBeanClass();
            final BeanContext.BusinessLocalBeanHome home = bean.getBusinessLocalBeanHome();
            final BusinessLocalBeanReference ref = new BusinessLocalBeanReference(home);
            optionalBind(bindings, ref, "openejb/Deployment/" + format(id, beanClass.getName(), InterfaceType.LOCALBEAN));
            // if the user inject the EJB using a parent class
            if (!bean.getBeanClass().isInterface()) {
                for (Class<?> clazz = bean.getBeanClass().getSuperclass(); !clazz.equals(Object.class); clazz = clazz.getSuperclass()) {
                    optionalBind(bindings, ref, "openejb/Deployment/" + format(id, clazz.getName(), InterfaceType.LOCALBEAN));
                }
            }
            final String internalName = "openejb/Deployment/" + format(id, beanClass.getName(), InterfaceType.BUSINESS_LOCALBEAN_HOME);
            bind(internalName, ref, bindings, beanInfo, beanClass);
            final String name = strategy.getName(beanClass, DEFAULT_NAME_KEY, JndiNameStrategy.Interface.LOCALBEAN);
            bind("openejb/local/" + name, ref, bindings, beanInfo, beanClass);
            bindJava(bean, beanClass, ref, bindings, beanInfo);
            if (USE_OLD_JNDI_NAMES) {
                bean.getModuleContext().getAppContext().getBindings().put(name, ref);
            }
            simpleNameRef = ref;
        }
    } catch (final NamingException e) {
        throw new OpenEJBRuntimeException("Unable to bind business remote deployment in jndi.", e);
    }
    try {
        for (final Class interfce : bean.getBusinessLocalInterfaces()) {
            final BeanContext.BusinessLocalHome home = bean.getBusinessLocalHome(interfce);
            final BusinessLocalReference ref = new BusinessLocalReference(home);
            optionalBind(bindings, ref, "openejb/Deployment/" + format(id, interfce.getName()));
            final String internalName = "openejb/Deployment/" + format(id, interfce.getName(), InterfaceType.BUSINESS_LOCAL);
            bind(internalName, ref, bindings, beanInfo, interfce);
            final String name = strategy.getName(interfce, DEFAULT_NAME_KEY, JndiNameStrategy.Interface.BUSINESS_LOCAL);
            final String externalName = "openejb/local/" + name;
            bind(externalName, ref, bindings, beanInfo, interfce);
            bindJava(bean, interfce, ref, bindings, beanInfo);
            if (USE_OLD_JNDI_NAMES) {
                bean.getModuleContext().getAppContext().getBindings().put(name, ref);
            }
            if (simpleNameRef == null) {
                simpleNameRef = ref;
            }
        }
    } catch (final NamingException e) {
        throw new OpenEJBRuntimeException("Unable to bind business local interface for deployment " + id, e);
    }
    try {
        for (final Class interfce : bean.getBusinessRemoteInterfaces()) {
            final BeanContext.BusinessRemoteHome home = bean.getBusinessRemoteHome(interfce);
            final BusinessRemoteReference ref = new BusinessRemoteReference(home);
            optionalBind(bindings, ref, "openejb/Deployment/" + format(id, interfce.getName(), null));
            final String internalName = "openejb/Deployment/" + format(id, interfce.getName(), InterfaceType.BUSINESS_REMOTE);
            bind(internalName, ref, bindings, beanInfo, interfce);
            final String name = strategy.getName(interfce, DEFAULT_NAME_KEY, JndiNameStrategy.Interface.BUSINESS_REMOTE);
            bind("openejb/local/" + name, ref, bindings, beanInfo, interfce);
            bind("openejb/remote/" + name, ref, bindings, beanInfo, interfce);
            bind("openejb/remote/" + computeGlobalName(bean, interfce), ref, bindings, beanInfo, interfce);
            bindJava(bean, interfce, ref, bindings, beanInfo);
            if (USE_OLD_JNDI_NAMES) {
                bean.getModuleContext().getAppContext().getBindings().put(name, ref);
            }
            if (simpleNameRef == null) {
                simpleNameRef = ref;
            }
        }
    } catch (final NamingException e) {
        throw new OpenEJBRuntimeException("Unable to bind business remote deployment in jndi.", e);
    }
    try {
        final Class localHomeInterface = bean.getLocalHomeInterface();
        if (localHomeInterface != null) {
            final ObjectReference ref = new ObjectReference(bean.getEJBLocalHome());
            String name = strategy.getName(bean.getLocalHomeInterface(), DEFAULT_NAME_KEY, JndiNameStrategy.Interface.LOCAL_HOME);
            bind("openejb/local/" + name, ref, bindings, beanInfo, localHomeInterface);
            optionalBind(bindings, ref, "openejb/Deployment/" + format(id, localHomeInterface.getName(), InterfaceType.EJB_LOCAL_HOME));
            name = "openejb/Deployment/" + format(id, bean.getLocalInterface().getName());
            bind(name, ref, bindings, beanInfo, localHomeInterface);
            name = "openejb/Deployment/" + format(id, bean.getLocalInterface().getName(), InterfaceType.EJB_LOCAL);
            bind(name, ref, bindings, beanInfo, localHomeInterface);
            bindJava(bean, localHomeInterface, ref, bindings, beanInfo);
            if (simpleNameRef == null) {
                simpleNameRef = ref;
            }
        }
    } catch (final NamingException e) {
        throw new OpenEJBRuntimeException("Unable to bind local home interface for deployment " + id, e);
    }
    try {
        final Class homeInterface = bean.getHomeInterface();
        if (homeInterface != null) {
            final ObjectReference ref = new ObjectReference(bean.getEJBHome());
            String name = strategy.getName(homeInterface, DEFAULT_NAME_KEY, JndiNameStrategy.Interface.REMOTE_HOME);
            bind("openejb/local/" + name, ref, bindings, beanInfo, homeInterface);
            bind("openejb/remote/" + name, ref, bindings, beanInfo, homeInterface);
            optionalBind(bindings, ref, "openejb/Deployment/" + format(id, homeInterface.getName(), InterfaceType.EJB_HOME));
            name = "openejb/Deployment/" + format(id, bean.getRemoteInterface().getName());
            bind(name, ref, bindings, beanInfo, homeInterface);
            name = "openejb/Deployment/" + format(id, bean.getRemoteInterface().getName(), InterfaceType.EJB_OBJECT);
            bind(name, ref, bindings, beanInfo, homeInterface);
            bindJava(bean, homeInterface, ref, bindings, beanInfo);
            if (simpleNameRef == null) {
                simpleNameRef = ref;
            }
        }
    } catch (final NamingException e) {
        throw new OpenEJBRuntimeException("Unable to bind remote home interface for deployment " + id, e);
    }
    try {
        if (simpleNameRef != null) {
            bindJava(bean, null, simpleNameRef, bindings, beanInfo);
        }
    } catch (final NamingException e) {
        throw new OpenEJBRuntimeException("Unable to bind simple java:global name in jndi", e);
    }
    try {
        if (MessageListener.class.equals(bean.getMdbInterface())) {
            final String destinationId = bean.getDestinationId();
            final String jndiName = "openejb/Resource/" + destinationId;
            final Reference reference = new IntraVmJndiReference(jndiName);
            final String deploymentId = id.toString();
            bind("openejb/local/" + deploymentId, reference, bindings, beanInfo, MessageListener.class);
            bind("openejb/remote/" + deploymentId, reference, bindings, beanInfo, MessageListener.class);
        }
    } catch (final NamingException e) {
        throw new OpenEJBRuntimeException("Unable to bind mdb destination in jndi.", e);
    } catch (final NoClassDefFoundError ncdfe) {
    // no-op: no jms API
    }
}
Also used : IntraVmJndiReference(org.apache.openejb.core.ivm.naming.IntraVmJndiReference) ObjectReference(org.apache.openejb.core.ivm.naming.ObjectReference) BusinessRemoteReference(org.apache.openejb.core.ivm.naming.BusinessRemoteReference) BusinessLocalBeanReference(org.apache.openejb.core.ivm.naming.BusinessLocalBeanReference) Reference(javax.naming.Reference) BusinessLocalReference(org.apache.openejb.core.ivm.naming.BusinessLocalReference) BusinessLocalReference(org.apache.openejb.core.ivm.naming.BusinessLocalReference) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) BeanContext(org.apache.openejb.BeanContext) IntraVmJndiReference(org.apache.openejb.core.ivm.naming.IntraVmJndiReference) ObjectReference(org.apache.openejb.core.ivm.naming.ObjectReference) BusinessLocalBeanReference(org.apache.openejb.core.ivm.naming.BusinessLocalBeanReference) NamingException(javax.naming.NamingException) BusinessRemoteReference(org.apache.openejb.core.ivm.naming.BusinessRemoteReference)

Example 10 with BeanContext

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

the class JndiBuilder method bindJava.

private void bindJava(final BeanContext cdi, final Class intrface, final Reference ref, final Bindings bindings, final EnterpriseBeanInfo beanInfo) throws NamingException {
    final ModuleContext module = cdi.getModuleContext();
    final AppContext application = module.getAppContext();
    final Context moduleContext = module.getModuleJndiContext();
    final Context appContext = application.getAppJndiContext();
    final Context globalContext = application.getGlobalJndiContext();
    final String appName = application.isStandaloneModule() ? "" : application.getId() + "/";
    String moduleName = moduleName(cdi);
    if (moduleName.startsWith("/")) {
        moduleName = moduleName.substring(1);
    }
    String beanName = cdi.getEjbName();
    if (intrface != null) {
        beanName = beanName + "!" + intrface.getName();
    }
    final String globalName = "global/" + appName + moduleName + beanName;
    try {
        if (embeddedEjbContainerApi && !(beanInfo instanceof ManagedBeanInfo && ((ManagedBeanInfo) beanInfo).hidden)) {
            logger.info(String.format("Jndi(name=\"java:%s\")", globalName));
        }
        globalContext.bind(globalName, ref);
        application.getBindings().put(globalName, ref);
        bind("openejb/global/" + globalName, ref, bindings, beanInfo, intrface);
    } catch (final NameAlreadyBoundException e) {
        // one interface in more than one role (e.g. both Local and Remote
        return;
    }
    appContext.bind("app/" + moduleName + beanName, ref);
    application.getBindings().put("app/" + moduleName + beanName, ref);
    final String moduleJndi = "module/" + beanName;
    moduleContext.bind(moduleJndi, ref);
    // contextual if the same ejb (api) is deployed in 2 wars of an ear
    ContextualEjbLookup contextual = ContextualEjbLookup.class.cast(application.getBindings().get(moduleJndi));
    if (contextual == null) {
        final Map<BeanContext, Object> potentials = new HashMap<>();
        contextual = new ContextualEjbLookup(potentials, ref);
        // TODO: we shouldn't do it but use web bindings
        application.getBindings().put(moduleJndi, contextual);
    }
    contextual.potentials.put(cdi, ref);
}
Also used : BeanContext(org.apache.openejb.BeanContext) ModuleContext(org.apache.openejb.ModuleContext) Context(javax.naming.Context) AppContext(org.apache.openejb.AppContext) BeanContext(org.apache.openejb.BeanContext) NameAlreadyBoundException(javax.naming.NameAlreadyBoundException) HashMap(java.util.HashMap) AppContext(org.apache.openejb.AppContext) ModuleContext(org.apache.openejb.ModuleContext)

Aggregations

BeanContext (org.apache.openejb.BeanContext)198 OpenEJBException (org.apache.openejb.OpenEJBException)40 ThreadContext (org.apache.openejb.core.ThreadContext)40 Method (java.lang.reflect.Method)38 ContainerSystem (org.apache.openejb.spi.ContainerSystem)28 ArrayList (java.util.ArrayList)27 AppContext (org.apache.openejb.AppContext)26 TransactionPolicy (org.apache.openejb.core.transaction.TransactionPolicy)26 NamingException (javax.naming.NamingException)24 InterceptorData (org.apache.openejb.core.interceptor.InterceptorData)23 Context (javax.naming.Context)22 ApplicationException (org.apache.openejb.ApplicationException)20 HashMap (java.util.HashMap)19 EJBLocalObject (javax.ejb.EJBLocalObject)18 EJBObject (javax.ejb.EJBObject)18 SystemException (org.apache.openejb.SystemException)18 OpenEJBRuntimeException (org.apache.openejb.OpenEJBRuntimeException)17 ModuleContext (org.apache.openejb.ModuleContext)16 EjbTransactionUtil.createTransactionPolicy (org.apache.openejb.core.transaction.EjbTransactionUtil.createTransactionPolicy)16 FinderException (javax.ejb.FinderException)14