Search in sources :

Example 11 with WebAppInfo

use of org.apache.openejb.assembler.classic.WebAppInfo in project tomee by apache.

the class TomcatWebAppBuilder method startInternal.

/**
 * {@inheritDoc}
 */
// @Override
private void startInternal(final StandardContext standardContext) {
    if (isIgnored(standardContext)) {
        return;
    }
    if (shouldNotDeploy(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)

Example 12 with WebAppInfo

use of org.apache.openejb.assembler.classic.WebAppInfo in project tomee by apache.

the class Container method deploy.

public AppContext deploy(final String name, final File file, final boolean overrideName) throws OpenEJBException, IOException, NamingException {
    final AppContext context;
    final AppInfo appInfo;
    if (WebAppDeployer.Helper.isWebApp(file)) {
        String contextRoot = file.getName();
        if (overrideName) {
            contextRoot = name;
        }
        appInfo = SystemInstance.get().getComponent(WebAppDeployer.class).deploy(null, contextRoot, file);
        if (appInfo != null) {
            context = SystemInstance.get().getComponent(ContainerSystem.class).getAppContext(appInfo.appId);
        } else {
            context = null;
        }
    } else {
        appInfo = configurationFactory.configureApplication(file);
        // ensure to activate CDI for classpath deployment, we can desire to move it but it breaks less apps this way
        for (final EjbJarInfo jar : appInfo.ejbJars) {
            if (jar.enterpriseBeans.size() == 1) {
                final EnterpriseBeanInfo next = jar.enterpriseBeans.iterator().next();
                if (ManagedBeanInfo.class.isInstance(next) && ManagedBeanInfo.class.cast(next).hidden) {
                    continue;
                }
            }
            if (jar.beans == null) {
                if (!jar.enterpriseBeans.isEmpty()) {
                    jar.beans = new BeansInfo();
                    jar.beans.version = "1.1";
                    jar.beans.discoveryMode = "annotated";
                    final BeansInfo.BDAInfo info = new BeansInfo.BDAInfo();
                    info.discoveryMode = "annotated";
                    info.uri = jar.moduleUri;
                    jar.beans.noDescriptorBdas.add(info);
                    for (final EnterpriseBeanInfo bean : jar.enterpriseBeans) {
                        if (bean.ejbClass == null) {
                            continue;
                        }
                        info.managedClasses.add(bean.ejbClass);
                    }
                }
            }
        }
        if (overrideName) {
            appInfo.appId = name;
            for (final EjbJarInfo ejbJar : appInfo.ejbJars) {
                if (file.getName().equals(ejbJar.moduleName)) {
                    ejbJar.moduleName = name;
                    ejbJar.moduleId = name;
                }
                for (final EnterpriseBeanInfo ejb : ejbJar.enterpriseBeans) {
                    if (BeanContext.Comp.openejbCompName(file.getName()).equals(ejb.ejbName)) {
                        ejb.ejbName = BeanContext.Comp.openejbCompName(name);
                    }
                }
            }
            for (final WebAppInfo webApp : appInfo.webApps) {
                if (sameApplication(file, webApp)) {
                    webApp.moduleId = name;
                    webApp.contextRoot = lastPart(name, webApp.contextRoot);
                    if ("ROOT".equals(webApp.contextRoot)) {
                        webApp.contextRoot = "";
                    }
                }
            }
        }
        context = assembler.createApplication(appInfo);
    }
    moduleIds.put(name, null != appInfo ? appInfo.path : null);
    infos.put(name, appInfo);
    appContexts.put(name, context);
    return context;
}
Also used : EnterpriseBeanInfo(org.apache.openejb.assembler.classic.EnterpriseBeanInfo) WebAppInfo(org.apache.openejb.assembler.classic.WebAppInfo) BeansInfo(org.apache.openejb.assembler.classic.BeansInfo) AppContext(org.apache.openejb.AppContext) ManagedBeanInfo(org.apache.openejb.assembler.classic.ManagedBeanInfo) EjbJarInfo(org.apache.openejb.assembler.classic.EjbJarInfo) AppInfo(org.apache.openejb.assembler.classic.AppInfo) WebAppInfo(org.apache.openejb.assembler.classic.WebAppInfo)

Example 13 with WebAppInfo

use of org.apache.openejb.assembler.classic.WebAppInfo in project tomee by apache.

the class TomcatWebAppBuilder method afterStart.

/**
 * {@inheritDoc}
 */
@Override
public void afterStart(final StandardContext standardContext) {
    if (isIgnored(standardContext)) {
        return;
    }
    if (shouldNotDeploy(standardContext)) {
        return;
    }
    final Realm realm = standardContext.getRealm();
    final ClassLoader classLoader = standardContext.getLoader().getClassLoader();
    final Thread thread = Thread.currentThread();
    final ClassLoader originalLoader = thread.getContextClassLoader();
    if (realm != null && !(realm instanceof TomEERealm) && (standardContext.getParent() == null || (!realm.equals(standardContext.getParent().getRealm())))) {
        thread.setContextClassLoader(classLoader);
        try {
            standardContext.setRealm(tomeeRealm(realm));
        } finally {
            thread.setContextClassLoader(originalLoader);
        }
    }
    // if appInfo is null this is a failed deployment... just ignore
    final ContextInfo contextInfo = getContextInfo(standardContext);
    // shouldnt be there after startup (actually we shouldnt need it from info tree but our scanning does)
    contextInfo.module = null;
    if (contextInfo != null && contextInfo.appInfo == null) {
        return;
    } else if (contextInfo == null) {
        // openejb webapp loaded from the LoaderServlet
        return;
    }
    final String id = getId(standardContext);
    WebAppInfo currentWebAppInfo = null;
    for (final WebAppInfo webAppInfo : contextInfo.appInfo.webApps) {
        final String wId = getId(webAppInfo.host, webAppInfo.contextRoot, contextInfo.version);
        if (id.equals(wId)) {
            currentWebAppInfo = webAppInfo;
            break;
        }
    }
    // bind extra stuff at the java:comp level which can only be
    // bound after the context is created
    thread.setContextClassLoader(classLoader);
    final NamingContextListener ncl = standardContext.getNamingContextListener();
    final String listenerName = ncl.getName();
    ContextAccessController.setWritable(listenerName, standardContext.getNamingToken());
    try {
        final Context openejbContext = (Context) getContainerSystem().getJNDIContext().lookup("openejb");
        final Context root = (Context) ContextBindings.getClassLoader().lookup("");
        // usually fails
        final Context comp = (Context) ContextBindings.getClassLoader().lookup("comp");
        // Context root = ncl.getNamingContext();
        // Context comp = (Context) root.lookup("comp");
        safeBind(root, "openejb", openejbContext);
        // add context to WebDeploymentInfo
        if (currentWebAppInfo != null) {
            final WebContext webContext = getContainerSystem().getWebContext(currentWebAppInfo.moduleId);
            if (webContext != null) {
                webContext.setJndiEnc(root);
            }
            try {
                // Bean Validation
                standardContext.getServletContext().setAttribute("javax.faces.validator.beanValidator.ValidatorFactory", openejbContext.lookup(Assembler.VALIDATOR_FACTORY_NAMING_CONTEXT.replaceFirst("openejb", "") + currentWebAppInfo.uniqueId));
            } catch (final NamingException ne) {
                logger.warning("no validator factory found for webapp " + currentWebAppInfo.moduleId);
            }
        }
        try {
            final Class<?> orb = TomcatWebAppBuilder.class.getClassLoader().loadClass("org.omg.CORBA.ORB");
            if (SystemInstance.get().getComponent(orb) != null) {
                safeBind(comp, "ORB", new SystemComponentReference(orb));
            }
        } catch (final NoClassDefFoundError | ClassNotFoundException cnfe) {
        // no-op
        }
        if (SystemInstance.get().getComponent(HandleDelegate.class) != null) {
            safeBind(comp, "HandleDelegate", new SystemComponentReference(HandleDelegate.class));
        }
    } catch (final NamingException e) {
    // no-op
    } finally {
        // see also the start method getContainerSystem().addWebDeployment(webContext);
        for (final WebAppInfo webApp : contextInfo.appInfo.webApps) {
            SystemInstance.get().fireEvent(new AfterApplicationCreated(contextInfo.appInfo, webApp));
        }
        thread.setContextClassLoader(originalLoader);
        ContextAccessController.setReadOnly(listenerName);
    }
    thread.setContextClassLoader(classLoader);
    try {
        // owb integration filters
        final WebBeansContext webBeansContext = getWebBeansContext(contextInfo);
        if (webBeansContext != null) {
            // it is important to have a begin and a end listener
            // to be sure to create contexts before other listeners
            // and destroy contexts after other listeners
            final BeginWebBeansListener beginWebBeansListener = new BeginWebBeansListener(webBeansContext);
            final EndWebBeansListener endWebBeansListener = new EndWebBeansListener(webBeansContext);
            {
                final Object[] appEventListeners = standardContext.getApplicationEventListeners();
                final Object[] newEventListeners = new Object[appEventListeners.length + 2];
                newEventListeners[0] = beginWebBeansListener;
                System.arraycopy(appEventListeners, 0, newEventListeners, 1, appEventListeners.length);
                newEventListeners[newEventListeners.length - 1] = endWebBeansListener;
                standardContext.setApplicationEventListeners(newEventListeners);
            }
            {
                final Object[] lifecycleListeners = standardContext.getApplicationLifecycleListeners();
                final Object[] newLifecycleListeners = new Object[lifecycleListeners.length + 2];
                newLifecycleListeners[0] = beginWebBeansListener;
                System.arraycopy(lifecycleListeners, 0, newLifecycleListeners, 1, lifecycleListeners.length);
                newLifecycleListeners[newLifecycleListeners.length - 1] = endWebBeansListener;
                standardContext.setApplicationLifecycleListeners(newLifecycleListeners);
            }
            // also add the ThreadBindingListener to clean up async thread executions
            {
                WebBeansThreadBindingListener webBeansThreadBindingListener = new WebBeansThreadBindingListener(webBeansContext, standardContext.getThreadBindingListener());
                standardContext.setThreadBindingListener(webBeansThreadBindingListener);
            }
            final ContextsService contextsService = webBeansContext.getContextsService();
            if (CdiAppContextsService.class.isInstance(contextsService)) {
                // here ServletContext is usable
                CdiAppContextsService.class.cast(contextsService).applicationStarted(standardContext.getServletContext());
            }
        } else {
            // just add the end listener to be able to stack tasks to execute at the request end
            final EndWebBeansListener endWebBeansListener = new EndWebBeansListener(webBeansContext);
            {
                final Object[] appEventListeners = standardContext.getApplicationEventListeners();
                final Object[] newEventListeners = new Object[appEventListeners.length + 1];
                System.arraycopy(appEventListeners, 0, newEventListeners, 0, appEventListeners.length);
                newEventListeners[newEventListeners.length - 1] = endWebBeansListener;
                standardContext.setApplicationEventListeners(newEventListeners);
            }
            {
                final Object[] lifecycleListeners = standardContext.getApplicationLifecycleListeners();
                final Object[] newLifecycleListeners = new Object[lifecycleListeners.length + 1];
                System.arraycopy(lifecycleListeners, 0, newLifecycleListeners, 0, lifecycleListeners.length);
                newLifecycleListeners[newLifecycleListeners.length - 1] = endWebBeansListener;
                standardContext.setApplicationLifecycleListeners(newLifecycleListeners);
            }
        }
    } finally {
        thread.setContextClassLoader(originalLoader);
    }
    LinkageErrorProtection.preload(standardContext);
    final Pipeline pipeline = standardContext.getPipeline();
    pipeline.addValve(new OpenEJBValve());
    final String[] valves = SystemInstance.get().getOptions().get("tomee.valves", "").split(" *, *");
    for (final String className : valves) {
        if ("".equals(className)) {
            continue;
        }
        try {
            final Class<?> clazz = classLoader.loadClass(className);
            if (Valve.class.isAssignableFrom(clazz)) {
                final Valve valve = (Valve) clazz.newInstance();
                pipeline.addValve(valve);
            }
        } catch (final Exception e) {
            logger.error("can't add the valve " + className, e);
        }
    }
    // add servlets to webappinfo
    if (currentWebAppInfo != null) {
        for (final String mapping : standardContext.findServletMappings()) {
            final ServletInfo info = new ServletInfo();
            info.servletName = standardContext.findServletMapping(mapping);
            info.mappings.add(mapping);
            final Container container = standardContext.findChild(info.servletName);
            if (container instanceof StandardWrapper) {
                info.servletClass = ((StandardWrapper) container).getServletClass();
            } else {
                info.servletClass = mapping;
            }
            currentWebAppInfo.servlets.add(info);
        }
    }
    addConfiguredDocBases(standardContext, contextInfo);
    ensureMyFacesDontLooseFacesContext(standardContext);
}
Also used : WebContext(org.apache.openejb.core.WebContext) CdiAppContextsService(org.apache.openejb.cdi.CdiAppContextsService) ServletInfo(org.apache.openejb.assembler.classic.ServletInfo) BeginWebBeansListener(org.apache.openejb.server.httpd.BeginWebBeansListener) WebAppInfo(org.apache.openejb.assembler.classic.WebAppInfo) Container(org.apache.catalina.Container) WebBeansContext(org.apache.webbeans.config.WebBeansContext) EndWebBeansListener(org.apache.openejb.server.httpd.EndWebBeansListener) NewEjbAvailableAfterApplicationCreated(org.apache.openejb.assembler.classic.event.NewEjbAvailableAfterApplicationCreated) AfterApplicationCreated(org.apache.tomee.catalina.event.AfterApplicationCreated) RouterValve(org.apache.tomee.catalina.routing.RouterValve) Valve(org.apache.catalina.Valve) NamingException(javax.naming.NamingException) NamingContextListener(org.apache.catalina.core.NamingContextListener) 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) CdiAppContextsService(org.apache.openejb.cdi.CdiAppContextsService) ContextsService(org.apache.webbeans.spi.ContextsService) WebBeansThreadBindingListener(org.apache.tomee.catalina.cdi.WebBeansThreadBindingListener) SystemComponentReference(org.apache.openejb.core.ivm.naming.SystemComponentReference) 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) Pipeline(org.apache.catalina.Pipeline) HandleDelegate(javax.ejb.spi.HandleDelegate) StandardWrapper(org.apache.catalina.core.StandardWrapper)

