Search in sources :

Example 1 with Jndi

use of org.apache.openejb.jee.oejb3.Jndi in project tomee by apache.

the class OpenEjb2Conversion method convertEjbRefs.

public final void convertEjbRefs(final EjbJar ejbJar, final OpenejbJar openejbJar, final OpenejbJarType openejbJarType) {
    openejbJar.getProperties().putAll(openejbJarType.getProperties());
    final Map<String, EnterpriseBean> ejbs = ejbJar.getEnterpriseBeansByEjbName();
    final Map<String, EjbDeployment> deployments = openejbJar.getDeploymentsByEjbName();
    for (final org.apache.openejb.jee.oejb2.EnterpriseBean enterpriseBean : openejbJarType.getEnterpriseBeans()) {
        final EnterpriseBean ejb = ejbs.get(enterpriseBean.getEjbName());
        if (ejb == null) {
            // todo warn no such ejb in the ejb-jar.xml
            continue;
        }
        final Map<String, EjbRef> ejbRefs = ejb.getEjbRefMap();
        final EjbDeployment deployment = deployments.get(enterpriseBean.getEjbName());
        if (deployment == null) {
            // todo warn no such ejb in the ejb-jar.xml
            continue;
        }
        // Add WS Security
        if (enterpriseBean instanceof SessionBeanType) {
            final SessionBeanType sessionBean = (SessionBeanType) enterpriseBean;
            final WebServiceSecurityType webServiceSecurityType = sessionBean.getWebServiceSecurity();
            if (webServiceSecurityType != null) {
                if (webServiceSecurityType.getRealmName() != null) {
                    deployment.addProperty("webservice.security.realm", webServiceSecurityType.getRealmName());
                }
                if (webServiceSecurityType.getSecurityRealmName() != null) {
                    deployment.addProperty("webservice.security.securityRealm", webServiceSecurityType.getSecurityRealmName());
                }
                if (webServiceSecurityType.getTransportGuarantee() != null) {
                    deployment.addProperty("webservice.security.transportGarantee", webServiceSecurityType.getTransportGuarantee().value());
                } else {
                    deployment.addProperty("webservice.security.transportGarantee", "NONE");
                }
                if (webServiceSecurityType.getAuthMethod() != null) {
                    deployment.addProperty("webservice.security.authMethod", webServiceSecurityType.getAuthMethod().value());
                } else {
                    deployment.addProperty("webservice.security.authMethod", "NONE");
                }
                deployment.getProperties().putAll(webServiceSecurityType.getProperties());
            }
            if (sessionBean.getWebServiceAddress() != null) {
                deployment.getProperties().put("openejb.webservice.deployment.address", sessionBean.getWebServiceAddress());
            }
        }
        deployment.getProperties().putAll(enterpriseBean.getProperties());
        for (final String name : enterpriseBean.getLocalJndiName()) {
            deployment.getJndi().add(new org.apache.openejb.jee.oejb3.Jndi(name, "LocalHome"));
        }
        for (final String name : enterpriseBean.getJndiName()) {
            deployment.getJndi().add(new org.apache.openejb.jee.oejb3.Jndi(name, "RemoteHome"));
        }
        for (final Jndi jndi : enterpriseBean.getJndi()) {
            deployment.getJndi().add(new org.apache.openejb.jee.oejb3.Jndi(jndi.getName(), jndi.getInterface()));
        }
        final Set<String> ejbLinks = new TreeSet<String>();
        for (final EjbLink ejbLink : deployment.getEjbLink()) {
            ejbLinks.add(ejbLink.getEjbRefName());
        }
        for (final EjbRefType refType : enterpriseBean.getEjbRef()) {
            final String refName = refType.getRefName();
            if (ejbLinks.contains(refName)) {
                // don't overwrite refs that have been already set
                continue;
            }
            final String nsCorbaloc = refType.getNsCorbaloc();
            if (nsCorbaloc != null) {
                final EjbRef ref = ejbRefs.get(refName);
                if (ref != null) {
                    ref.setMappedName("jndi:" + nsCorbaloc);
                }
            } else if (refType.getEjbLink() != null) {
                final EjbRef ref = ejbRefs.get(refName);
                if (ref != null) {
                    ref.setEjbLink(refType.getEjbLink());
                }
            } else {
                final PatternType pattern = refType.getPattern();
                addEjbLink(deployment, refName, pattern);
            }
        }
        for (final EjbLocalRefType refType : enterpriseBean.getEjbLocalRef()) {
            final String refName = refType.getRefName();
            if (ejbLinks.contains(refName)) {
                // don't overwrite refs that have been already set
                continue;
            }
            if (refType.getEjbLink() != null) {
                final EjbRef ref = ejbRefs.get(refName);
                if (ref != null) {
                    ref.setEjbLink(refType.getEjbLink());
                }
            } else {
                final PatternType pattern = refType.getPattern();
                addEjbLink(deployment, refName, pattern);
            }
        }
    }
}
Also used : PatternType(org.apache.openejb.jee.oejb2.PatternType) WebServiceSecurityType(org.apache.openejb.jee.oejb2.WebServiceSecurityType) EjbRefType(org.apache.openejb.jee.oejb2.EjbRefType) EnterpriseBean(org.apache.openejb.jee.EnterpriseBean) EjbLocalRefType(org.apache.openejb.jee.oejb2.EjbLocalRefType) Jndi(org.apache.openejb.jee.oejb2.Jndi) EjbLink(org.apache.openejb.jee.oejb3.EjbLink) TreeSet(java.util.TreeSet) EjbRef(org.apache.openejb.jee.EjbRef) SessionBeanType(org.apache.openejb.jee.oejb2.SessionBeanType) EjbDeployment(org.apache.openejb.jee.oejb3.EjbDeployment)

