Search in sources :

Example 21 with ContainerSystem

use of org.apache.openejb.spi.ContainerSystem 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<Class>();
    for (final String businessLocal : bean.businessLocal) {
        businessLocals.add(loadClass(businessLocal, "classNotFound.businessLocal"));
    }
    final List<Class> businessRemotes = new ArrayList<Class>();
    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<?>>();
    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<Method>();
            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 22 with ContainerSystem

use of org.apache.openejb.spi.ContainerSystem in project tomee by apache.

the class StartDeploymentTest method deployment.

@Test
public void deployment() {
    final ContainerSystem containerSystem = SystemInstance.get().getComponent(ContainerSystem.class);
    assertNotNull(containerSystem.getAppContext("start"));
    assertNotNull(containerSystem.getAppContext("start2"));
}
Also used : ContainerSystem(org.apache.openejb.spi.ContainerSystem) Test(org.junit.Test)

Example 23 with ContainerSystem

use of org.apache.openejb.spi.ContainerSystem in project tomee by apache.

the class BeanPropertiesTest method testOverrideAdd.

public void testOverrideAdd() throws Exception {
    final ConfigurationFactory config = new ConfigurationFactory();
    final Assembler assembler = new Assembler();
    {
        // setup the system
        assembler.createTransactionManager(config.configureService(TransactionServiceInfo.class));
        assembler.createSecurityService(config.configureService(SecurityServiceInfo.class));
    }
    {
        SystemInstance.get().getProperties().put("WidgetBean.color", "orange");
        final Map<String, String> map = new HashMap<String, String>();
        final File app = Archives.fileArchive(map, WidgetBean.class);
        assembler.createApplication(config.configureApplication(app));
    }
    final ContainerSystem containerSystem = SystemInstance.get().getComponent(ContainerSystem.class);
    assertContexts(containerSystem);
}
Also used : ContainerSystem(org.apache.openejb.spi.ContainerSystem) Assembler(org.apache.openejb.assembler.classic.Assembler) HashMap(java.util.HashMap) Map(java.util.Map) File(java.io.File)

Example 24 with ContainerSystem

use of org.apache.openejb.spi.ContainerSystem in project tomee by apache.

the class BeanPropertiesTest method testOverrideFromModuleProperties.

public void testOverrideFromModuleProperties() throws Exception {
    final ConfigurationFactory config = new ConfigurationFactory();
    final Assembler assembler = new Assembler();
    {
        // setup the system
        assembler.createTransactionManager(config.configureService(TransactionServiceInfo.class));
        assembler.createSecurityService(config.configureService(SecurityServiceInfo.class));
    }
    {
        final Map<String, String> map = new HashMap<String, String>();
        map.put("META-INF/openejb-jar.xml", "<openejb-jar>\n" + "  <ejb-deployment ejb-name=\"WidgetBean\">\n" + "    <properties>\n" + "      color=white\n" + "    </properties>\n" + "  </ejb-deployment>\n" + "</openejb-jar>");
        map.put("META-INF/module.properties", "WidgetBean.color=orange");
        final File app = Archives.fileArchive(map, WidgetBean.class);
        assembler.createApplication(config.configureApplication(app));
    }
    final ContainerSystem containerSystem = SystemInstance.get().getComponent(ContainerSystem.class);
    assertContexts(containerSystem);
}
Also used : ContainerSystem(org.apache.openejb.spi.ContainerSystem) Assembler(org.apache.openejb.assembler.classic.Assembler) HashMap(java.util.HashMap) Map(java.util.Map) File(java.io.File)

Example 25 with ContainerSystem

use of org.apache.openejb.spi.ContainerSystem in project tomee by apache.

the class TomcatWebAppBuilder method startInternal.

/**
     * {@inheritDoc}
     */