Example 14 with WebAppInfo

use of org.apache.openejb.assembler.classic.WebAppInfo in project tomee by apache.

the class TomcatWebAppBuilder method deployWebApps.

// 
// OpenEJB WebAppBuilder
// 
/**
 * {@inheritDoc}
 */
@Override
public void deployWebApps(final AppInfo appInfo, final ClassLoader classLoader) throws Exception {
    try {
        for (final WebAppInfo webApp : appInfo.webApps) {
            // look for context.xml
            final File war = new File(webApp.path);
            URL contextXmlUrl = null;
            if (war.isDirectory()) {
                final File cXml = new File(war, Constants.ApplicationContextXml).getAbsoluteFile();
                if (cXml.exists()) {
                    contextXmlUrl = cXml.toURI().toURL();
                    logger.info("using context file " + cXml.getAbsolutePath());
                }
            } else {
                // war
                try (final JarFile warAsJar = new JarFile(war)) {
                    final JarEntry entry = warAsJar.getJarEntry(Constants.ApplicationContextXml);
                    if (entry != null) {
                        contextXmlUrl = new URL("jar:" + war.getAbsoluteFile().toURI().toURL().toExternalForm() + "!/" + Constants.ApplicationContextXml);
                    }
                }
            }
            if (isAlreadyDeployed(appInfo, webApp)) {
                continue;
            }
            StandardContext standardContext;
            {
                final ClassLoader containerLoader = Helper.get();
                final Host host = hosts.getDefault();
                if (StandardHost.class.isInstance(host) && !StandardContext.class.getName().equals(StandardHost.class.cast(host).getContextClass())) {
                    try {
                        standardContext = StandardContext.class.cast(containerLoader.loadClass(StandardHost.class.cast(host).getContextClass()).newInstance());
                    } catch (final Throwable th) {
                        logger.warning("Can't use context class specified, using default StandardContext", th);
                        standardContext = new StandardContext();
                    }
                } else {
                    standardContext = new StandardContext();
                }
                // should be optional but in maven parent is app loader and not maven loader which is the real parent
                final ClassLoader currentParent = standardContext.getParentClassLoader();
                if (currentParent == null || isParent(currentParent, containerLoader)) {
                    standardContext.setParentClassLoader(containerLoader);
                }
            }
            standardContext.setUnpackWAR(!"false".equalsIgnoreCase(appInfo.properties.getProperty("tomcat.unpackWar")));
            if (contextXmlUrl != null) {
                standardContext.setConfigFile(contextXmlUrl);
            }
            if (standardContext.getPath() != null) {
                webApp.contextRoot = standardContext.getPath();
            }
            if (webApp.contextRoot.startsWith("/") || webApp.contextRoot.startsWith(File.separator)) {
                webApp.contextRoot = webApp.contextRoot.substring(1);
            }
            if (webApp.contextRoot.startsWith(File.separator)) {
                webApp.contextRoot = webApp.contextRoot.replaceFirst(File.separator, "");
            }
            // /!\ take care, StandardContext default host = "_" and not null or localhost
            final String hostname = Contexts.getHostname(standardContext);
            if (hostname != null && !"_".equals(hostname)) {
                webApp.host = hostname;
            }
            final ApplicationParameter appParam = new ApplicationParameter();
            appParam.setName(OPENEJB_WEBAPP_MODULE_ID);
            appParam.setValue(webApp.moduleId);
            standardContext.addApplicationParameter(appParam);
            if (!isAlreadyDeployed(appInfo, webApp)) {
                if (standardContext.getPath() == null) {
                    if (webApp.contextRoot != null && webApp.contextRoot.startsWith("/")) {
                        standardContext.setPath(webApp.contextRoot);
                    } else if (isRoot(webApp.contextRoot)) {
                        standardContext.setPath("");
                    } else {
                        standardContext.setPath("/" + webApp.contextRoot);
                    }
                }
                if (standardContext.getDocBase() == null) {
                    standardContext.setDocBase(webApp.path);
                }
                String docBase = standardContext.getDocBase();
                File docBaseFile = new File(docBase);
                if (docBase != null && docBaseFile.isFile() && docBase.endsWith(".war")) {
                    DeploymentLoader.unpack(docBaseFile);
                    if (standardContext.getPath().endsWith(".war")) {
                        standardContext.setPath(removeFirstSlashAndWar("/" + standardContext.getPath()));
                        standardContext.setName(standardContext.getPath());
                        webApp.contextRoot = standardContext.getPath();
                    }
                    standardContext.setDocBase(docBase.substring(0, docBase.length() - 4));
                }
                if (isRoot(standardContext.getName())) {
                    standardContext.setName("");
                    webApp.contextRoot = "";
                }
                if (isAlreadyDeployed(appInfo, webApp)) {
                    // possible because of the previous renaming
                    continue;
                }
                // but here we have all the classloading logic
                if (classLoader != null) {
                    standardContext.setParentClassLoader(classLoader);
                    standardContext.setDelegate(true);
                }
                String host = webApp.host;
                if (host == null) {
                    host = hosts.getDefaultHost();
                    logger.info("using default host: " + host);
                }
                if (classLoader != null) {
                    appInfo.autoDeploy = false;
                    deployWar(standardContext, host, appInfo);
                } else {
                    // force a normal deployment with lazy building of AppInfo
                    deployWar(standardContext, host, null);
                }
            }
        }
    } finally {
        // cleanup temp var passing
        for (final WebAppInfo webApp : appInfo.webApps) {
            appInfo.properties.remove(webApp);
        }
    }
}
Also used : WebAppInfo(org.apache.openejb.assembler.classic.WebAppInfo) ApplicationParameter(org.apache.tomcat.util.descriptor.web.ApplicationParameter) StandardHost(org.apache.catalina.core.StandardHost) StandardContext(org.apache.catalina.core.StandardContext) Host(org.apache.catalina.Host) StandardHost(org.apache.catalina.core.StandardHost) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) File(java.io.File) JarFile(java.util.jar.JarFile) URL(java.net.URL)

