Search in sources :

Example 11 with WebContext

use of org.apache.openejb.core.WebContext in project tomee by apache.

the class Assembler method destroyApplication.

public void destroyApplication(final AppInfo appInfo) throws UndeployException {
    final ReentrantLock l = lock;
    l.lock();
    try {
        deployedApplications.remove(appInfo.path);
        logger.info("destroyApplication.start", appInfo.path);
        final Context globalContext = containerSystem.getJNDIContext();
        final AppContext appContext = containerSystem.getAppContext(appInfo.appId);
        if (null == appContext) {
            logger.warning("Application id '" + appInfo.appId + "' not found in: " + Arrays.toString(containerSystem.getAppContextKeys()));
            return;
        }
        final ClassLoader classLoader = appContext.getClassLoader();
        SystemInstance.get().fireEvent(new AssemblerBeforeApplicationDestroyed(appInfo, appContext));
        // noinspection ConstantConditions
        final WebBeansContext webBeansContext = appContext.getWebBeansContext();
        if (webBeansContext != null) {
            final ClassLoader old = Thread.currentThread().getContextClassLoader();
            Thread.currentThread().setContextClassLoader(classLoader);
            try {
                final ServletContext context = appContext.isStandaloneModule() && appContext.getWebContexts().iterator().hasNext() ? appContext.getWebContexts().iterator().next().getServletContext() : null;
                webBeansContext.getService(ContainerLifecycle.class).stopApplication(context);
            } 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;
            }
            if (IvmContext.class.isInstance(globalContext)) {
                IvmContext.class.cast(globalContext).setReadOnly(false);
            }
            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<>();
        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<>();
        for (final ClientInfo clientInfo : appInfo.clients) {
            clientIds.add(clientInfo.moduleId);
            clientIds.addAll(clientInfo.localClients);
            clientIds.addAll(clientInfo.remoteClients);
        }
        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);
                }
            } catch (final NamingException e) {
                logger.warning("can't unbind resource '{0}'", id);
            }
        }
        for (final String id : appInfo.resourceIds) {
            final String name = OPENEJB_RESOURCE_JNDI_PREFIX + id;
            try {
                destroyLookedUpResource(globalContext, id, name);
            } catch (final NamingException e) {
                logger.warning("can't unbind resource '{0}'", id);
            }
        }
        for (final ConnectorInfo connector : appInfo.connectors) {
            if (connector.resourceAdapter == null || connector.resourceAdapter.id == null) {
                continue;
            }
            final String name = OPENEJB_RESOURCE_JNDI_PREFIX + connector.resourceAdapter.id;
            try {
                destroyLookedUpResource(globalContext, connector.resourceAdapter.id, name);
            } catch (final NamingException e) {
                logger.warning("can't unbind resource '{0}'", connector);
            }
            for (final ResourceInfo outbound : connector.outbound) {
                try {
                    destroyLookedUpResource(globalContext, outbound.id, OPENEJB_RESOURCE_JNDI_PREFIX + outbound.id);
                } catch (final Exception e) {
                // no-op
                }
            }
            for (final ResourceInfo outbound : connector.adminObject) {
                try {
                    destroyLookedUpResource(globalContext, outbound.id, OPENEJB_RESOURCE_JNDI_PREFIX + outbound.id);
                } catch (final Exception e) {
                // no-op
                }
            }
            for (final MdbContainerInfo container : connector.inbound) {
                try {
                    containerSystem.removeContainer(container.id);
                    config.containerSystem.containers.remove(container);
                    this.containerSystem.getJNDIContext().unbind(JAVA_OPENEJB_NAMING_CONTEXT + container.service + "/" + container.id);
                } catch (final Exception e) {
                // no-op
                }
            }
        }
        for (final ContainerInfo containerInfo : appInfo.containers) {
            if (!containerInfo.applicationWide) {
                removeContainer(containerInfo.id);
            }
        }
        containerSystem.removeAppContext(appInfo.appId);
        if (!appInfo.properties.containsKey("tomee.destroying")) {
            // destroy tomee classloader after resources cleanup
            try {
                final Method m = classLoader.getClass().getMethod("internalStop");
                m.invoke(classLoader);
            } catch (final NoSuchMethodException nsme) {
            // no-op
            } catch (final Exception e) {
                logger.error("error stopping classloader of webapp " + appInfo.appId, e);
            }
            ClassLoaderUtil.cleanOpenJPACache(classLoader);
        }
        ClassLoaderUtil.destroyClassLoader(appInfo.appId, appInfo.path);
        if (undeployException.getCauses().size() > 0) {
            // logging causes here otherwise it will be eaten in later logs.
            for (Throwable cause : undeployException.getCauses()) {
                logger.error("undeployException original cause", cause);
            }
            throw undeployException;
        }
        logger.debug("destroyApplication.success", appInfo.path);
    } finally {
        l.unlock();
    }
}
Also used : IvmContext(org.apache.openejb.core.ivm.naming.IvmContext) WebContext(org.apache.openejb.core.WebContext) ArrayList(java.util.ArrayList) AsynchronousPool(org.apache.openejb.async.AsynchronousPool) JMXContainer(org.apache.openejb.assembler.monitoring.JMXContainer) Container(org.apache.openejb.Container) WebBeansContext(org.apache.webbeans.config.WebBeansContext) ServletContext(javax.servlet.ServletContext) NamingException(javax.naming.NamingException) LocalMBeanServer(org.apache.openejb.monitoring.LocalMBeanServer) MBeanServer(javax.management.MBeanServer) ReentrantLock(java.util.concurrent.locks.ReentrantLock) WebContext(org.apache.openejb.core.WebContext) SimpleBootstrapContext(org.apache.openejb.core.transaction.SimpleBootstrapContext) Context(javax.naming.Context) ServletContext(javax.servlet.ServletContext) MethodContext(org.apache.openejb.MethodContext) IvmContext(org.apache.openejb.core.ivm.naming.IvmContext) AppContext(org.apache.openejb.AppContext) InitialContext(javax.naming.InitialContext) WebBeansContext(org.apache.webbeans.config.WebBeansContext) BeanContext(org.apache.openejb.BeanContext) CreationalContext(javax.enterprise.context.spi.CreationalContext) DeploymentContext(org.apache.openejb.DeploymentContext) GeronimoBootstrapContext(org.apache.geronimo.connector.GeronimoBootstrapContext) BootstrapContext(javax.resource.spi.BootstrapContext) MalformedObjectNameException(javax.management.MalformedObjectNameException) AppContext(org.apache.openejb.AppContext) InstanceNotFoundException(javax.management.InstanceNotFoundException) AssemblerBeforeApplicationDestroyed(org.apache.openejb.assembler.classic.event.AssemblerBeforeApplicationDestroyed) Method(java.lang.reflect.Method) InvalidObjectException(java.io.InvalidObjectException) NameAlreadyBoundException(javax.naming.NameAlreadyBoundException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ObjectStreamException(java.io.ObjectStreamException) ResourceAdapterInternalException(javax.resource.spi.ResourceAdapterInternalException) URISyntaxException(java.net.URISyntaxException) UndeployException(org.apache.openejb.UndeployException) DefinitionException(javax.enterprise.inject.spi.DefinitionException) ConstructionException(org.apache.xbean.recipe.ConstructionException) MBeanRegistrationException(javax.management.MBeanRegistrationException) InstanceNotFoundException(javax.management.InstanceNotFoundException) ValidationException(javax.validation.ValidationException) MalformedObjectNameException(javax.management.MalformedObjectNameException) DuplicateDeploymentIdException(org.apache.openejb.DuplicateDeploymentIdException) TimeoutException(java.util.concurrent.TimeoutException) NamingException(javax.naming.NamingException) OpenEJBException(org.apache.openejb.OpenEJBException) DeploymentException(javax.enterprise.inject.spi.DeploymentException) NoSuchApplicationException(org.apache.openejb.NoSuchApplicationException) MalformedURLException(java.net.MalformedURLException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) ContainerLifecycle(org.apache.webbeans.spi.ContainerLifecycle) ObjectName(javax.management.ObjectName) BeanContext(org.apache.openejb.BeanContext) CreationalContext(javax.enterprise.context.spi.CreationalContext) MBeanRegistrationException(javax.management.MBeanRegistrationException) ContextualJndiReference(org.apache.openejb.core.ivm.naming.ContextualJndiReference) UndeployException(org.apache.openejb.UndeployException)

Example 12 with WebContext

use of org.apache.openejb.core.WebContext in project tomee by apache.

the class LightweightWebAppBuilder method deployWebApps.

@Override
public void deployWebApps(final AppInfo appInfo, final ClassLoader appClassLoader) throws Exception {
    final CoreContainerSystem cs = (CoreContainerSystem) SystemInstance.get().getComponent(ContainerSystem.class);
    final AppContext appContext = cs.getAppContext(appInfo.appId);
    if (appContext == null) {
        throw new OpenEJBRuntimeException("Can't find app context for " + appInfo.appId);
    }
    for (final WebAppInfo webAppInfo : appInfo.webApps) {
        ClassLoader classLoader = loaderByWebContext.get(webAppInfo.moduleId);
        if (classLoader == null) {
            classLoader = appClassLoader;
        }
        final Set<Injection> injections = new HashSet<>(appContext.getInjections());
        injections.addAll(new InjectionBuilder(classLoader).buildInjections(webAppInfo.jndiEnc));
        final List<BeanContext> beanContexts;
        if (!appInfo.webAppAlone) {
            // add module bindings in app
            final Assembler assembler = SystemInstance.get().getComponent(Assembler.class);
            beanContexts = assembler.initEjbs(classLoader, appInfo, appContext, injections, new ArrayList<>(), webAppInfo.moduleId);
            appContext.getBeanContexts().addAll(beanContexts);
        } else {
            beanContexts = null;
        }
        final Map<String, Object> bindings = new HashMap<>();
        bindings.putAll(appContext.getBindings());
        bindings.putAll(new JndiEncBuilder(webAppInfo.jndiEnc, injections, webAppInfo.moduleId, "Bean", null, webAppInfo.uniqueId, classLoader, appInfo.properties).buildBindings(JndiEncBuilder.JndiScope.comp));
        final WebContext webContext = new WebContext(appContext);
        webContext.setBindings(bindings);
        webContext.getBindings().putAll(new JndiEncBuilder(webAppInfo.jndiEnc, injections, webAppInfo.moduleId, "Bean", null, webAppInfo.uniqueId, classLoader, appInfo.properties).buildBindings(JndiEncBuilder.JndiScope.comp));
        webContext.setJndiEnc(WebInitialContext.create(bindings, appContext.getGlobalJndiContext()));
        webContext.setClassLoader(classLoader);
        webContext.setId(webAppInfo.moduleId);
        webContext.setContextRoot(webAppInfo.contextRoot);
        webContext.setHost(webAppInfo.host);
        webContext.getInjections().addAll(injections);
        webContext.setInitialContext(new EmbeddedInitialContext(webContext.getJndiEnc(), webContext.getBindings()));
        final ServletContext component = SystemInstance.get().getComponent(ServletContext.class);
        final ServletContextEvent sce = component == null ? new MockServletContextEvent() : new ServletContextEvent(new LightServletContext(component, webContext.getClassLoader()));
        servletContextEvents.put(webAppInfo, sce);
        webContext.setServletContext(sce.getServletContext());
        SystemInstance.get().fireEvent(new EmbeddedServletContextCreated(sce.getServletContext()));
        appContext.getWebContexts().add(webContext);
        cs.addWebContext(webContext);
        if (!appInfo.webAppAlone && hasCdi(appInfo)) {
            final Assembler assembler = SystemInstance.get().getComponent(Assembler.class);
            new CdiBuilder().build(appInfo, appContext, beanContexts, webContext);
            assembler.startEjbs(true, beanContexts);
        }
        // listeners
        for (final ListenerInfo listener : webAppInfo.listeners) {
            final Class<?> clazz = webContext.getClassLoader().loadClass(listener.classname);
            final Object instance = webContext.newInstance(clazz);
            if (ServletContextListener.class.isInstance(instance)) {
                switchServletContextIfNeeded(sce.getServletContext(), new Runnable() {

                    @Override
                    public void run() {
                        ((ServletContextListener) instance).contextInitialized(sce);
                    }
                });
            }
            List<Object> list = listeners.computeIfAbsent(webAppInfo, k -> new ArrayList<>());
            list.add(instance);
        }
        for (final ClassListInfo info : webAppInfo.webAnnotatedClasses) {
            final String url = info.name;
            for (final String filterPath : info.list) {
                final Class<?> clazz = loadFromUrls(webContext.getClassLoader(), url, filterPath);
                final WebListener annotation = clazz.getAnnotation(WebListener.class);
                if (annotation != null) {
                    final Object instance = webContext.newInstance(clazz);
                    if (ServletContextListener.class.isInstance(instance)) {
                        switchServletContextIfNeeded(sce.getServletContext(), new Runnable() {

                            @Override
                            public void run() {
                                ((ServletContextListener) instance).contextInitialized(sce);
                            }
                        });
                    }
                    List<Object> list = listeners.computeIfAbsent(webAppInfo, k -> new ArrayList<>());
                    list.add(instance);
                }
            }
        }
        final DeployedWebObjects deployedWebObjects = new DeployedWebObjects();
        deployedWebObjects.webContext = webContext;
        servletDeploymentInfo.put(webAppInfo, deployedWebObjects);
        if (webContext.getWebBeansContext() != null && webContext.getWebBeansContext().getBeanManagerImpl().isInUse()) {
            final Thread thread = Thread.currentThread();
            final ClassLoader old = thread.getContextClassLoader();
            thread.setContextClassLoader(webContext.getClassLoader());
            try {
                OpenEJBLifecycle.class.cast(webContext.getWebBeansContext().getService(ContainerLifecycle.class)).startServletContext(sce.getServletContext());
            } finally {
                thread.setContextClassLoader(old);
            }
        }
        if (addServletMethod == null) {
            // can't manage filter/servlets
            continue;
        }
        // register filters
        for (final FilterInfo info : webAppInfo.filters) {
            switchServletContextIfNeeded(sce.getServletContext(), new Runnable() {

                @Override
                public void run() {
                    for (final String mapping : info.mappings) {
                        final FilterConfig config = new SimpleFilterConfig(sce.getServletContext(), info.name, info.initParams);
                        try {
                            addFilterMethod.invoke(null, info.classname, webContext, mapping, config);
                            deployedWebObjects.filterMappings.add(mapping);
                        } catch (final Exception e) {
                            LOGGER.warning(e.getMessage(), e);
                        }
                    }
                }
            });
        }
        for (final ClassListInfo info : webAppInfo.webAnnotatedClasses) {
            final String url = info.name;
            for (final String filterPath : info.list) {
                final Class<?> clazz = loadFromUrls(webContext.getClassLoader(), url, filterPath);
                final WebFilter annotation = clazz.getAnnotation(WebFilter.class);
                if (annotation != null) {
                    final Properties initParams = new Properties();
                    for (final WebInitParam param : annotation.initParams()) {
                        initParams.put(param.name(), param.value());
                    }
                    final FilterConfig config = new SimpleFilterConfig(sce.getServletContext(), info.name, initParams);
                    for (final String[] mappings : asList(annotation.urlPatterns(), annotation.value())) {
                        switchServletContextIfNeeded(sce.getServletContext(), new Runnable() {

                            @Override
                            public void run() {
                                for (final String mapping : mappings) {
                                    try {
                                        addFilterMethod.invoke(null, clazz.getName(), webContext, mapping, config);
                                        deployedWebObjects.filterMappings.add(mapping);
                                    } catch (final Exception e) {
                                        LOGGER.warning(e.getMessage(), e);
                                    }
                                }
                            }
                        });
                    }
                }
            }
        }
        final Map<String, PortInfo> ports = new TreeMap<>();
        for (final PortInfo port : webAppInfo.portInfos) {
            ports.put(port.serviceLink, port);
        }
        // register servlets
        for (final ServletInfo info : webAppInfo.servlets) {
            if ("true".equalsIgnoreCase(appInfo.properties.getProperty("openejb.jaxrs.on", "true"))) {
                // skip jaxrs servlets
                boolean skip = false;
                for (final ParamValueInfo pvi : info.initParams) {
                    if ("javax.ws.rs.Application".equals(pvi.name) || Application.class.getName().equals(pvi.name)) {
                        skip = true;
                    }
                }
                if (skip) {
                    continue;
                }
                if (info.servletClass == null) {
                    try {
                        if (Application.class.isAssignableFrom(classLoader.loadClass(info.servletName))) {
                            continue;
                        }
                    } catch (final Exception e) {
                    // no-op
                    }
                }
            }
            // If POJO web services, it will be overriden with WsServlet
            if (ports.containsKey(info.servletName) || ports.containsKey(info.servletClass)) {
                continue;
            }
            // deploy
            for (final String mapping : info.mappings) {
                switchServletContextIfNeeded(sce.getServletContext(), new Runnable() {

                    @Override
                    public void run() {
                        try {
                            addServletMethod.invoke(null, info.servletClass, webContext, mapping);
                            deployedWebObjects.mappings.add(mapping);
                        } catch (final Exception e) {
                            LOGGER.warning(e.getMessage(), e);
                        }
                    }
                });
            }
        }
        for (final ClassListInfo info : webAppInfo.webAnnotatedClasses) {
            final String url = info.name;
            for (final String servletPath : info.list) {
                final Class<?> clazz = loadFromUrls(webContext.getClassLoader(), url, servletPath);
                final WebServlet annotation = clazz.getAnnotation(WebServlet.class);
                if (annotation != null) {
                    for (final String[] mappings : asList(annotation.urlPatterns(), annotation.value())) {
                        switchServletContextIfNeeded(sce.getServletContext(), new Runnable() {

                            @Override
                            public void run() {
                                for (final String mapping : mappings) {
                                    try {
                                        addServletMethod.invoke(null, clazz.getName(), webContext, mapping);
                                        deployedWebObjects.mappings.add(mapping);
                                    } catch (final Exception e) {
                                        LOGGER.warning(e.getMessage(), e);
                                    }
                                }
                            }
                        });
                    }
                }
            }
        }
        if (addDefaults != null && tryJsp()) {
            addDefaults.invoke(null, webContext);
            deployedWebObjects.mappings.add("*\\.jsp");
        }
    }
}
Also used : CoreContainerSystem(org.apache.openejb.core.CoreContainerSystem) ContainerSystem(org.apache.openejb.spi.ContainerSystem) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ServletInfo(org.apache.openejb.assembler.classic.ServletInfo) WebAppInfo(org.apache.openejb.assembler.classic.WebAppInfo) ParamValueInfo(org.apache.openejb.assembler.classic.ParamValueInfo) FilterConfig(javax.servlet.FilterConfig) HashSet(java.util.HashSet) InjectionBuilder(org.apache.openejb.assembler.classic.InjectionBuilder) CoreContainerSystem(org.apache.openejb.core.CoreContainerSystem) Injection(org.apache.openejb.Injection) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) BeanContext(org.apache.openejb.BeanContext) ListenerInfo(org.apache.openejb.assembler.classic.ListenerInfo) CdiBuilder(org.apache.openejb.cdi.CdiBuilder) Assembler(org.apache.openejb.assembler.classic.Assembler) OpenEJBLifecycle(org.apache.openejb.cdi.OpenEJBLifecycle) WebContext(org.apache.openejb.core.WebContext) MockServletContextEvent(org.apache.webbeans.web.lifecycle.test.MockServletContextEvent) Properties(java.util.Properties) ClassListInfo(org.apache.openejb.assembler.classic.ClassListInfo) PortInfo(org.apache.openejb.assembler.classic.PortInfo) WebServlet(javax.servlet.annotation.WebServlet) MockServletContext(org.apache.webbeans.web.lifecycle.test.MockServletContext) ServletContext(javax.servlet.ServletContext) FilterInfo(org.apache.openejb.assembler.classic.FilterInfo) WebFilter(javax.servlet.annotation.WebFilter) AppContext(org.apache.openejb.AppContext) TreeMap(java.util.TreeMap) NamingException(javax.naming.NamingException) NameNotFoundException(javax.naming.NameNotFoundException) MalformedURLException(java.net.MalformedURLException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) WebListener(javax.servlet.annotation.WebListener) JndiEncBuilder(org.apache.openejb.assembler.classic.JndiEncBuilder) WebInitParam(javax.servlet.annotation.WebInitParam) ServletContextEvent(javax.servlet.ServletContextEvent) MockServletContextEvent(org.apache.webbeans.web.lifecycle.test.MockServletContextEvent)