//    @Override
private void startInternal(final StandardContext standardContext) {
    if (isIgnored(standardContext)) {
        return;
    }
    final CoreContainerSystem cs = getContainerSystem();
    final Assembler a = getAssembler();
    if (a == null) {
        logger.warning("OpenEJB has not been initialized so war will not be scanned for nested modules " + standardContext.getPath());
        return;
    }
    AppContext appContext = null;
    //Look for context info, maybe context is already scanned
    ContextInfo contextInfo = getContextInfo(standardContext);
    ClassLoader classLoader = standardContext.getLoader().getClassLoader();
    // bind jta before the app starts to ensure we have it in CDI
    final Thread thread = Thread.currentThread();
    final ClassLoader originalLoader = thread.getContextClassLoader();
    thread.setContextClassLoader(classLoader);
    final String listenerName = standardContext.getNamingContextListener().getName();
    ContextAccessController.setWritable(listenerName, standardContext.getNamingToken());
    try {
        final Context comp = Context.class.cast(ContextBindings.getClassLoader().lookup("comp"));
        // bind TransactionManager
        final TransactionManager transactionManager = SystemInstance.get().getComponent(TransactionManager.class);
        safeBind(comp, "TransactionManager", transactionManager);
        // bind TransactionSynchronizationRegistry
        final TransactionSynchronizationRegistry synchronizationRegistry = SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class);
        safeBind(comp, "TransactionSynchronizationRegistry", synchronizationRegistry);
    } catch (final NamingException e) {
    // no-op
    } finally {
        thread.setContextClassLoader(originalLoader);
        ContextAccessController.setReadOnly(listenerName);
    }
    if (contextInfo == null) {
        final AppModule appModule = loadApplication(standardContext);
        appModule.getProperties().put("loader.from", "tomcat");
        final boolean skipTomeeResourceWrapping = !"true".equalsIgnoreCase(SystemInstance.get().getProperty("tomee.tomcat.resource.wrap", "true"));
        if (!skipTomeeResourceWrapping && OpenEJBNamingResource.class.isInstance(standardContext.getNamingResources())) {
            // we can get the same resource twice as in tomcat
            final Collection<String> importedNames = new ArrayList<>();
            // add them to the app as resource
            final boolean forceDataSourceWrapping = "true".equalsIgnoreCase(SystemInstance.get().getProperty("tomee.tomcat.datasource.wrap", "false"));
            final OpenEJBNamingResource nr = (OpenEJBNamingResource) standardContext.getNamingResources();
            for (final ResourceBase resource : nr.getTomcatResources()) {
                final String name = resource.getName();
                // already init (org.apache.catalina.core.NamingContextListener.addResource())
                // skip wrapping to ensure resource consistency
                final boolean isDataSource = DataSource.class.getName().equals(resource.getType());
                final boolean isAlreadyCreated = ContextResource.class.isInstance(resource) && ContextResource.class.cast(resource).getSingleton() && isDataSource;
                if (!importedNames.contains(name)) {
                    importedNames.add(name);
                } else {
                    continue;
                }
                boolean found = false;
                for (final ResourceInfo r : SystemInstance.get().getComponent(OpenEjbConfiguration.class).facilities.resources) {
                    if (r.id.equals(name)) {
                        nr.removeResource(name);
                        found = true;
                        logger.warning(name + " resource was defined in both tomcat and tomee so removing tomcat one");
                        break;
                    }
                }
                if (!found) {
                    final Resource newResource;
                    if (forceDataSourceWrapping || (!isAlreadyCreated && isDataSource)) {
                        // we forward it to TomEE datasources
                        newResource = new Resource(name, resource.getType());
                        boolean jta = false;
                        final Properties properties = newResource.getProperties();
                        final Iterator<String> params = resource.listProperties();
                        while (params.hasNext()) {
                            final String paramName = params.next();
                            final String paramValue = (String) resource.getProperty(paramName);
                            // handling some param name conversion to OpenEJB style
                            if ("driverClassName".equals(paramName)) {
                                properties.setProperty("JdbcDriver", paramValue);
                            } else if ("url".equals(paramName)) {
                                properties.setProperty("JdbcUrl", paramValue);
                            } else {
                                properties.setProperty(paramName, paramValue);
                            }
                            if ("JtaManaged".equalsIgnoreCase(paramName)) {
                                jta = Boolean.parseBoolean(paramValue);
                            }
                        }
                        if (!jta) {
                            properties.setProperty("JtaManaged", "false");
                        }
                    } else {
                        // custom type, let it be created
                        newResource = new Resource(name, resource.getType(), "org.apache.tomee:ProvidedByTomcat");
                        final Properties properties = newResource.getProperties();
                        properties.setProperty("jndiName", newResource.getId());
                        properties.setProperty("appName", getId(standardContext));
                        properties.setProperty("factory", (String) resource.getProperty("factory"));
                        final Reference reference = createReference(resource);
                        if (reference != null) {
                            properties.put("reference", reference);
                        }
                    }
                    appModule.getResources().add(newResource);
                }
            }
        }
        if (appModule != null) {
            try {
                contextInfo = addContextInfo(Contexts.getHostname(standardContext), standardContext);
                // ensure to do it before an exception can be thrown
                contextInfo.standardContext = standardContext;
                contextInfo.appInfo = configurationFactory.configureApplication(appModule);
                final Boolean autoDeploy = DeployerEjb.AUTO_DEPLOY.get();
                contextInfo.appInfo.autoDeploy = autoDeploy == null || autoDeploy;
                DeployerEjb.AUTO_DEPLOY.remove();
                if (!appModule.isWebapp()) {
                    classLoader = appModule.getClassLoader();
                } else {
                    final ClassLoader loader = standardContext.getLoader().getClassLoader();
                    if (loader instanceof TomEEWebappClassLoader) {
                        final TomEEWebappClassLoader tomEEWebappClassLoader = (TomEEWebappClassLoader) loader;
                        for (final URL url : appModule.getWebModules().iterator().next().getAddedUrls()) {
                            tomEEWebappClassLoader.addURL(url);
                        }
                    }
                }
                setFinderOnContextConfig(standardContext, appModule);
                servletContextHandler.getContexts().put(classLoader, standardContext.getServletContext());
                try {
                    appContext = a.createApplication(contextInfo.appInfo, classLoader);
                } finally {
                    servletContextHandler.getContexts().remove(classLoader);
                }
                // todo add watched resources to context
                eagerInitOfLocalBeanProxies(appContext.getBeanContexts(), classLoader);
            } catch (final Exception e) {
                logger.error("Unable to deploy collapsed ear in war " + standardContext, e);
                undeploy(standardContext, contextInfo);
                // just to force tomee to start without EE part
                if (System.getProperty(TOMEE_EAT_EXCEPTION_PROP) == null) {
                    final TomEERuntimeException tre = new TomEERuntimeException(e);
                    final DeploymentExceptionManager dem = SystemInstance.get().getComponent(DeploymentExceptionManager.class);
                    dem.saveDeploymentException(contextInfo.appInfo, tre);
                    throw tre;
                }
                return;
            }
        }
    } else {
        contextInfo.standardContext = standardContext;
        if (contextInfo.module != null && contextInfo.module.getFinder() != null) {
            // TODO: make it more explicit or less hacky not using properties
            final OpenEJBContextConfig openEJBContextConfig = findOpenEJBContextConfig(standardContext);
            if (openEJBContextConfig != null) {
                openEJBContextConfig.finder(contextInfo.module.getFinder(), contextInfo.module.getClassLoader());
            }
        }
    }
    final String id = getId(standardContext);
    WebAppInfo webAppInfo = null;
    // appInfo is null when deployment fails
    if (contextInfo.appInfo != null) {
        for (final WebAppInfo w : contextInfo.appInfo.webApps) {
            if (id.equals(getId(w.host, w.contextRoot, contextInfo.version)) || id.equals(getId(w.host, w.moduleId, contextInfo.version))) {
                if (webAppInfo == null) {
                    webAppInfo = w;
                } else if (w.host != null && w.host.equals(Contexts.getHostname(standardContext))) {
                    webAppInfo = w;
                }
                break;
            }
        }
        if (appContext == null) {
            appContext = cs.getAppContext(contextInfo.appInfo.appId);
        }
    }
    if (webAppInfo != null) {
        if (appContext == null) {
            appContext = getContainerSystem().getAppContext(contextInfo.appInfo.appId);
        }
        // ensure matching (see getId() usage)
        webAppInfo.host = Contexts.getHostname(standardContext);
        webAppInfo.contextRoot = standardContext.getPath();
        // save jsf stuff
        final Map<String, Set<String>> scannedJsfClasses = new HashMap<String, Set<String>>();
        for (final ClassListInfo info : webAppInfo.jsfAnnotatedClasses) {
            scannedJsfClasses.put(info.name, info.list);
        }
        jsfClasses.put(classLoader, scannedJsfClasses);
        try {
            // determine the injections
            final Set<Injection> injections = new HashSet<Injection>();
            injections.addAll(appContext.getInjections());
            if (!contextInfo.appInfo.webAppAlone) {
                updateInjections(injections, classLoader, false);
                for (final BeanContext bean : appContext.getBeanContexts()) {
                    // TODO: how if the same class in multiple webapps?
                    updateInjections(bean.getInjections(), classLoader, true);
                }
            }
            injections.addAll(new InjectionBuilder(classLoader).buildInjections(webAppInfo.jndiEnc));
            // merge OpenEJB jndi into Tomcat jndi
            final TomcatJndiBuilder jndiBuilder = new TomcatJndiBuilder(standardContext, webAppInfo, injections);
            NamingUtil.setCurrentContext(standardContext);
            try {
                jndiBuilder.mergeJndi();
            } finally {
                NamingUtil.setCurrentContext(null);
            }
            // create EMF included in this webapp when nested in an ear
            for (final PersistenceUnitInfo unitInfo : contextInfo.appInfo.persistenceUnits) {
                if (unitInfo.webappName != null && unitInfo.webappName.equals(webAppInfo.moduleId)) {
                    try {
                        final ReloadableEntityManagerFactory remf = (ReloadableEntityManagerFactory) SystemInstance.get().getComponent(ContainerSystem.class).getJNDIContext().lookup(Assembler.PERSISTENCE_UNIT_NAMING_CONTEXT + unitInfo.id);
                        remf.overrideClassLoader(classLoader);
                        remf.createDelegate();
                    } catch (final NameNotFoundException nnfe) {
                        logger.warning("Can't find " + unitInfo.id + " persistence unit");
                    }
                }
            }
            // add WebDeploymentInfo to ContainerSystem
            final WebContext webContext = new WebContext(appContext);
            webContext.setServletContext(standardContext.getServletContext());
            webContext.setJndiEnc(new InitialContext());
            webContext.setClassLoader(classLoader);
            webContext.setId(webAppInfo.moduleId);
            webContext.setContextRoot(webAppInfo.contextRoot);
            webContext.setHost(webAppInfo.host);
            webContext.setBindings(new HashMap<String, Object>());
            webContext.getInjections().addAll(injections);
            appContext.getWebContexts().add(webContext);
            cs.addWebContext(webContext);
            standardContext.getServletContext().setAttribute("openejb.web.context", webContext);
            if (!contextInfo.appInfo.webAppAlone) {
                final List<BeanContext> beanContexts = assembler.initEjbs(classLoader, contextInfo.appInfo, appContext, injections, new ArrayList<BeanContext>(), webAppInfo.moduleId);
                OpenEJBLifecycle.CURRENT_APP_INFO.set(contextInfo.appInfo);
                servletContextHandler.getContexts().put(classLoader, standardContext.getServletContext());
                try {
                    new CdiBuilder().build(contextInfo.appInfo, appContext, beanContexts, webContext);
                } catch (final Exception e) {
                    final DeploymentExceptionManager dem = SystemInstance.get().getComponent(DeploymentExceptionManager.class);
                    if (dem != null) {
                        dem.saveDeploymentException(contextInfo.appInfo, e);
                    }
                    throw e;
                } finally {
                    servletContextHandler.getContexts().remove(classLoader);
                    OpenEJBLifecycle.CURRENT_APP_INFO.remove();
                }
                assembler.startEjbs(true, beanContexts);
                assembler.bindGlobals(appContext.getBindings());
                eagerInitOfLocalBeanProxies(beanContexts, standardContext.getLoader().getClassLoader());
                deployWebServicesIfEjbCreatedHere(contextInfo.appInfo, beanContexts);
            }
            // jndi bindings
            webContext.getBindings().putAll(appContext.getBindings());
            webContext.getBindings().putAll(getJndiBuilder(classLoader, webAppInfo, injections, appContext.getProperties()).buildBindings(JndiEncBuilder.JndiScope.comp));
            final JavaeeInstanceManager instanceManager = new JavaeeInstanceManager(standardContext, webContext);
            standardContext.setInstanceManager(instanceManager);
            instanceManagers.put(classLoader, instanceManager);
            standardContext.getServletContext().setAttribute(InstanceManager.class.getName(), standardContext.getInstanceManager());
        } catch (final Exception e) {
            logger.error("Error merging Java EE JNDI entries in to war " + standardContext.getPath() + ": Exception: " + e.getMessage(), e);
            if (System.getProperty(TOMEE_EAT_EXCEPTION_PROP) == null) {
                final DeploymentExceptionManager dem = SystemInstance.get().getComponent(DeploymentExceptionManager.class);
                if (dem != null && dem.getDeploymentException(contextInfo.appInfo) != null) {
                    if (RuntimeException.class.isInstance(e)) {
                        throw RuntimeException.class.cast(e);
                    }
                    throw new TomEERuntimeException(e);
                }
            }
        }
        final WebBeansContext webBeansContext = appContext.getWebBeansContext();
        if (webBeansContext != null && webBeansContext.getBeanManagerImpl().isInUse()) {
            OpenEJBLifecycle.initializeServletContext(standardContext.getServletContext(), webBeansContext);
        }
    }
    // router
    final URL routerConfig = RouterValve.configurationURL(standardContext.getServletContext());
    if (routerConfig != null) {
        final RouterValve filter = new RouterValve();
        filter.setPrefix(standardContext.getName());
        filter.setConfigurationPath(routerConfig);
        standardContext.getPipeline().addValve(filter);
    }
    // register realm to have it in TomcatSecurityService
    final Realm realm = standardContext.getRealm();
    realms.put(standardContext.getName(), realm);
}
Also used : CoreContainerSystem(org.apache.openejb.core.CoreContainerSystem) ContainerSystem(org.apache.openejb.spi.ContainerSystem) AppModule(org.apache.openejb.config.AppModule) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) InstanceManager(org.apache.tomcat.InstanceManager) ArrayList(java.util.ArrayList) RouterValve(org.apache.tomee.catalina.routing.RouterValve) WebAppInfo(org.apache.openejb.assembler.classic.WebAppInfo) NamingException(javax.naming.NamingException) DeploymentExceptionManager(org.apache.openejb.assembler.classic.DeploymentExceptionManager) HashSet(java.util.HashSet) InjectionBuilder(org.apache.openejb.assembler.classic.InjectionBuilder) ResourceInfo(org.apache.openejb.assembler.classic.ResourceInfo) ContextResource(org.apache.tomcat.util.descriptor.web.ContextResource) WebResource(org.apache.catalina.WebResource) Resource(org.apache.openejb.config.sys.Resource) OpenEJBContextConfig(org.apache.catalina.startup.OpenEJBContextConfig) CoreContainerSystem(org.apache.openejb.core.CoreContainerSystem) Injection(org.apache.openejb.Injection) DataSource(javax.sql.DataSource) ContextResource(org.apache.tomcat.util.descriptor.web.ContextResource) BeanContext(org.apache.openejb.BeanContext) TransactionManager(javax.transaction.TransactionManager) TransactionSynchronizationRegistry(javax.transaction.TransactionSynchronizationRegistry) CdiBuilder(org.apache.openejb.cdi.CdiBuilder) Assembler(org.apache.openejb.assembler.classic.Assembler) DirResourceSet(org.apache.catalina.webresources.DirResourceSet) Set(java.util.Set) WebResourceSet(org.apache.catalina.WebResourceSet) HashSet(java.util.HashSet) WebContext(org.apache.openejb.core.WebContext) ResourceBase(org.apache.tomcat.util.descriptor.web.ResourceBase) Properties(java.util.Properties) URL(java.net.URL) ClassListInfo(org.apache.openejb.assembler.classic.ClassListInfo) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) WebBeansContext(org.apache.webbeans.config.WebBeansContext) Realm(org.apache.catalina.Realm) WebContext(org.apache.openejb.core.WebContext) InitialContext(javax.naming.InitialContext) WebBeansContext(org.apache.webbeans.config.WebBeansContext) BeanContext(org.apache.openejb.BeanContext) Context(javax.naming.Context) ServletContext(javax.servlet.ServletContext) AppContext(org.apache.openejb.AppContext) StandardContext(org.apache.catalina.core.StandardContext) NameNotFoundException(javax.naming.NameNotFoundException) SystemComponentReference(org.apache.openejb.core.ivm.naming.SystemComponentReference) Reference(javax.naming.Reference) AtomicReference(java.util.concurrent.atomic.AtomicReference) AppContext(org.apache.openejb.AppContext) PersistenceUnitInfo(org.apache.openejb.assembler.classic.PersistenceUnitInfo) LifecycleException(org.apache.catalina.LifecycleException) NameNotFoundException(javax.naming.NameNotFoundException) IOException(java.io.IOException) NamingException(javax.naming.NamingException) OpenEJBException(org.apache.openejb.OpenEJBException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) InitialContext(javax.naming.InitialContext) ReloadableEntityManagerFactory(org.apache.openejb.assembler.classic.ReloadableEntityManagerFactory)

Aggregations

ContainerSystem (org.apache.openejb.spi.ContainerSystem)64 Assembler (org.apache.openejb.assembler.classic.Assembler)31 BeanContext (org.apache.openejb.BeanContext)22 HashMap (java.util.HashMap)20 Map (java.util.Map)19 File (java.io.File)17 ConfigurationFactory (org.apache.openejb.config.ConfigurationFactory)13 Context (javax.naming.Context)12 EjbJar (org.apache.openejb.jee.EjbJar)11 StatelessBean (org.apache.openejb.jee.StatelessBean)11 AppContext (org.apache.openejb.AppContext)10 AppInfo (org.apache.openejb.assembler.classic.AppInfo)10 Properties (java.util.Properties)9 EjbModule (org.apache.openejb.config.EjbModule)9 OpenejbJar (org.apache.openejb.jee.oejb3.OpenejbJar)9 ArrayList (java.util.ArrayList)8 NamingException (javax.naming.NamingException)8 WebContext (org.apache.openejb.core.WebContext)8 InitialContext (javax.naming.InitialContext)7 NameNotFoundException (javax.naming.NameNotFoundException)6