Example 2 with Jndi

use of org.apache.openejb.jee.oejb3.Jndi in project tomee by apache.

the class AppInfoBuilder method build.

public AppInfo build(final AppModule appModule) throws OpenEJBException {
    // send an event so that it becomes pretty easy at this step to dynamically change the module description
    // before going into the info tree. Pretty easy to hack on portability issues.
    SystemInstance.get().fireEvent(new BeforeAppInfoBuilderEvent(appModule));
    final AppInfo appInfo = new AppInfo();
    appInfo.appId = appModule.getModuleId();
    appInfo.path = appModule.getJarLocation();
    appInfo.standaloneModule = appModule.isStandaloneModule() || appModule.isWebapp();
    appInfo.delegateFirst = appModule.isDelegateFirst();
    appInfo.watchedResources.addAll(appModule.getWatchedResources());
    appInfo.mbeans.addAll(appModule.getAdditionalLibMbeans());
    appInfo.jaxRsProviders.addAll(appModule.getJaxRsProviders());
    appInfo.properties.putAll(appModule.getProperties());
    if (appInfo.appId == null) {
        throw new IllegalArgumentException("AppInfo.appId cannot be null");
    }
    if (appInfo.path == null) {
        appInfo.path = appInfo.appId;
    }
    this.buildPojoConfiguration(appModule, appInfo);
    this.buildAppResources(appModule, appInfo);
    this.buildAppContainers(appModule, appInfo);
    this.buildAppServices(appModule, appInfo);
    // 
    // J2EE Connectors
    // 
    this.buildConnectorModules(appModule, appInfo);
    // 
    // Persistence Units
    // 
    this.buildPersistenceModules(appModule, appInfo);
    final List<String> containerIds = this.configFactory.getContainerIds();
    for (final ConnectorInfo connectorInfo : appInfo.connectors) {
        for (final MdbContainerInfo containerInfo : connectorInfo.inbound) {
            containerIds.add(containerInfo.id);
        }
    }
    for (final ContainerInfo containerInfo : appInfo.containers) {
        containerIds.add(containerInfo.id);
    }
    // 
    // EJB Jars
    // 
    final Map<EjbModule, EjbJarInfo> ejbJarInfos = new HashMap<EjbModule, EjbJarInfo>();
    for (final EjbModule ejbModule : appModule.getEjbModules()) {
        try {
            final EjbJarInfo ejbJarInfo = this.ejbJarInfoBuilder.buildInfo(ejbModule);
            ejbJarInfo.mbeans = ejbModule.getMbeans();
            final Map<String, EjbDeployment> deploymentsByEjbName = ejbModule.getOpenejbJar().getDeploymentsByEjbName();
            for (final EnterpriseBeanInfo bean : ejbJarInfo.enterpriseBeans) {
                final EjbDeployment d = deploymentsByEjbName.get(bean.ejbName);
                if (d.getContainerId() != null && !containerIds.contains(d.getContainerId())) {
                    for (final ContainerInfo containerInfo : appInfo.containers) {
                        if (containerInfo.id.endsWith("/" + d.getContainerId())) {
                            d.setContainerId(containerInfo.id);
                            break;
                        }
                    }
                }
                /*
                     * JRG - there's probably a better way of handling this, but this code handles the case when:
                     * 
                     * A connector with two or more inbound adapter is registered, causing two containers named with the format:
                     *     <moduleId>-<message listener interface>
                     * 
                     * This code adjusts the container id for the associated MDBs by sticking the message listener interface on the end.
                     * 
                     */
                if (bean instanceof MessageDrivenBeanInfo && !containerIds.contains(d.getContainerId()) && !skipMdb(bean)) {
                    final MessageDrivenBeanInfo mdb = (MessageDrivenBeanInfo) bean;
                    final String newContainerId = d.getContainerId() + "-" + mdb.mdbInterface;
                    if (containerIds.contains(newContainerId)) {
                        d.setContainerId(newContainerId);
                    }
                }
                if (!containerIds.contains(d.getContainerId()) && !skipMdb(bean)) {
                    final String msg = new Messages("org.apache.openejb.util.resources").format("config.noContainerFound", d.getContainerId(), d.getEjbName());
                    logger.fatal(msg);
                    throw new OpenEJBException(msg);
                }
                bean.containerId = d.getContainerId();
            }
            for (final PojoDeployment pojoDeployment : ejbModule.getOpenejbJar().getPojoDeployment()) {
                final IdPropertiesInfo info = new IdPropertiesInfo();
                info.id = pojoDeployment.getClassName();
                info.properties.putAll(pojoDeployment.getProperties());
                ejbJarInfo.pojoConfigurations.add(info);
            }
            ejbJarInfo.validationInfo = ValidatorBuilder.getInfo(ejbModule.getValidationConfig());
            ejbJarInfo.portInfos.addAll(this.configureWebservices(ejbModule.getWebservices()));
            ejbJarInfo.uniqueId = ejbModule.getUniqueId();
            ejbJarInfo.webapp = ejbModule.isWebapp();
            this.configureWebserviceSecurity(ejbJarInfo, ejbModule);
            ejbJarInfos.put(ejbModule, ejbJarInfo);
            appInfo.ejbJars.add(ejbJarInfo);
        } catch (final OpenEJBException e) {
            ConfigUtils.logger.warning("conf.0004", ejbModule.getJarLocation(), e.getMessage());
            throw e;
        }
    }
    // Create the JNDI info builder
    final JndiEncInfoBuilder jndiEncInfoBuilder = new JndiEncInfoBuilder(appInfo);
    if (appModule.getApplication() != null) {
        // TODO figure out how to prevent adding stuff to the module and comp contexts from the application
        // or maybe validate the xml so this won't happen.
        jndiEncInfoBuilder.build(appModule.getApplication(), appInfo.appId, null, appModule.getModuleUri(), new JndiEncInfo(), new JndiEncInfo());
    }
    final List<EnterpriseBeanInfo> beans = new ArrayList<EnterpriseBeanInfo>();
    // Build the JNDI tree for each ejb
    for (final EjbModule ejbModule : appModule.getEjbModules()) {
        final EjbJarInfo ejbJar = ejbJarInfos.get(ejbModule);
        final Map<String, EnterpriseBean> beanData = ejbModule.getEjbJar().getEnterpriseBeansByEjbName();
        for (final EnterpriseBeanInfo beanInfo : ejbJar.enterpriseBeans) {
            beans.add(beanInfo);
            // Get the ejb-jar.xml object
            final EnterpriseBean enterpriseBean = beanData.get(beanInfo.ejbName);
            // Build the JNDI info tree for the EJB
            jndiEncInfoBuilder.build(enterpriseBean, beanInfo.ejbName, ejbJar.moduleName, ejbModule.getModuleUri(), ejbJar.moduleJndiEnc, beanInfo.jndiEnc);
            jndiEncInfoBuilder.buildDependsOnRefs(enterpriseBean, beanInfo, ejbJar.moduleName);
        }
    }
    // Check for circular references in Singleton @DependsOn
    try {
        References.sort(beans, new References.Visitor<EnterpriseBeanInfo>() {

            @Override
            public String getName(final EnterpriseBeanInfo bean) {
                return bean.ejbDeploymentId;
            }

            @Override
            public Set<String> getReferences(final EnterpriseBeanInfo bean) {
                return new LinkedHashSet<String>(bean.dependsOn);
            }
        });
    } catch (final CircularReferencesException e) {
    // List<List> circuits = e.getCircuits();
    // TODO Seems we lost circular reference detection, or we do it elsewhere and don't need it here
    }
    // 
    // Application Clients
    // 
    this.buildClientModules(appModule, appInfo, jndiEncInfoBuilder);
    // 
    // Webapps
    // 
    this.buildWebModules(appModule, jndiEncInfoBuilder, appInfo);
    // 
    // Final AppInfo creation
    // 
    final List<URL> additionalLibraries = appModule.getAdditionalLibraries();
    for (final URL url : additionalLibraries) {
        final File file = toFile(url);
        try {
            appInfo.libs.add(file.getCanonicalPath());
        } catch (final IOException e) {
            throw new OpenEJBException("Invalid application lib path " + file.getAbsolutePath());
        }
    }
    if (appModule.getCmpMappings() != null) {
        try {
            appInfo.cmpMappingsXml = JpaJaxbUtil.marshal(EntityMappings.class, appModule.getCmpMappings());
        } catch (final JAXBException e) {
            throw new OpenEJBException("Unable to marshal cmp entity mappings", e);
        }
    }
    final ReportValidationResults reportValidationResults = new ReportValidationResults();
    reportValidationResults.deploy(appModule);
    logger.info("config.appLoaded", appInfo.path);
    appInfo.webAppAlone = appModule.isWebapp();
    return appInfo;
}
Also used : OpenEJBException(org.apache.openejb.OpenEJBException) EnterpriseBean(org.apache.openejb.jee.EnterpriseBean) Set(java.util.Set) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) PojoDeployment(org.apache.openejb.jee.oejb3.PojoDeployment) BeforeAppInfoBuilderEvent(org.apache.openejb.config.event.BeforeAppInfoBuilderEvent) URL(java.net.URL) EnterpriseBeanInfo(org.apache.openejb.assembler.classic.EnterpriseBeanInfo) MdbContainerInfo(org.apache.openejb.assembler.classic.MdbContainerInfo) MessageDrivenBeanInfo(org.apache.openejb.assembler.classic.MessageDrivenBeanInfo) IdPropertiesInfo(org.apache.openejb.assembler.classic.IdPropertiesInfo) Messages(org.apache.openejb.util.Messages) ConnectorInfo(org.apache.openejb.assembler.classic.ConnectorInfo) JndiEncInfo(org.apache.openejb.assembler.classic.JndiEncInfo) JAXBException(javax.xml.bind.JAXBException) IOException(java.io.IOException) WebAppInfo(org.apache.openejb.assembler.classic.WebAppInfo) AppInfo(org.apache.openejb.assembler.classic.AppInfo) References(org.apache.openejb.util.References) CircularReferencesException(org.apache.openejb.util.CircularReferencesException) ContainerInfo(org.apache.openejb.assembler.classic.ContainerInfo) MdbContainerInfo(org.apache.openejb.assembler.classic.MdbContainerInfo) EntityMappings(org.apache.openejb.jee.jpa.EntityMappings) EjbDeployment(org.apache.openejb.jee.oejb3.EjbDeployment) EjbJarInfo(org.apache.openejb.assembler.classic.EjbJarInfo) URLs.toFile(org.apache.openejb.util.URLs.toFile) File(java.io.File)

