Search in sources :

Example 1 with CoreContainerSystem

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

the class OpenEjbBrokerFactoryTest method testLookupDataSource.

public void testLookupDataSource() throws Exception {
    final Properties properties = new Properties();
    final JDBCDataSource dataSource = new JDBCDataSource();
    dataSource.setDatabase("jdbc:hsqldb:mem:testdb" + System.currentTimeMillis());
    dataSource.setUser("sa");
    dataSource.setPassword("");
    dataSource.getConnection().close();
    MockInitialContextFactory.install(Collections.singletonMap("openejb/Resource/TestDs", dataSource));
    assertSame(dataSource, new InitialContext().lookup("openejb/Resource/TestDs"));
    final CoreContainerSystem containerSystem = new CoreContainerSystem(new IvmJndiFactory());
    containerSystem.getJNDIContext().bind("openejb/Resource/TestDs", dataSource);
    SystemInstance.get().setComponent(ContainerSystem.class, containerSystem);
    properties.put("DataSource", "TestDs");
    properties.put("UseDatabaseLock", "false");
    properties.put("StartupTimeout", "10000");
    ActiveMQFactory.setThreadProperties(properties);
    BrokerService broker = null;
    try {
        broker = BrokerFactory.createBroker(new URI(getBrokerUri("broker:(tcp://localhost:" + brokerPort + ")?useJmx=false")));
        assertNotNull("broker is null", broker);
        final PersistenceAdapter persistenceAdapter = broker.getPersistenceAdapter();
        assertNotNull("persistenceAdapter is null", persistenceAdapter);
        assertTrue("persistenceAdapter should be an instance of JDBCPersistenceAdapter", persistenceAdapter instanceof JDBCPersistenceAdapter);
        final JDBCPersistenceAdapter jdbcPersistenceAdapter = (JDBCPersistenceAdapter) persistenceAdapter;
        assertSame(dataSource, jdbcPersistenceAdapter.getDataSource());
    } finally {
        stopBroker(broker);
        ActiveMQFactory.setThreadProperties(null);
    }
}
Also used : JDBCPersistenceAdapter(org.apache.activemq.store.jdbc.JDBCPersistenceAdapter) IvmJndiFactory(org.apache.openejb.core.ivm.naming.IvmJndiFactory) JDBCDataSource(org.hsqldb.jdbc.JDBCDataSource) CoreContainerSystem(org.apache.openejb.core.CoreContainerSystem) Properties(java.util.Properties) BrokerService(org.apache.activemq.broker.BrokerService) URI(java.net.URI) InitialContext(javax.naming.InitialContext) MemoryPersistenceAdapter(org.apache.activemq.store.memory.MemoryPersistenceAdapter) JDBCPersistenceAdapter(org.apache.activemq.store.jdbc.JDBCPersistenceAdapter) PersistenceAdapter(org.apache.activemq.store.PersistenceAdapter)

Example 2 with CoreContainerSystem

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

the class Assembler method buildContainerSystem.

