Package org.apache.openejb

Examples of org.apache.openejb.AppContext


            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);
            appContext.getProperties().putAll(appInfo.properties);
            appContext.getInjections().addAll(injections);
            appContext.getBindings().putAll(globalBindings);
            appContext.getBindings().putAll(appBindings);

            containerSystem.addAppContext(appContext);

            appContext.set(AsynchronousPool.class, AsynchronousPool.create(appContext));

            final Context containerSystemContext = containerSystem.getJNDIContext();

            final Map<String, LazyValidatorFactory> lazyValidatorFactories = new HashMap<String, LazyValidatorFactory>();
            final Map<String, LazyValidator> lazyValidators = new HashMap<String, LazyValidator>();
            final boolean isGeronimo = SystemInstance.get().hasProperty("openejb.geronimo");
            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<String, ValidatorFactory>();

                for (final CommonInfoObject info : vfs) {
                    ValidatorFactory 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;
                    }
                    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);

                        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<String, String>();
            final PersistenceBuilder persistenceBuilder = new PersistenceBuilder(persistenceClassLoaderHandler);
            for (final PersistenceUnitInfo info : appInfo.persistenceUnits) {
                final ReloadableEntityManagerFactory factory;
                try {
                    factory = persistenceBuilder.createEntityManagerFactory(info, classLoader);
                    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 peristence 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(connector.resourceAdapter);
                    }
                    for (final ResourceInfo outbound : connector.outbound) {
                        createResource(outbound);
                        outbound.properties.setProperty("openejb.connector", "true"); // set it after as a marker but not as an attribute (no getOpenejb().setConnector(...))
                    }
                    for (final MdbContainerInfo inbound : connector.inbound) {
                        createContainer(inbound);
                    }
                    for (final ResourceInfo adminObject : connector.adminObject) {
                        createResource(adminObject);
                    }
                } finally {
                    Thread.currentThread().setContextClassLoader(oldClassLoader);
                }
            }

            final List<BeanContext> allDeployments = initEjbs(classLoader, appInfo, appContext, injections, new ArrayList<BeanContext>(), null);

            if ("true".equalsIgnoreCase(SystemInstance.get()
                .getProperty(PROPAGATE_APPLICATION_EXCEPTIONS,
                    appInfo.properties.getProperty(PROPAGATE_APPLICATION_EXCEPTIONS, "false")))) {
                propagateApplicationExceptions(appInfo, classLoader, allDeployments);
            }

            if ("true".equalsIgnoreCase(appInfo.properties.getProperty("openejb.cdi.activated", "true"))) {
                new CdiBuilder().build(appInfo, appContext, allDeployments);
                ensureWebBeansContext(appContext);
                appJndiContext.bind("app/BeanManager", appContext.getBeanManager());
                appContext.getBindings().put("app/BeanManager", appContext.getBeanManager());
            }

            // 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);
                // if there is at least a remote client classes
                // or if there is no local client classes
                // 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());

            // 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");
                }
            }

            deployedApplications.put(appInfo.path, appInfo);
            resumePersistentSchedulers(appContext);