Example 3 with Jndi

use of org.apache.openejb.jee.oejb3.Jndi in project tomee by apache.

the class AutoConfig method processResourceRef.

private void processResourceRef(final ResourceRef ref, final EjbDeployment ejbDeployment, final AppResources appResources, final EjbModule ejbModule) throws OpenEJBException {
    // skip destinations with lookup name
    if (ref.getLookupName() != null) {
        return;
    }
    // skip destinations with a global jndi name
    final String mappedName = ref.getMappedName() == null ? "" : ref.getMappedName();
    if (mappedName.startsWith("jndi:")) {
        return;
    }
    final String refName = ref.getName();
    final String refType = getType(ref, ejbModule.getClassLoader());
    // skip references such as URLs which are automatically handled by the server
    if (ignoredReferenceTypes.contains(refType)) {
        final ResourceInfo resourceInfo = configFactory.getResourceInfo(refName.replace("java:", "").replace("comp/env/", ""));
        if (resourceInfo != null) {
            ref.setMappedName("jndi:" + (resourceInfo.id.startsWith("java:") ? resourceInfo.id : "openejb:Resource/" + resourceInfo.id));
        }
        return;
    }
    try {
        final Class<?> clazz = ejbModule.getClassLoader().loadClass(refType);
        if (clazz.isAnnotationPresent(ManagedBean.class)) {
            return;
        }
    } catch (final Throwable t) {
    // no-op
    }
    try {
        ResourceLink link = ejbDeployment.getResourceLink(refName);
        if (link == null) {
            String id = mappedName.length() == 0 ? ref.getName() : mappedName;
            if (id.startsWith("java:")) {
                id = id.substring("java:".length());
            }
            if (id.startsWith("/")) {
                id = id.substring(1);
            }
            try {
                final AppModule appModule = ejbModule.getAppModule();
                if (appModule != null) {
                    final String newId = findResourceId(appModule.getModuleId() + '/' + id.replace("java:", "").replaceAll("^comp/env/", ""), refType, new Properties(), appResources);
                    if (newId != null) {
                        // app scoped resources, try to find it without creating it first
                        id = getResourceId(ejbModule.getModuleId(), newId, refType, appResources);
                    } else {
                        id = getResourceId(ejbDeployment.getDeploymentId(), id, refType, appResources);
                    }
                } else {
                    id = getResourceId(ejbDeployment.getDeploymentId(), id, refType, appResources);
                }
            } catch (final OpenEJBException e) {
                // changing the message to be explicit
                throw new OpenEJBException("Can't find resource for " + ref.getOrigin() + ". (" + e.getMessage() + ")", e.getCause());
            }
            logger.info("Auto-linking resource-ref '" + refName + "' in bean " + ejbDeployment.getDeploymentId() + " to Resource(id=" + id + ")");
            link = new ResourceLink();
            link.setResId(id);
            link.setResRefName(refName);
            ejbDeployment.addResourceLink(link);
        } else {
            final String id = getResourceId(ejbDeployment.getDeploymentId(), link.getResId(), refType, appResources);
            link.setResId(id);
            link.setResRefName(refName);
        }
    } catch (final OpenEJBException ex) {
        if (!(ref instanceof ContextRef)) {
            throw ex;
        }
    }
}
Also used : ResourceInfo(org.apache.openejb.assembler.classic.ResourceInfo) OpenEJBException(org.apache.openejb.OpenEJBException) ResourceLink(org.apache.openejb.jee.oejb3.ResourceLink) PersistenceContextRef(org.apache.openejb.jee.PersistenceContextRef) Properties(java.util.Properties) SuperProperties(org.apache.openejb.util.SuperProperties)