Example 15 with WebAppInfo

use of org.apache.openejb.assembler.classic.WebAppInfo in project tomee by apache.

the class TomcatWebAppBuilder method undeployWebApps.

/**
 * {@inheritDoc}
 */
@Override
public void undeployWebApps(final AppInfo appInfo) throws Exception {
    final String version = appVersion(appInfo);
    for (final WebAppInfo webApp : appInfo.webApps) {
        final ContextInfo contextInfo = getContextInfo(webApp.host, webApp.contextRoot, version);
        if (contextInfo != null) {
            final StandardContext standardContext = contextInfo.standardContext;
            if (!appInfo.webAppAlone || !appInfo.properties.containsKey("tomee.destroying")) {
                undeploy(standardContext, contextInfo);
                final File extracted = Contexts.warPath(standardContext);
                if (isExtracted(extracted)) {
                    deleteDir(extracted);
                }
                removeContextInfo(standardContext);
            }
        }
    }
}
Also used : WebAppInfo(org.apache.openejb.assembler.classic.WebAppInfo) StandardContext(org.apache.catalina.core.StandardContext) File(java.io.File) JarFile(java.util.jar.JarFile)

Aggregations

WebAppInfo (org.apache.openejb.assembler.classic.WebAppInfo)27 AppInfo (org.apache.openejb.assembler.classic.AppInfo)9 BeanContext (org.apache.openejb.BeanContext)8 MalformedURLException (java.net.MalformedURLException)7 HashMap (java.util.HashMap)7 EjbJarInfo (org.apache.openejb.assembler.classic.EjbJarInfo)7 ServletInfo (org.apache.openejb.assembler.classic.ServletInfo)7 NamingException (javax.naming.NamingException)6 EnterpriseBeanInfo (org.apache.openejb.assembler.classic.EnterpriseBeanInfo)6 File (java.io.File)5 ArrayList (java.util.ArrayList)5 NameNotFoundException (javax.naming.NameNotFoundException)5 OpenEJBRuntimeException (org.apache.openejb.OpenEJBRuntimeException)5 ClassListInfo (org.apache.openejb.assembler.classic.ClassListInfo)5 IOException (java.io.IOException)4 Map (java.util.Map)4 StandardContext (org.apache.catalina.core.StandardContext)4 AppContext (org.apache.openejb.AppContext)4 OpenEJBException (org.apache.openejb.OpenEJBException)4 URL (java.net.URL)3