View Full Code Here


        try {
            deployedApplications.remove(appInfo.path);
            logger.info("destroyApplication.start", appInfo.path);

            final Context globalContext = containerSystem.getJNDIContext();
            final AppContext appContext = containerSystem.getAppContext(appInfo.appId);
            final ClassLoader classLoader = appContext.getClassLoader();

            SystemInstance.get().fireEvent(new AssemblerBeforeApplicationDestroyed(appInfo, appContext));

            if (null == appContext) {
                logger.warning("Application id '" + appInfo.appId + "' not found in: " + Arrays.toString(containerSystem.getAppContextKeys()));
                return;
            } else {
                final WebBeansContext webBeansContext = appContext.getWebBeansContext();
                if (webBeansContext != null) {
                    final ClassLoader old = Thread.currentThread().getContextClassLoader();
                    Thread.currentThread().setContextClassLoader(classLoader);
                    try {
                        webBeansContext.getService(ContainerLifecycle.class).stopApplication(null);
                    } finally {
                        Thread.currentThread().setContextClassLoader(old);
                    }
                }
                final Map<String, Object> cb = appContext.getBindings();
                for (final Entry<String, Object> value : cb.entrySet()) {
                    String path = value.getKey();
                    if (path.startsWith("global")) {
                        path = "java:" + path;
                    }
                    if (!path.startsWith("java:global")) {
                        continue;
                    }

                    unbind(globalContext, path);
                    unbind(globalContext, "openejb/global/" + path.substring("java:".length()));
                    unbind(globalContext, path.substring("java:global".length()));
                }
                if (appInfo.appId != null && !appInfo.appId.isEmpty() && !"openejb".equals(appInfo.appId)) {
                    unbind(globalContext, "global/" + appInfo.appId);
                    unbind(globalContext, appInfo.appId);
                }
            }

            final EjbResolver globalResolver = new EjbResolver(null, EjbResolver.Scope.GLOBAL);
            for (final AppInfo info : deployedApplications.values()) {
                globalResolver.addAll(info.ejbJars);
            }
            SystemInstance.get().setComponent(EjbResolver.class, globalResolver);

            final UndeployException undeployException = new UndeployException(messages.format("destroyApplication.failed", appInfo.path));

            final WebAppBuilder webAppBuilder = SystemInstance.get().getComponent(WebAppBuilder.class);
            if (webAppBuilder != null && !appInfo.webAppAlone) {
                try {
                    webAppBuilder.undeployWebApps(appInfo);
                } catch (final Exception e) {
                    undeployException.getCauses().add(new Exception("App: " + appInfo.path + ": " + e.getMessage(), e));
                }
            }

            // get all of the ejb deployments
            List<BeanContext> deployments = new ArrayList<BeanContext>();
            for (final EjbJarInfo ejbJarInfo : appInfo.ejbJars) {
                for (final EnterpriseBeanInfo beanInfo : ejbJarInfo.enterpriseBeans) {
                    final String deploymentId = beanInfo.ejbDeploymentId;
                    final BeanContext beanContext = containerSystem.getBeanContext(deploymentId);
                    if (beanContext == null) {
                        undeployException.getCauses().add(new Exception("deployment not found: " + deploymentId));
                    } else {
                        deployments.add(beanContext);
                    }
                }
            }

            // Just as with startup we need to get things in an
            // order that respects the singleton @DependsOn information
            // Theoreticlly if a Singleton depends on something in its
            // @PostConstruct, it can depend on it in its @PreDestroy.
            // Therefore we want to make sure that if A dependsOn B,
            // that we destroy A first then B so that B will still be
            // usable in the @PreDestroy method of A.

            // Sort them into the original starting order
            deployments = sort(deployments);
            // reverse that to get the stopping order
            Collections.reverse(deployments);

            // stop
            for (final BeanContext deployment : deployments) {
                final String deploymentID = String.valueOf(deployment.getDeploymentID());
                try {
                    final Container container = deployment.getContainer();
                    container.stop(deployment);
                } catch (final Throwable t) {
                    undeployException.getCauses().add(new Exception("bean: " + deploymentID + ": " + t.getMessage(), t));
                }
            }

            // undeploy
            for (final BeanContext bean : deployments) {
                final String deploymentID = String.valueOf(bean.getDeploymentID());
                try {
                    final Container container = bean.getContainer();
                    container.undeploy(bean);
                    bean.setContainer(null);
                } catch (final Throwable t) {
                    undeployException.getCauses().add(new Exception("bean: " + deploymentID + ": " + t.getMessage(), t));
                } finally {
                    bean.setDestroyed(true);
                }
            }

            if (webAppBuilder != null && appInfo.webAppAlone) { // now that EJB are stopped we can undeploy webapps
                try {
                    webAppBuilder.undeployWebApps(appInfo);
                } catch (final Exception e) {
                    undeployException.getCauses().add(new Exception("App: " + appInfo.path + ": " + e.getMessage(), e));
                }
            }

            // get the client ids
            final List<String> clientIds = new ArrayList<String>();
            for (final ClientInfo clientInfo : appInfo.clients) {
                clientIds.add(clientInfo.moduleId);
                for (final String className : clientInfo.localClients) {
                    clientIds.add(className);
                }
                for (final String className : clientInfo.remoteClients) {
                    clientIds.add(className);
                }
            }

            for (final WebContext webContext : appContext.getWebContexts()) {
                containerSystem.removeWebContext(webContext);
            }
            TldScanner.forceCompleteClean(classLoader);

            // Clear out naming for all components first
            for (final BeanContext deployment : deployments) {
                final String deploymentID = String.valueOf(deployment.getDeploymentID());
                try {
                    containerSystem.removeBeanContext(deployment);
                } catch (final Throwable t) {
                    undeployException.getCauses().add(new Exception(deploymentID, t));
                }

                final JndiBuilder.Bindings bindings = deployment.get(JndiBuilder.Bindings.class);
                if (bindings != null) {
                    for (final String name : bindings.getBindings()) {
                        try {
                            globalContext.unbind(name);
                        } catch (final Throwable t) {
                            undeployException.getCauses().add(new Exception("bean: " + deploymentID + ": " + t.getMessage(), t));
                        }
                    }
                }
            }

            // stop this executor only now since @PreDestroy can trigger some stop events
            final AsynchronousPool pool = appContext.get(AsynchronousPool.class);
            if (pool != null) {
                pool.stop();
            }

            for (final CommonInfoObject jar : listCommonInfoObjectsForAppInfo(appInfo)) {
                try {
                    globalContext.unbind(VALIDATOR_FACTORY_NAMING_CONTEXT + jar.uniqueId);
                    globalContext.unbind(VALIDATOR_NAMING_CONTEXT + jar.uniqueId);
                } catch (final NamingException e) {
                    if (EjbJarInfo.class.isInstance(jar)) {
                        undeployException.getCauses().add(new Exception("validator: " + jar.uniqueId + ": " + e.getMessage(), e));
                    } // else an error but not that important
                }
            }
            try {
                if (globalContext instanceof IvmContext) {
                    final IvmContext ivmContext = (IvmContext) globalContext;
                    ivmContext.prune("openejb/Deployment");
                    ivmContext.prune("openejb/local");
                    ivmContext.prune("openejb/remote");
                    ivmContext.prune("openejb/global");
                }
            } catch (final NamingException e) {
                undeployException.getCauses().add(new Exception("Unable to prune openejb/Deployments and openejb/local namespaces, this could cause future deployments to fail.",
                    e));
            }

            deployments.clear();

            for (final String clientId : clientIds) {
                try {
                    globalContext.unbind("/openejb/client/" + clientId);
                } catch (final Throwable t) {
                    undeployException.getCauses().add(new Exception("client: " + clientId + ": " + t.getMessage(), t));
                }
            }

            // mbeans
            final MBeanServer server = LocalMBeanServer.get();
            for (final Object objectName : appInfo.jmx.values()) {
                try {
                    final ObjectName on = new ObjectName((String) objectName);
                    if (server.isRegistered(on)) {
                        server.unregisterMBean(on);
                    }
                    final CreationalContext cc = creationalContextForAppMbeans.remove(on);
                    if (cc != null) {
                        cc.release();
                    }
                } catch (final InstanceNotFoundException e) {
                    logger.warning("can't unregister " + objectName + " because the mbean was not found", e);
                } catch (final MBeanRegistrationException e) {
                    logger.warning("can't unregister " + objectName, e);
                } catch (final MalformedObjectNameException mone) {
                    logger.warning("can't unregister because the ObjectName is malformed: " + objectName, mone);
                }
            }

            // destroy PUs before resources since the JPA provider can use datasources
            for (final PersistenceUnitInfo unitInfo : appInfo.persistenceUnits) {
                try {
                    final Object object = globalContext.lookup(PERSISTENCE_UNIT_NAMING_CONTEXT + unitInfo.id);
                    globalContext.unbind(PERSISTENCE_UNIT_NAMING_CONTEXT + unitInfo.id);

                    // close EMF so all resources are released
                    final ReloadableEntityManagerFactory remf = (ReloadableEntityManagerFactory) object;
                    remf.close();
                    persistenceClassLoaderHandler.destroy(unitInfo.id);
                    remf.unregister();
                } catch (final Throwable t) {
                    undeployException.getCauses().add(new Exception("persistence-unit: " + unitInfo.id + ": " + t.getMessage(), t));
                }
            }

            for (final String id : appInfo.resourceAliases) {
                final String name = OPENEJB_RESOURCE_JNDI_PREFIX + id;
                ContextualJndiReference.followReference.set(false);
                try {
                    final Object object;
                    try {
                        object = globalContext.lookup(name);
                    } finally {
                        ContextualJndiReference.followReference.remove();
                    }
                    if (object instanceof ContextualJndiReference) {
                        final ContextualJndiReference contextualJndiReference = ContextualJndiReference.class.cast(object);
                        contextualJndiReference.removePrefix(appContext.getId());
                        if (contextualJndiReference.hasNoMorePrefix()) {
                            globalContext.unbind(name);
                        } // else not the last deployed application to use this resource so keep it
                    } else {
                        globalContext.unbind(name);
View Full Code Here

        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();

        if (contextInfo == null) {
            final AppModule appModule = loadApplication(standardContext);

            if (standardContext.getNamingResources() instanceof OpenEJBNamingResource) {
                final Collection<String> importedNames = new ArrayList<String>(); // we can get the same resource twice as in tomcat

                // add them to the app as resource
                final OpenEJBNamingResource nr = (OpenEJBNamingResource) standardContext.getNamingResources();
                for (final ResourceBase resource : nr.getTomcatResources()) {
                    final String name = resource.getName();
                    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 (DataSource.class.getName().equals(resource.getType())) { // 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);
                    contextInfo.standardContext = standardContext; // ensure to do it before an exception can be thrown

                    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 LazyStopWebappClassLoader) {
                            final LazyStopWebappClassLoader lazyStopWebappClassLoader = (LazyStopWebappClassLoader) loader;
                            for (final URL url : appModule.getWebModules().iterator().next().getAddedUrls()) {
                                lazyStopWebappClassLoader.addURL(url);
                            }
                        }
                    }

                    OpenEJBContextConfig openEJBContextConfig = null;
                    for (final LifecycleListener listener : standardContext.findLifecycleListeners()) {
                        if (OpenEJBContextConfig.class.isInstance(listener)) {
                            openEJBContextConfig = OpenEJBContextConfig.class.cast(listener);
                            break;
                        }
                    }
                    if (openEJBContextConfig != null) {
                        for (final EjbModule ejbModule : appModule.getEjbModules()) {
                            if (ejbModule.getFile() != null && warPath(standardContext).equals(rootPath(ejbModule.getFile()))) {
                                openEJBContextConfig.finder(ejbModule.getFinder(), ejbModule.getClassLoader());
                                break;
                            }
                        }
                    }


                    appContext = a.createApplication(contextInfo.appInfo, 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;
        }

        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)) || id.equals(getId(w.host, w.moduleId))) {
                    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.getName();

            // 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.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);

                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);
                    try {
                        new CdiBuilder().build(contextInfo.appInfo, appContext, beanContexts, webContext);
                    } finally {
                        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).buildBindings(JndiEncBuilder.JndiScope.comp));

                final JavaeeInstanceManager instanceManager = new JavaeeInstanceManager(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);
            }

            final JspFactory factory = JspFactory.getDefaultFactory();
            if (factory != null) {
                final JspApplicationContext applicationCtx = factory.getJspApplicationContext(standardContext.getServletContext());
                final WebBeansContext context = appContext.getWebBeansContext();
                if (context != null && context.getBeanManagerImpl().isInUse()) {
                    // Registering ELResolver with JSP container
                    final ELAdaptor elAdaptor = context.getService(ELAdaptor.class);
                    final ELResolver resolver = elAdaptor.getOwbELResolver();
                    applicationCtx.addELResolver(resolver);
View Full Code Here

            }
        }
    }

    private WebBeansContext getWebBeansContext(final ContextInfo contextInfo) {
        final AppContext appContext = getContainerSystem().getAppContext(contextInfo.appInfo.appId);

        if (appContext == null) {
            return null;
        }

        WebBeansContext webBeansContext = appContext.getWebBeansContext();

        if (webBeansContext == null) {
            return null;
        }

        for (final WebContext web : appContext.getWebContexts()) {
            final String stdName = removeFirstSlashAndWar(contextInfo.standardContext.getName());
            if (stdName == null) {
                continue;
            }

            final String name = removeFirstSlashAndWar(web.getContextRoot());
            if (stdName.equals(name)) {
                webBeansContext = web.getWebbeansContext();
                if (Contexts.getHostname(contextInfo.standardContext).equals(web.getHost())) {
                    break;
                } // else loop hoping to find a better matching
            }
        }

        if (webBeansContext == null) {
            webBeansContext = appContext.getWebBeansContext();
        }

        return webBeansContext;
    }