Example 4 with Jndi

use of org.apache.openejb.jee.oejb3.Jndi in project tomee by apache.

the class ApplicationComposers method deployApp.

public void deployApp(final Object inputTestInstance) throws Exception {
    final ClassFinder testClassFinder = fixFakeClassFinder(inputTestInstance);
    final ClassLoader loader = testClass.getClassLoader();
    AppModule appModule = new AppModule(loader, testClass.getSimpleName());
    // Add the test case as an @ManagedBean
    final ManagedBean testBean;
    {
        final EjbJar ejbJar = new EjbJar();
        final OpenejbJar openejbJar = new OpenejbJar();
        testBean = ejbJar.addEnterpriseBean(new ManagedBean(testClass.getSimpleName(), testClass.getName(), true));
        testBean.localBean();
        testBean.setTransactionType(TransactionType.BEAN);
        final EjbDeployment ejbDeployment = openejbJar.addEjbDeployment(testBean);
        ejbDeployment.setDeploymentId(testClass.getName());
        final EjbModule ejbModule = new EjbModule(ejbJar, openejbJar);
        ejbModule.getProperties().setProperty("openejb.cdi.activated", "false");
        final FinderFactory.OpenEJBAnnotationFinder finder = new FinderFactory.OpenEJBAnnotationFinder(new ClassesArchive(ancestors(testClass)));
        ejbModule.setFinder(finder);
        if (finder.findMetaAnnotatedFields(Inject.class).size() + finder.findMetaAnnotatedMethods(Inject.class).size() > 0) {
            // "activate" cdi to avoid WARNINGs
            ejbModule.setBeans(new Beans());
        }
        appModule.getEjbModules().add(ejbModule);
    }
    final Map<String, URL> additionalDescriptors = descriptorsToMap(testClass.getAnnotation(org.apache.openejb.junit.Descriptors.class));
    final Map<String, URL> additionalDescriptorsNew = descriptorsToMap(testClass.getAnnotation(Descriptors.class));
    additionalDescriptors.putAll(additionalDescriptorsNew);
    Application application = null;
    int webModulesNb = 0;
    final Jars globalJarsAnnotation = testClass.getAnnotation(Jars.class);
    // Invoke the @Module producer methods to build out the AppModule
    int moduleNumber = 0;
    // we dont consider resources.xml to set an app as standalone or not
    int notBusinessModuleNumber = 0;
    final Map<Object, List<Method>> moduleMethods = new HashMap<>();
    findAnnotatedMethods(moduleMethods, Module.class);
    findAnnotatedMethods(moduleMethods, org.apache.openejb.junit.Module.class);
    for (final Map.Entry<Object, List<Method>> methods : moduleMethods.entrySet()) {
        moduleNumber += methods.getValue().size();
        for (final Method method : methods.getValue()) {
            final Object obj = method.invoke(methods.getKey());
            final Jars jarsAnnotation = method.getAnnotation(Jars.class);
            final Classes classesAnnotation = method.getAnnotation(Classes.class);
            final org.apache.openejb.junit.Classes classesAnnotationOld = method.getAnnotation(org.apache.openejb.junit.Classes.class);
            final boolean defaultConfig = method.getAnnotation(Default.class) != null;
            Class<?>[] classes = null;
            String[] excludes = null;
            Class<?>[] cdiInterceptors = null;
            Class<?>[] cdiAlternatives = null;
            Class<?>[] cdiStereotypes = null;
            Class<?>[] cdiDecorators = null;
            boolean cdi = false;
            boolean innerClassesAsBean = false;
            if (classesAnnotation != null) {
                classes = classesAnnotation.value();
                excludes = classesAnnotation.excludes();
                innerClassesAsBean = classesAnnotation.innerClassesAsBean();
                cdiInterceptors = classesAnnotation.cdiInterceptors();
                cdiDecorators = classesAnnotation.cdiDecorators();
                cdiAlternatives = classesAnnotation.cdiAlternatives();
                cdiStereotypes = classesAnnotation.cdiStereotypes();
                cdi = isCdi(classesAnnotation.cdi(), cdiInterceptors, cdiAlternatives, cdiStereotypes, cdiDecorators);
            } else if (classesAnnotationOld != null) {
                classes = classesAnnotationOld.value();
            }
            if (obj instanceof WebApp) {
                // will add the ejbmodule too
                final WebApp webApp = WebApp.class.cast(obj);
                if (webApp.getContextRoot() == null && classesAnnotation != null) {
                    webApp.contextRoot(classesAnnotation.context());
                }
                webModulesNb++;
                addWebApp(appModule, testBean, additionalDescriptors, method.getAnnotation(Descriptors.class), method.getAnnotation(JaxrsProviders.class), webApp, globalJarsAnnotation, jarsAnnotation, classes, excludes, cdiInterceptors, cdiAlternatives, cdiDecorators, cdiStereotypes, cdi, innerClassesAsBean, defaultConfig);
            } else if (obj instanceof WebModule) {
                // will add the ejbmodule too
                webModulesNb++;
                final WebModule webModule = (WebModule) obj;
                webModule.getAltDDs().putAll(additionalDescriptors);
                webModule.getAltDDs().putAll(descriptorsToMap(method.getAnnotation(Descriptors.class)));
                final EjbModule ejbModule = DeploymentLoader.addWebModule(webModule, appModule);
                ejbModule.getProperties().put(CdiScanner.OPENEJB_CDI_FILTER_CLASSLOADER, "false");
                if (cdi) {
                    ejbModule.setBeans(beans(new Beans(), cdiDecorators, cdiInterceptors, cdiAlternatives, cdiStereotypes));
                }
                Collection<File> files = findFiles(jarsAnnotation);
                if (defaultConfig) {
                    (files == null ? files = new LinkedList<>() : files).add(jarLocation(testClass));
                }
                webModule.setFinder(finderFromClasses(webModule, classes, files, excludes));
                ejbModule.setFinder(webModule.getFinder());
            } else if (obj instanceof EjbModule) {
                final EjbModule ejbModule = (EjbModule) obj;
                ejbModule.getAltDDs().putAll(additionalDescriptors);
                ejbModule.getAltDDs().putAll(descriptorsToMap(method.getAnnotation(Descriptors.class)));
                ejbModule.initAppModule(appModule);
                appModule.getEjbModules().add(ejbModule);
                if (cdi) {
                    ejbModule.setBeans(beans(new Beans(), cdiDecorators, cdiInterceptors, cdiAlternatives, cdiStereotypes));
                }
                Collection<File> files = findFiles(jarsAnnotation);
                if (defaultConfig) {
                    (files == null ? files = new LinkedList<>() : files).add(jarLocation(testClass));
                }
                ejbModule.setFinder(finderFromClasses(ejbModule, classes, files, excludes));
            } else if (obj instanceof EjbJar) {
                final EjbJar ejbJar = (EjbJar) obj;
                setId(ejbJar, method);
                final EjbModule ejbModule = new EjbModule(ejbJar);
                ejbModule.getAltDDs().putAll(additionalDescriptors);
                ejbModule.getAltDDs().putAll(descriptorsToMap(method.getAnnotation(Descriptors.class)));
                appModule.getEjbModules().add(ejbModule);
                if (cdi) {
                    ejbModule.setBeans(beans(new Beans(), cdiDecorators, cdiInterceptors, cdiAlternatives, cdiStereotypes));
                }
                Collection<File> files = findFiles(jarsAnnotation);
                if (defaultConfig) {
                    (files == null ? files = new LinkedList<>() : files).add(jarLocation(testClass));
                }
                ejbModule.setFinder(finderFromClasses(ejbModule, classes, files, excludes));
            } else if (obj instanceof EnterpriseBean) {
                final EnterpriseBean bean = (EnterpriseBean) obj;
                final EjbJar ejbJar = new EjbJar(method.getName());
                ejbJar.addEnterpriseBean(bean);
                final EjbModule ejbModule = new EjbModule(ejbJar);
                final Beans beans = new Beans();
                beans.addManagedClass(bean.getEjbClass());
                ejbModule.setBeans(beans);
                appModule.getEjbModules().add(ejbModule);
                if (cdi) {
                    ejbModule.setBeans(beans(new Beans(), cdiDecorators, cdiInterceptors, cdiAlternatives, cdiStereotypes));
                }
                Collection<File> files = findFiles(jarsAnnotation);
                if (defaultConfig) {
                    (files == null ? files = new LinkedList<>() : files).add(jarLocation(testClass));
                }
                ejbModule.setFinder(finderFromClasses(ejbModule, classes, files, excludes));
            } else if (obj instanceof Application) {
                application = (Application) obj;
                setId(application, method);
            } else if (obj instanceof Connector) {
                final Connector connector = (Connector) obj;
                setId(connector, method);
                appModule.getConnectorModules().add(new ConnectorModule(connector));
            } else if (obj instanceof Persistence) {
                final Persistence persistence = (Persistence) obj;
                appModule.addPersistenceModule(new PersistenceModule(appModule, implicitRootUrl(method.getAnnotation(PersistenceRootUrl.class)), persistence));
                notBusinessModuleNumber++;
            } else if (obj instanceof PersistenceUnit) {
                final PersistenceUnit unit = (PersistenceUnit) obj;
                appModule.addPersistenceModule(new PersistenceModule(appModule, implicitRootUrl(method.getAnnotation(PersistenceRootUrl.class)), new Persistence(unit)));
                notBusinessModuleNumber++;
            } else if (obj instanceof Beans) {
                final Beans beans = (Beans) obj;
                final EjbModule ejbModule = new EjbModule(new EjbJar(method.getName()));
                ejbModule.setBeans(beans);
                appModule.getEjbModules().add(ejbModule);
                if (cdi) {
                    ejbModule.setBeans(beans(beans, cdiDecorators, cdiInterceptors, cdiAlternatives, cdiStereotypes));
                }
                Collection<File> files = findFiles(jarsAnnotation);
                if (defaultConfig) {
                    (files == null ? files = new LinkedList<>() : files).add(jarLocation(testClass));
                }
                ejbModule.setFinder(finderFromClasses(ejbModule, classes, files, excludes));
            } else if (obj instanceof Class[]) {
                final Class[] beans = (Class[]) obj;
                final EjbModule ejbModule = new EjbModule(new EjbJar(method.getName()));
                ejbModule.setFinder(new AnnotationFinder(new ClassesArchive(beans)).link());
                ejbModule.setBeans(new Beans());
                appModule.getEjbModules().add(ejbModule);
            } else if (obj instanceof Class) {
                final Class bean = (Class) obj;
                final EjbModule ejbModule = new EjbModule(new EjbJar(method.getName()));
                ejbModule.setFinder(new AnnotationFinder(new ClassesArchive(bean)).link());
                ejbModule.setBeans(new Beans());
                appModule.getEjbModules().add(ejbModule);
            } else if (obj instanceof IAnnotationFinder) {
                final EjbModule ejbModule = new EjbModule(new EjbJar(method.getName()));
                ejbModule.setFinder((IAnnotationFinder) obj);
                ejbModule.setBeans(new Beans());
                appModule.getEjbModules().add(ejbModule);
            } else if (obj instanceof ClassesArchive) {
                final EjbModule ejbModule = new EjbModule(new EjbJar(method.getName()));
                ejbModule.setFinder(new AnnotationFinder((Archive) obj).link());
                ejbModule.setBeans(new Beans());
                appModule.getEjbModules().add(ejbModule);
            } else if (obj instanceof Resources) {
                final Resources asResources = Resources.class.cast(obj);
                appModule.getResources().addAll(asResources.getResource());
                appModule.getContainers().addAll(asResources.getContainer());
                notBusinessModuleNumber++;
            } else if (obj instanceof AppModule) {
                // we can probably go further here
                final AppModule module = (AppModule) obj;
                module.getAltDDs().putAll(additionalDescriptors);
                module.getAltDDs().putAll(descriptorsToMap(method.getAnnotation(Descriptors.class)));
                if (module.getWebModules().size() > 0) {
                    webModulesNb++;
                }
                appModule.getEjbModules().addAll(module.getEjbModules());
                appModule.getPersistenceModules().addAll(module.getPersistenceModules());
                appModule.getAdditionalLibMbeans().addAll(module.getAdditionalLibMbeans());
                appModule.getWebModules().addAll(module.getWebModules());
                appModule.getConnectorModules().addAll(module.getConnectorModules());
                appModule.getResources().addAll(module.getResources());
                appModule.getServices().addAll(module.getServices());
                appModule.getPojoConfigurations().putAll(module.getPojoConfigurations());
                appModule.getAdditionalLibraries().addAll(module.getAdditionalLibraries());
                appModule.getAltDDs().putAll(module.getAltDDs());
                appModule.getProperties().putAll(module.getProperties());
            } else {
                moduleNumber--;
            }
        }
    }
    final Classes classClasses = testClass.getAnnotation(Classes.class);
    if (classClasses != null) {
        final WebApp webapp = new WebApp();
        webapp.setContextRoot(classClasses.context());
        addWebApp(appModule, testBean, additionalDescriptors, null, null, webapp, globalJarsAnnotation, null, classClasses.value(), classClasses.excludes(), classClasses.cdiInterceptors(), classClasses.cdiAlternatives(), classClasses.cdiDecorators(), classClasses.cdiStereotypes(), classClasses.cdi(), classClasses.innerClassesAsBean(), testClass.getAnnotation(Default.class) != null);
        webModulesNb++;
        moduleNumber++;
    }
    // Application is final in AppModule, which is fine, so we'll create a new one and move everything
    if (application != null) {
        final AppModule newModule = new AppModule(appModule.getClassLoader(), appModule.getModuleId(), application, false);
        newModule.getClientModules().addAll(appModule.getClientModules());
        newModule.addPersistenceModules(appModule.getPersistenceModules());
        newModule.getEjbModules().addAll(appModule.getEjbModules());
        newModule.getConnectorModules().addAll(appModule.getConnectorModules());
        appModule = newModule;
    }
    // config for the app
    for (final Map.Entry<Object, List<Method>> method : findAnnotatedMethods(new HashMap<Object, List<Method>>(), ApplicationConfiguration.class).entrySet()) {
        for (final Method m : method.getValue()) {
            final Object o = m.invoke(method.getKey());
            if (Properties.class.isInstance(o)) {
                appModule.getProperties().putAll(Properties.class.cast(o));
            }
        }
    }
    // copy ejb into beans if cdi is activated and init finder
    for (final EjbModule ejb : appModule.getEjbModules()) {
        final EnterpriseBean[] enterpriseBeans = ejb.getEjbJar().getEnterpriseBeans();
        final Beans beans = ejb.getBeans();
        if (beans != null && ejb.getEjbJar() != null) {
            for (final EnterpriseBean bean : enterpriseBeans) {
                boolean found = false;
                for (final List<String> mc : beans.getManagedClasses().values()) {
                    if (mc.contains(bean.getEjbClass())) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    beans.addManagedClass(bean.getEjbClass());
                }
            }
        }
    }
    if (moduleNumber - notBusinessModuleNumber == 1 && webModulesNb == 1) {
        appModule.setStandloneWebModule();
    }
    if (webModulesNb > 0 && SystemInstance.get().getComponent(WebAppBuilder.class) == null) {
        SystemInstance.get().setComponent(WebAppBuilder.class, new LightweightWebAppBuilder());
    }
    final Context jndiContext = SystemInstance.get().getComponent(ContainerSystem.class).getJNDIContext();
    for (final EnvEntry entry : testBean.getEnvEntry()) {
        // set it in global jndi context since that's "app" entries and otherwise when we are no more in test bean context lookup fails
        final String name = entry.getName();
        final String jndi;
        if (name.startsWith("java:") || name.startsWith("comp/env")) {
            jndi = name;
        } else {
            jndi = "java:comp/env/" + name;
        }
        jndiContext.bind(jndi, entry.getEnvEntryValue());
    }
    appInfo = SystemInstance.get().getComponent(ConfigurationFactory.class).configureApplication(appModule);
    appContext = assembler.createApplication(appInfo);
    if (mockCdiContexts() && appContext.getWebBeansContext() != null) {
        ScopeHelper.startContexts(appContext.getWebBeansContext().getContextsService(), servletContext, session);
    }
    final BeanContext context = SystemInstance.get().getComponent(ContainerSystem.class).getBeanContext(testClass.getName());
    enrich(inputTestInstance, context);
    JavaSecurityManagers.setSystemProperty(Context.INITIAL_CONTEXT_FACTORY, InitContextFactory.class.getName());
    JavaSecurityManagers.setSystemProperty(OPENEJB_APPLICATION_COMPOSER_CONTEXT, appContext.getGlobalJndiContext());
    final List<Field> fields = new ArrayList<>(testClassFinder.findAnnotatedFields(AppResource.class));
    fields.addAll(testClassFinder.findAnnotatedFields(org.apache.openejb.junit.AppResource.class));
    for (final Field field : fields) {
        final Class<?> type = field.getType();
        if (AppModule.class.isAssignableFrom(type)) {
            field.setAccessible(true);
            field.set(inputTestInstance, appModule);
        } else if (Context.class.isAssignableFrom(type)) {
            field.setAccessible(true);
            field.set(inputTestInstance, new InitialContext(new Properties() {

                {
                    setProperty(Context.INITIAL_CONTEXT_FACTORY, LocalInitialContextFactory.class.getName());
                }
            }));
        } else if (ApplicationComposers.class.isAssignableFrom(type)) {
            field.setAccessible(true);
            field.set(inputTestInstance, this);
        } else if (ContextProvider.class.isAssignableFrom(type)) {
            RESTResourceFinder finder = SystemInstance.get().getComponent(RESTResourceFinder.class);
            if (finder == null || !ContextProvider.class.isInstance(finder)) {
                finder = new ContextProvider(finder);
                SystemInstance.get().setComponent(RESTResourceFinder.class, finder);
            }
            field.setAccessible(true);
            field.set(inputTestInstance, finder);
        } else {
            throw new IllegalArgumentException("can't find value for type " + type.getName());
        }
    }
    previous = ThreadContext.enter(new ThreadContext(context, null, Operation.BUSINESS));
    // switch back since next test will use another instance
    testClassFinders.put(this, testClassFinder);
}
Also used : ContainerSystem(org.apache.openejb.spi.ContainerSystem) AppModule(org.apache.openejb.config.AppModule) FilteredArchive(org.apache.xbean.finder.archive.FilteredArchive) ClassesArchive(org.apache.xbean.finder.archive.ClassesArchive) FileArchive(org.apache.xbean.finder.archive.FileArchive) JarArchive(org.apache.xbean.finder.archive.JarArchive) CompositeArchive(org.apache.xbean.finder.archive.CompositeArchive) Archive(org.apache.xbean.finder.archive.Archive) HashMap(java.util.HashMap) EjbModule(org.apache.openejb.config.EjbModule) ArrayList(java.util.ArrayList) Arrays.asList(java.util.Arrays.asList) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) RESTResourceFinder(org.apache.openejb.rest.RESTResourceFinder) Method(java.lang.reflect.Method) WebModule(org.apache.openejb.config.WebModule) ContextProvider(org.apache.openejb.testing.rest.ContextProvider) LinkedList(java.util.LinkedList) Persistence(org.apache.openejb.jee.jpa.unit.Persistence) BeanContext(org.apache.openejb.BeanContext) Collection(java.util.Collection) EjbDeployment(org.apache.openejb.jee.oejb3.EjbDeployment) Resources(org.apache.openejb.config.sys.Resources) ManagedBean(org.apache.openejb.jee.ManagedBean) Application(org.apache.openejb.jee.Application) Map(java.util.Map) HashMap(java.util.HashMap) File(java.io.File) AnnotationFinder(org.apache.xbean.finder.AnnotationFinder) IAnnotationFinder(org.apache.xbean.finder.IAnnotationFinder) Connector(org.apache.openejb.jee.Connector) EnterpriseBean(org.apache.openejb.jee.EnterpriseBean) IAnnotationFinder(org.apache.xbean.finder.IAnnotationFinder) InitContextFactory(org.apache.openejb.core.ivm.naming.InitContextFactory) Properties(java.util.Properties) URL(java.net.URL) ConnectorModule(org.apache.openejb.config.ConnectorModule) Field(java.lang.reflect.Field) OpenejbJar(org.apache.openejb.jee.oejb3.OpenejbJar) PersistenceUnit(org.apache.openejb.jee.jpa.unit.PersistenceUnit) ClassFinder(org.apache.xbean.finder.ClassFinder) EjbJar(org.apache.openejb.jee.EjbJar) EnvEntry(org.apache.openejb.jee.EnvEntry) WebContext(org.apache.openejb.core.WebContext) InitialContext(javax.naming.InitialContext) MockServletContext(org.apache.webbeans.web.lifecycle.test.MockServletContext) BeanContext(org.apache.openejb.BeanContext) Context(javax.naming.Context) ThreadContext(org.apache.openejb.core.ThreadContext) AppContext(org.apache.openejb.AppContext) ThreadContext(org.apache.openejb.core.ThreadContext) FinderFactory(org.apache.openejb.config.FinderFactory) PersistenceModule(org.apache.openejb.config.PersistenceModule) InitialContext(javax.naming.InitialContext) Beans(org.apache.openejb.jee.Beans) LightweightWebAppBuilder(org.apache.openejb.web.LightweightWebAppBuilder) ClassesArchive(org.apache.xbean.finder.archive.ClassesArchive) WebApp(org.apache.openejb.jee.WebApp)