Example 13 with WebContext

use of org.apache.openejb.core.WebContext in project tomee by apache.

the class LightweightWebAppBuilderTest method checkWebContextExists.

@Test
public void checkWebContextExists() {
    final WebContext wc = SystemInstance.get().getComponent(ContainerSystem.class).getWebContext("web");
    assertNotNull(wc);
    assertEquals("web", wc.getId());
}
Also used : ContainerSystem(org.apache.openejb.spi.ContainerSystem) WebContext(org.apache.openejb.core.WebContext) Test(org.junit.Test)

Example 14 with WebContext

use of org.apache.openejb.core.WebContext in project tomee by apache.

the class ValidatorUtil method proxy.

// proxy because depending on when injection/threadcontext is set
// it is better to do it lazily
// this is mainly done for tests since the first lookup will work in TomEE
private static <T> T proxy(final Class<T> t, final String jndi) {
    return t.cast(Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[] { t }, new InvocationHandler() {

        @Override
        public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
            if (Object.class.equals(method.getDeclaringClass())) {
                return method.invoke(this);
            }
            final ThreadContext ctx = ThreadContext.getThreadContext();
            if (ctx != null) {
                return method.invoke(ctx.getBeanContext().getJndiContext().lookup(jndi), args);
            }
            // try to find from current ClassLoader
            // can lead to find the bad validator regarding module separation
            // but since it shares the same classloader
            // it will probably share the same config
            // so the behavior will be the same
            // + this code should rarely be used
            final ClassLoader tccl = Thread.currentThread().getContextClassLoader();
            if (tccl == null) {
                return null;
            }
            final ContainerSystem containerSystem = SystemInstance.get().getComponent(ContainerSystem.class);
            Object value = null;
            for (final AppContext appContext : containerSystem.getAppContexts()) {
                final ClassLoader appContextClassLoader = appContext.getClassLoader();
                if (tccl.equals(appContextClassLoader) || appContextClassLoader.equals(tccl)) {
                    final Collection<String> tested = new ArrayList<>();
                    for (final BeanContext bean : appContext.getBeanContexts()) {
                        if (BeanContext.Comp.class.equals(bean.getBeanClass())) {
                            final String uniqueId = bean.getModuleContext().getUniqueId();
                            if (tested.contains(uniqueId)) {
                                continue;
                            }
                            tested.add(uniqueId);
                            try {
                                value = containerSystem.getJNDIContext().lookup((jndi.endsWith("Factory") ? Assembler.VALIDATOR_FACTORY_NAMING_CONTEXT : Assembler.VALIDATOR_NAMING_CONTEXT) + uniqueId);
                                break;
                            } catch (final NameNotFoundException nnfe) {
                            // no-op
                            }
                        }
                    }
                    if (ClassLoader.getSystemClassLoader() != appContextClassLoader) {
                        break;
                    }
                // else we surely have a single AppContext so let's try WebContext
                }
                for (final WebContext web : appContext.getWebContexts()) {
                    final ClassLoader webClassLoader = web.getClassLoader();
                    if (webClassLoader.equals(tccl) || tccl.equals(webClassLoader)) {
                        value = web.getJndiEnc().lookup(jndi);
                        break;
                    }
                }
                if (value != null) {
                    break;
                }
            }
            if (value != null) {
                return method.invoke(value, args);
            }
            return null;
        }

        @Override
        public String toString() {
            return "Proxy::" + t.getName();
        }
    }));
}
Also used : ContainerSystem(org.apache.openejb.spi.ContainerSystem) WebContext(org.apache.openejb.core.WebContext) NameNotFoundException(javax.naming.NameNotFoundException) AppContext(org.apache.openejb.AppContext) ThreadContext(org.apache.openejb.core.ThreadContext) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) InvocationHandler(java.lang.reflect.InvocationHandler) BeanContext(org.apache.openejb.BeanContext)