View Full Code Here

    private DeploymentInfo quickDeploy(final Archive<?> archive, final TestClass testClass) throws DeploymentException {
        try {
            final AppModule module = OpenEJBArchiveProcessor.createModule(archive, testClass);
            final AppInfo appInfo = configurationFactory.configureApplication(module);
            final AppContext appCtx = assembler.createApplication(appInfo, module.getClassLoader());

            final ServletContext appServletContext = new MockServletContext();
            final HttpSession appSession = new MockHttpSession();

            startContexts(appCtx.getWebBeansContext().getContextsService(), appServletContext, appSession);

            return new DeploymentInfo(appServletContext, appSession, appInfo, appCtx);
        } catch (final Exception e) {
            throw new DeploymentException("can't deploy " + archive.getName(), e);
        }
View Full Code Here


        {
            final EjbJar ejbJar = new EjbJar();
            ejbJar.addEnterpriseBean(new SingletonBean(MyBean.class));
            final AppContext application = assembler.createApplication(factory.configureApplication(new EjbModule(ejbJar)));

            final MyBean myBean = (MyBean) application.getBeanContexts().get(0).getBusinessLocalBeanHome().create();

            final Color color = myBean.getColor();
            assertNotNull(color);
            assertEquals(255, color.getRed());
            assertEquals(200, color.getGreen());
View Full Code Here

    }

    @Test
    public void testRollback() throws Exception {
        SystemInstance.init(new Properties());
        final BeanContext cdi = new BeanContext("foo", null, new ModuleContext("foo", null, "bar", new AppContext("foo", SystemInstance.get(), null, null, null, false), null, null), Object.class, null, new HashMap<String, String>());
        cdi.addApplicationException(AE1.class, true, true);
        cdi.addApplicationException(AE3.class, true, false);
        cdi.addApplicationException(AE6.class, false, true);

        assertEquals(ExceptionType.APPLICATION_ROLLBACK, cdi.getExceptionType(new AE1()));
View Full Code Here

        assembler.createSecurityService(factory.configureService(SecurityServiceInfo.class));
        assembler.createTransactionManager(factory.configureService(TransactionServiceInfo.class));

        final EjbJar ejbJar = new EjbJar();
        ejbJar.addEnterpriseBean(new SingletonBean(MyBean.class));
        final AppContext application = assembler.createApplication(factory.configureApplication(new EjbModule(ejbJar)));

        final MyBean myBean = (MyBean) application.getBeanContexts().get(0).getBusinessLocalBeanHome().create();

        final Color color = myBean.getColor();
        assertNotNull(color);
        assertEquals(255, color.getRed());
        assertEquals(200, color.getGreen());
View Full Code Here

        assembler.createTransactionManager(config.configureService(TransactionServiceInfo.class));
        assembler.createSecurityService(config.configureService(SecurityServiceInfo.class));


        final AppContext circleApp = createApp("circle", config, assembler);
        final AppContext squareApp = createApp("square", config, assembler);

        {
            final BeanContext bean = squareApp.getBeanContexts().get(0);

            final Context context = bean.getJndiContext();

            assertTrue(context.lookup("global/square") instanceof Context);
            assertTrue(context.lookup("global/square/Bean") instanceof Bean);
View Full Code Here

            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);
            appContext.getProperties().putAll(appInfo.properties);
            appContext.getInjections().addAll(injections);
            appContext.getBindings().putAll(globalBindings);
            appContext.getBindings().putAll(appBindings);

            containerSystem.addAppContext(appContext);

            appContext.set(AsynchronousPool.class, AsynchronousPool.create(appContext));

            final Context containerSystemContext = containerSystem.getJNDIContext();

            if (!SystemInstance.get().hasProperty("openejb.geronimo")) {
                // 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<String, ValidatorFactory>();
                for (final CommonInfoObject info : vfs) {
                    ValidatorFactory factory = null;
                    try {
                        factory = ValidatorBuilder.buildFactory(classLoader, info.validationInfo);
                    } catch (final ValidationException ve) {
                        logger.warning("can't build the validation factory for module " + info.uniqueId, ve);
                    }
                    if (factory != null) {
                        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);

                        Validator validator;
                        try {
                            validator = factory.usingContext().getValidator();
                        } catch (final Exception e) {
                            validator = (Validator) Proxy.newProxyInstance(appContext.getClassLoader(), new Class<?>[]{Validator.class}, new LazyValidator(factory));
                        }

                        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);
                    }
                }
            }

            // 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<String, String>();
            final PersistenceBuilder persistenceBuilder = new PersistenceBuilder(persistenceClassLoaderHandler);
            for (final PersistenceUnitInfo info : appInfo.persistenceUnits) {
                final ReloadableEntityManagerFactory factory;
                try {
                    factory = persistenceBuilder.createEntityManagerFactory(info, classLoader);
                    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 peristence 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(connector.resourceAdapter);
                    }
                    for (final ResourceInfo outbound : connector.outbound) {
                        createResource(outbound);
                        outbound.properties.setProperty("openejb.connector", "true"); // set it after as a marker but not as an attribute (no getOpenejb().setConnector(...))
                    }
                    for (final MdbContainerInfo inbound : connector.inbound) {
                        createContainer(inbound);
                    }
                    for (final ResourceInfo adminObject : connector.adminObject) {
                        createResource(adminObject);
                    }
                } finally {
                    Thread.currentThread().setContextClassLoader(oldClassLoader);
                }
            }

            final List<BeanContext> allDeployments = initEjbs(classLoader, appInfo, appContext, injections, new ArrayList<BeanContext>(), null);

            if ("true".equalsIgnoreCase(SystemInstance.get()
                .getProperty(PROPAGATE_APPLICATION_EXCEPTIONS,
                    appInfo.properties.getProperty(PROPAGATE_APPLICATION_EXCEPTIONS, "false")))) {
                propagateApplicationExceptions(appInfo, classLoader, allDeployments);
            }

            if ("true".equalsIgnoreCase(appInfo.properties.getProperty("openejb.cdi.activated", "true"))) {
                new CdiBuilder().build(appInfo, appContext, allDeployments);
                ensureWebBeansContext(appContext);
                appJndiContext.bind("app/BeanManager", appContext.getBeanManager());
                appContext.getBindings().put("app/BeanManager", appContext.getBeanManager());
            }

            // before starting everything, give the user the opportunity to hack on the AppContext/BeanContext
            final SystemInstance systemInstance = SystemInstance.get();
            systemInstance.fireEvent(new BeanContextsInitializedEvent(appInfo, appContext, allDeployments));

            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);
                // if there is at least a remote client classes
                // or if there is no local client classes
                // 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 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());

            // 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");
                }
            }

            deployedApplications.put(appInfo.path, appInfo);
            resumePersistentSchedulers(appContext);
View Full Code Here

TOP

Related Classes of org.apache.openejb.AppContext

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.