Example 5 with Jndi

use of org.apache.openejb.jee.oejb3.Jndi in project tomee by apache.

the class JndiNameTest method test.

public void test() throws Exception {
    System.setProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY, InitContextFactory.class.getName());
    final ConfigurationFactory config = new ConfigurationFactory();
    final Assembler assembler = new Assembler();
    assembler.createProxyFactory(config.configureService(ProxyFactoryInfo.class));
    assembler.createTransactionManager(config.configureService(TransactionServiceInfo.class));
    assembler.createSecurityService(config.configureService(SecurityServiceInfo.class));
    // containers
    final StatelessSessionContainerInfo statelessContainerInfo = config.configureService(StatelessSessionContainerInfo.class);
    assembler.createContainer(statelessContainerInfo);
    // Setup the descriptor information
    final EjbModule ejbModule = new EjbModule(new EjbJar(), new OpenejbJar());
    ejbModule.getEjbJar().addEnterpriseBean(new StatelessBean(FooBean.class));
    final EjbDeployment ejbDeployment = new EjbDeployment(null, "FooBean", "FooBean");
    ejbDeployment.getJndi().add(new Jndi("thename", "Local"));
    ejbDeployment.getJndi().add(new Jndi("anothername", "Remote"));
    ejbDeployment.getJndi().add(new Jndi("loldstyle", "LocalHome"));
    ejbDeployment.getJndi().add(new Jndi("roldstyle", "RemoteHome"));
    ejbModule.getOpenejbJar().addEjbDeployment(ejbDeployment);
    assembler.createApplication(config.configureApplication(ejbModule));
    final InitialContext initialContext = new InitialContext();
    assertName(initialContext, Orange.class, "thename");
    assertName(initialContext, Red.class, "anothername");
    assertName(initialContext, LHYellow.class, "loldstyle");
    assertName(initialContext, RHGreen.class, "roldstyle");
}
Also used : StatelessSessionContainerInfo(org.apache.openejb.assembler.classic.StatelessSessionContainerInfo) InitContextFactory(org.apache.openejb.core.ivm.naming.InitContextFactory) Jndi(org.apache.openejb.jee.oejb3.Jndi) InitialContext(javax.naming.InitialContext) ProxyFactoryInfo(org.apache.openejb.assembler.classic.ProxyFactoryInfo) OpenejbJar(org.apache.openejb.jee.oejb3.OpenejbJar) TransactionServiceInfo(org.apache.openejb.assembler.classic.TransactionServiceInfo) StatelessBean(org.apache.openejb.jee.StatelessBean) EjbDeployment(org.apache.openejb.jee.oejb3.EjbDeployment) Assembler(org.apache.openejb.assembler.classic.Assembler) SecurityServiceInfo(org.apache.openejb.assembler.classic.SecurityServiceInfo) EjbJar(org.apache.openejb.jee.EjbJar)

Aggregations

EjbDeployment (org.apache.openejb.jee.oejb3.EjbDeployment)8 EnterpriseBean (org.apache.openejb.jee.EnterpriseBean)5 Jndi (org.apache.openejb.jee.oejb3.Jndi)4 OpenejbJar (org.apache.openejb.jee.oejb3.OpenejbJar)4 HashMap (java.util.HashMap)3 EjbJar (org.apache.openejb.jee.EjbJar)3 File (java.io.File)2 URL (java.net.URL)2 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 Properties (java.util.Properties)2 InitialContext (javax.naming.InitialContext)2 OpenEJBException (org.apache.openejb.OpenEJBException)2 ResourceLink (org.apache.openejb.jee.oejb3.ResourceLink)2 IOException (java.io.IOException)1 Field (java.lang.reflect.Field)1 Method (java.lang.reflect.Method)1 Arrays.asList (java.util.Arrays.asList)1 Collection (java.util.Collection)1 HashSet (java.util.HashSet)1