Example 15 with WebContext

use of org.apache.openejb.core.WebContext in project tomee by apache.

the class CdiResourceInjectionService method fillInjectionProperties.

@SuppressWarnings("unchecked")
private void fillInjectionProperties(final ObjectRecipe objectRecipe, final Object managedBeanInstance) {
    final boolean usePrefix = true;
    final Class<?> clazz = managedBeanInstance.getClass();
    Collection<BeanContext> comps;
    WebBeansContext webBeansContext = null;
    if (ear) {
        // let it be contextual, ie use webapp context (env-entries...) to create ear libs interceptors...
        try {
            webBeansContext = WebBeansContext.currentInstance();
            comps = CdiResourceInjectionService.class.cast(webBeansContext.getService(ResourceInjectionService.class)).compContexts;
        } catch (final Exception e) {
            comps = compContexts;
        }
    } else {
        comps = compContexts;
    }
    for (final BeanContext beanContext : comps) {
        for (final Injection injection : beanContext.getInjections()) {
            if (injection.getTarget() == null) {
                continue;
            }
            if (!injection.getTarget().isAssignableFrom(clazz)) {
                continue;
            }
            final String prefix;
            if (usePrefix) {
                prefix = injection.getTarget().getName() + "/";
            } else {
                prefix = "";
            }
            try {
                final Object value = lookup(beanContext, injection);
                objectRecipe.setProperty(prefix + injection.getName(), value);
            } catch (final NamingException e) {
                boolean found = false;
                if (webBeansContext != null) {
                    for (final WebContext w : appCtx.getWebContexts()) {
                        if (w.getWebBeansContext() == webBeansContext) {
                            final Object value = w.getBindings().get(injection.getJndiName());
                            if (value != null) {
                                objectRecipe.setProperty(prefix + injection.getName(), value);
                                found = true;
                            }
                            break;
                        }
                    }
                }
                if (!found) {
                    logger.warning("Injection data not found in JNDI context: jndiName='" + injection.getJndiName() + "', target=" + injection.getTarget().getName() + "/" + injection.getName());
                }
            }
        }
    }
}
Also used : BeanContext(org.apache.openejb.BeanContext) WebBeansContext(org.apache.webbeans.config.WebBeansContext) WebContext(org.apache.openejb.core.WebContext) NamingException(javax.naming.NamingException) Injection(org.apache.openejb.Injection) ResourceInjectionService(org.apache.webbeans.spi.ResourceInjectionService) NamingException(javax.naming.NamingException) IOException(java.io.IOException)

Aggregations

WebContext (org.apache.openejb.core.WebContext)25 AppContext (org.apache.openejb.AppContext)17 BeanContext (org.apache.openejb.BeanContext)11 ContainerSystem (org.apache.openejb.spi.ContainerSystem)11 WebBeansContext (org.apache.webbeans.config.WebBeansContext)9 NamingException (javax.naming.NamingException)8 IOException (java.io.IOException)7 Context (javax.naming.Context)7 OpenEJBRuntimeException (org.apache.openejb.OpenEJBRuntimeException)7 ArrayList (java.util.ArrayList)6 ServletContext (javax.servlet.ServletContext)6 OpenEJBException (org.apache.openejb.OpenEJBException)6 MalformedURLException (java.net.MalformedURLException)5 NameNotFoundException (javax.naming.NameNotFoundException)5 Injection (org.apache.openejb.Injection)5 WebAppInfo (org.apache.openejb.assembler.classic.WebAppInfo)5 InitialContext (javax.naming.InitialContext)4 ThreadContext (org.apache.openejb.core.ThreadContext)4 URL (java.net.URL)3 HashSet (java.util.HashSet)3