/////////////////////////////////////////////////////////////////////
////
////    Public Methods Used for Assembly
////
/////////////////////////////////////////////////////////////////////
/**
     * When given a complete OpenEjbConfiguration graph this method
     * will construct an entire container system and return a reference to that
     * container system, as ContainerSystem instance.
     * <p/>
     * This method leverage the other assemble and apply methods which
     * can be used independently.
     * <p/>
     * Assembles and returns the {@link CoreContainerSystem} using the
     * information from the {@link OpenEjbConfiguration} object passed in.
     * <pre>
     * This method performs the following actions(in order):
     *
     * 1  Assembles ProxyFactory
     * 2  Assembles External JNDI Contexts
     * 3  Assembles TransactionService
     * 4  Assembles SecurityService
     * 5  Assembles ConnectionManagers
     * 6  Assembles Connectors
     * 7  Assembles Containers
     * 8  Assembles Applications
     * </pre>
     *
     * @param configInfo OpenEjbConfiguration
     * @throws Exception if there was a problem constructing the ContainerSystem.
     * @see OpenEjbConfiguration
     */
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
public void buildContainerSystem(final OpenEjbConfiguration configInfo) throws Exception {
    final SystemInstance systemInstance = SystemInstance.get();
    if (systemInstance.getOptions().get(OPENEJB_JPA_DEPLOY_TIME_ENHANCEMENT_PROP, false)) {
        systemInstance.addObserver(new DeployTimeEnhancer());
    }
    if (hasBatchEE()) {
        systemInstance.addObserver(new BatchEEServiceManager());
    }
    for (final ServiceInfo serviceInfo : configInfo.facilities.services) {
        createService(serviceInfo);
    }
    final ContainerSystemInfo containerSystemInfo = configInfo.containerSystem;
    if (configInfo.facilities.intraVmServer != null) {
        createProxyFactory(configInfo.facilities.intraVmServer);
    }
    for (final JndiContextInfo contextInfo : configInfo.facilities.remoteJndiContexts) {
        createExternalContext(contextInfo);
    }
    createTransactionManager(configInfo.facilities.transactionService);
    createSecurityService(configInfo.facilities.securityService);
    final Set<String> reservedResourceIds = new HashSet<>(configInfo.facilities.resources.size());
    for (final AppInfo appInfo : containerSystemInfo.applications) {
        reservedResourceIds.addAll(appInfo.resourceIds);
    }
    final Set<String> rIds = new HashSet<>(configInfo.facilities.resources.size());
    for (final ResourceInfo resourceInfo : configInfo.facilities.resources) {
        createResource(configInfo.facilities.services, resourceInfo);
        rIds.add(resourceInfo.id);
    }
    rIds.removeAll(reservedResourceIds);
    final ContainerSystem component = systemInstance.getComponent(ContainerSystem.class);
    if (component != null) {
        postConstructResources(rIds, ParentClassLoaderFinder.Helper.get(), component.getJNDIContext(), null);
    } else {
        throw new RuntimeException("ContainerSystem has not been initialzed");
    }
    // Containers
    for (final ContainerInfo serviceInfo : containerSystemInfo.containers) {
        createContainer(serviceInfo);
    }
    // before any deployment bind global to be able to share the same context
    createJavaGlobal();
    for (final AppInfo appInfo : containerSystemInfo.applications) {
        try {
            createApplication(appInfo, createAppClassLoader(appInfo));
        } catch (final DuplicateDeploymentIdException e) {
        // already logged.
        } catch (final Throwable e) {
            logger.error("appNotDeployed", e, appInfo.path);
            final DeploymentExceptionManager exceptionManager = systemInstance.getComponent(DeploymentExceptionManager.class);
            if (exceptionManager != null && e instanceof Exception) {
                exceptionManager.saveDeploymentException(appInfo, (Exception) e);
            }
        }
    }
    systemInstance.fireEvent(new ContainerSystemPostCreate());
}
Also used : CoreContainerSystem(org.apache.openejb.core.CoreContainerSystem) ContainerSystem(org.apache.openejb.spi.ContainerSystem) 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) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) DuplicateDeploymentIdException(org.apache.openejb.DuplicateDeploymentIdException) SystemInstance(org.apache.openejb.loader.SystemInstance) BatchEEServiceManager(org.apache.openejb.batchee.BatchEEServiceManager) HashSet(java.util.HashSet) ContainerSystemPostCreate(org.apache.openejb.assembler.classic.event.ContainerSystemPostCreate)

Example 3 with CoreContainerSystem

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

the class TomcatWebAppBuilder method startInternal.

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

Example 4 with CoreContainerSystem

use of org.apache.openejb.core.CoreContainerSystem 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<Injection>(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<BeanContext>(), 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.get(webAppInfo);
            if (list == null) {
                list = new ArrayList<Object>();
                listeners.put(webAppInfo, list);
            }
            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.get(webAppInfo);
                    if (list == null) {
                        list = new ArrayList<Object>();
                        listeners.put(webAppInfo, list);
                    }
                    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<String, PortInfo>();
        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 5 with CoreContainerSystem

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

the class ContextualJndiReferenceTest method propagateUnwrapping.

@Test
public void propagateUnwrapping() throws NamingException {
    SystemInstance.get().setComponent(ContainerSystem.class, new CoreContainerSystem(new IvmJndiFactory()));
    final ContextualJndiReference ref = new ContextualJndiReference("foo");
    ref.setDefaultValue(new Reference() {

        @Override
        public Object getObject() throws NamingException {
            return "yeah";
        }
    });
    assertEquals("yeah", ref.getObject());
    SystemInstance.reset();
}
Also used : NamingException(javax.naming.NamingException) CoreContainerSystem(org.apache.openejb.core.CoreContainerSystem) Test(org.junit.Test)

Aggregations

CoreContainerSystem (org.apache.openejb.core.CoreContainerSystem)7 Properties (java.util.Properties)4 NamingException (javax.naming.NamingException)4 HashSet (java.util.HashSet)3 OpenEJBRuntimeException (org.apache.openejb.OpenEJBRuntimeException)3 IOException (java.io.IOException)2 MalformedURLException (java.net.MalformedURLException)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 InitialContext (javax.naming.InitialContext)2 NameNotFoundException (javax.naming.NameNotFoundException)2 ServletContext (javax.servlet.ServletContext)2 AppContext (org.apache.openejb.AppContext)2 OpenEJBException (org.apache.openejb.OpenEJBException)2 WebContext (org.apache.openejb.core.WebContext)2 IvmJndiFactory (org.apache.openejb.core.ivm.naming.IvmJndiFactory)2 ContainerSystem (org.apache.openejb.spi.ContainerSystem)2 Before (org.junit.Before)2 File (java.io.File)1