Search in sources :

Example 21 with AppModule

use of org.apache.openejb.config.AppModule in project tomee by apache.

the class ResourcesJsonTest method setUp.

@Before
public void setUp() throws OpenEJBException, NamingException, IOException {
    final ConfigurationFactory config = new ConfigurationFactory();
    final Assembler assembler = new Assembler();
    assembler.createTransactionManager(config.configureService(TransactionServiceInfo.class));
    assembler.createSecurityService(config.configureService(SecurityServiceInfo.class));
    final AppModule app = new AppModule(ResourcesJsonTest.class.getClassLoader(), ResourcesJsonTest.class.getSimpleName());
    final EjbJar ejbJar = new EjbJar();
    ejbJar.addEnterpriseBean(new SingletonBean(ConfiguredThroughJSonBean.class));
    app.getEjbModules().add(new EjbModule(ejbJar));
    app.getEjbModules().iterator().next().getAltDDs().put("resources.json", getClass().getClassLoader().getResource("appresource.resources.json"));
    assembler.createApplication(config.configureApplication(app));
    final Properties properties = new Properties();
    properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, LocalInitialContextFactory.class.getName());
    properties.setProperty("openejb.embedded.initialcontext.close", "destroy");
    // some hack to be sure to call destroy()
    context = new InitialContext(properties);
    bean = (ConfiguredThroughJSonBean) context.lookup("ConfiguredThroughJSonBeanLocalBean");
}
Also used : AppModule(org.apache.openejb.config.AppModule) EjbModule(org.apache.openejb.config.EjbModule) Properties(java.util.Properties) LocalInitialContextFactory(org.apache.openejb.core.LocalInitialContextFactory) InitialContext(javax.naming.InitialContext) SingletonBean(org.apache.openejb.jee.SingletonBean) ConfigurationFactory(org.apache.openejb.config.ConfigurationFactory) EjbJar(org.apache.openejb.jee.EjbJar) Before(org.junit.Before)

Example 22 with AppModule

use of org.apache.openejb.config.AppModule in project tomee by apache.

the class Container method deploy.

public Container deploy(final DeploymentRequest request) {
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    final SystemInstance systemInstance = SystemInstance.get();
    String contextRoot = request.context == null ? "" : request.context;
    if (!contextRoot.isEmpty() && !contextRoot.startsWith("/")) {
        contextRoot = "/" + request.context;
    }
    File jarLocation = request.docBase == null || !request.docBase.isDirectory() ? fakeRootDir() : request.docBase;
    final WebModule webModule = new WebModule(new WebApp(), contextRoot, loader, jarLocation.getAbsolutePath(), contextRoot.replace("/", ""));
    if (request.docBase == null) {
        webModule.getProperties().put("fakeJarLocation", "true");
    }
    webModule.setUrls(request.jarList);
    webModule.setAddedUrls(Collections.<URL>emptyList());
    webModule.setRarUrls(Collections.<URL>emptyList());
    webModule.setScannableUrls(request.jarList);
    final AnnotationFinder finder;
    try {
        Filter filter = configuration.getClassesFilter();
        if (filter == null && (request.jarList.size() <= 4 || "true".equalsIgnoreCase(SystemInstance.get().getProperty("tomee.embedded.filter-container-classes")))) {
            filter = new ContainerClassesFilter(configuration.getProperties());
        }
        final Archive archive;
        if (request.archive == null) {
            archive = new WebappAggregatedArchive(webModule, request.jarList, // see org.apache.openejb.config.DeploymentsResolver.ClasspathSearcher.cleanUpUrlSet()
            filter);
        } else if (WebappAggregatedArchive.class.isInstance(request.archive)) {
            archive = request.archive;
        } else {
            archive = new WebappAggregatedArchive(request.archive, request.jarList);
        }
        finder = new FinderFactory.OpenEJBAnnotationFinder(archive).link();
        SystemInstance.get().fireEvent(new TomEEEmbeddedScannerCreated(finder));
        webModule.setFinder(finder);
    } catch (final Exception e) {
        throw new IllegalArgumentException(e);
    }
    final File beansXml = new File(request.docBase, "WEB-INF/beans.xml");
    if (beansXml.exists()) {
        // add it since it is not in the scanned path by default
        try {
            webModule.getAltDDs().put("beans.xml", beansXml.toURI().toURL());
        } catch (final MalformedURLException e) {
        // no-op
        }
    }
    // else no classpath finding since we'll likely find it
    DeploymentLoader.addBeansXmls(webModule);
    final AppModule app = new AppModule(loader, null);
    app.setStandloneWebModule();
    app.setStandaloneModule(true);
    app.setModuleId(webModule.getModuleId());
    try {
        final Map<String, URL> webDescriptors = DeploymentLoader.getWebDescriptors(jarLocation);
        if (webDescriptors.isEmpty()) {
            // likely so let's try to find them in the classpath
            final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            final Collection<String> metaDir = asList("META-INF/tomee/", "META-INF/");
            for (final String dd : asList("app-ctx.xml", "module.properties", "application.properties", "env-entries.properties", NewLoaderLogic.EXCLUSION_FILE, "web.xml", "ejb-jar.xml", "openejb-jar.xml", "validation.xml")) {
                if (Boolean.parseBoolean(SystemInstance.get().getProperty("tomee.embedded.descriptors.classpath." + dd + ".skip")) || webDescriptors.containsKey(dd)) {
                    continue;
                }
                for (final String meta : metaDir) {
                    final URL url = classLoader.getResource(meta + dd);
                    if (url != null) {
                        webDescriptors.put(dd, url);
                        break;
                    }
                }
            }
        }
        webDescriptors.remove("beans.xml");
        webModule.getAltDDs().putAll(webDescriptors);
        DeploymentLoader.addWebModule(webModule, app);
        DeploymentLoader.addWebModuleDescriptors(new File(webModule.getJarLocation()).toURI().toURL(), webModule, app);
    } catch (final Exception e) {
        throw new IllegalStateException(e);
    }
    if (!SystemInstance.isInitialized() || Boolean.parseBoolean(SystemInstance.get().getProperty("tomee.embedded.add-callers", "true"))) {
        addCallersAsEjbModule(loader, app, request.additionalCallers);
    }
    systemInstance.addObserver(new StandardContextCustomizer(configuration, webModule, request.keepClassloader));
    if (systemInstance.getComponent(AnnotationDeployer.FolderDDMapper.class) == null) {
        systemInstance.setComponent(AnnotationDeployer.FolderDDMapper.class, new AnnotationDeployer.FolderDDMapper() {

            @Override
            public File getDDFolder(final File dir) {
                try {
                    return isMaven(dir) || isGradle(dir) ? new File(request.docBase, "WEB-INF") : null;
                } catch (final RuntimeException re) {
                    // folder doesn't exist -> test is stopped which is expected
                    return null;
                }
            }

            private boolean isGradle(final File dir) {
                return dir.getName().equals("classes") && dir.getParentFile().getName().equals("target");
            }

            private boolean isMaven(final File dir) {
                return dir.getName().equals("main") && dir.getParentFile().getName().equals("classes") && dir.getParentFile().getParentFile().getName().equals("build");
            }
        });
    }
    try {
        final AppInfo appInfo = configurationFactory.configureApplication(app);
        systemInstance.getComponent(Assembler.class).createApplication(appInfo, loader);
    } catch (final Exception e) {
        throw new IllegalStateException(e);
    }
    return this;
}
Also used : TomEEEmbeddedScannerCreated(org.apache.tomee.embedded.event.TomEEEmbeddedScannerCreated) MalformedURLException(java.net.MalformedURLException) WebappAggregatedArchive(org.apache.openejb.config.WebappAggregatedArchive) Archive(org.apache.xbean.finder.archive.Archive) AppModule(org.apache.openejb.config.AppModule) ContainerClassesFilter(org.apache.openejb.util.ContainerClassesFilter) URL(java.net.URL) TomEERuntimeException(org.apache.tomee.catalina.TomEERuntimeException) SystemInstance(org.apache.openejb.loader.SystemInstance) WebModule(org.apache.openejb.config.WebModule) LifecycleException(org.apache.catalina.LifecycleException) IOException(java.io.IOException) TomEERuntimeException(org.apache.tomee.catalina.TomEERuntimeException) NamingException(javax.naming.NamingException) UndeployException(org.apache.openejb.UndeployException) OpenEJBException(org.apache.openejb.OpenEJBException) NoSuchApplicationException(org.apache.openejb.NoSuchApplicationException) MalformedURLException(java.net.MalformedURLException) AppInfo(org.apache.openejb.assembler.classic.AppInfo) WebAppInfo(org.apache.openejb.assembler.classic.WebAppInfo) AnnotationDeployer(org.apache.openejb.config.AnnotationDeployer) StandardContextCustomizer(org.apache.tomee.embedded.internal.StandardContextCustomizer) Filter(org.apache.xbean.finder.filter.Filter) ContainerClassesFilter(org.apache.openejb.util.ContainerClassesFilter) WebappAggregatedArchive(org.apache.openejb.config.WebappAggregatedArchive) Assembler(org.apache.openejb.assembler.classic.Assembler) File(java.io.File) AnnotationFinder(org.apache.xbean.finder.AnnotationFinder) WebApp(org.apache.openejb.jee.WebApp)

Example 23 with AppModule

use of org.apache.openejb.config.AppModule in project tomee by apache.

the class DeployerEjb method deploy.

@Override
public AppInfo deploy(final String inLocation, Properties properties) throws OpenEJBException {
    String rawLocation = inLocation;
    if (rawLocation == null && properties == null) {
        throw new NullPointerException("location and properties are null");
    }
    if (rawLocation == null) {
        rawLocation = properties.getProperty(FILENAME);
    }
    if (properties == null) {
        properties = new Properties();
    }
    AppModule appModule = null;
    final File file;
    if ("true".equalsIgnoreCase(properties.getProperty(OPENEJB_USE_BINARIES, "false"))) {
        file = copyBinaries(properties);
    } else {
        file = new File(realLocation(rawLocation).iterator().next());
    }
    final boolean autoDeploy = Boolean.parseBoolean(properties.getProperty(OPENEJB_APP_AUTODEPLOY, "false"));
    final String host = properties.getProperty(OPENEJB_DEPLOYER_HOST, null);
    if (WebAppDeployer.Helper.isWebApp(file) && !oldWarDeployer) {
        AUTO_DEPLOY.set(autoDeploy);
        try {
            final AppInfo appInfo = SystemInstance.get().getComponent(WebAppDeployer.class).deploy(host, contextRoot(properties, file.getAbsolutePath()), file);
            if (appInfo != null) {
                saveIfNeeded(properties, file, appInfo);
                return appInfo;
            }
            throw new OpenEJBException("can't deploy " + file.getAbsolutePath());
        } finally {
            AUTO_DEPLOY.remove();
        }
    }
    AppInfo appInfo = null;
    try {
        appModule = deploymentLoader.load(file, null);
        // Add any alternate deployment descriptors to the modules
        final Map<String, DeploymentModule> modules = new TreeMap<>();
        for (final DeploymentModule module : appModule.getEjbModules()) {
            modules.put(module.getModuleId(), module);
        }
        for (final DeploymentModule module : appModule.getClientModules()) {
            modules.put(module.getModuleId(), module);
        }
        for (final WebModule module : appModule.getWebModules()) {
            final String contextRoot = contextRoot(properties, module.getJarLocation());
            if (contextRoot != null) {
                module.setContextRoot(contextRoot);
                module.setHost(host);
            }
            modules.put(module.getModuleId(), module);
        }
        for (final DeploymentModule module : appModule.getConnectorModules()) {
            modules.put(module.getModuleId(), module);
        }
        for (final Map.Entry<Object, Object> entry : properties.entrySet()) {
            String name = (String) entry.getKey();
            if (name.startsWith(ALT_DD + "/")) {
                name = name.substring(ALT_DD.length() + 1);
                final DeploymentModule module;
                final int slash = name.indexOf('/');
                if (slash > 0) {
                    final String moduleId = name.substring(0, slash);
                    name = name.substring(slash + 1);
                    module = modules.get(moduleId);
                } else {
                    module = appModule;
                }
                if (module != null) {
                    final String value = (String) entry.getValue();
                    final File dd = new File(value);
                    if (dd.canRead()) {
                        module.getAltDDs().put(name, dd.toURI().toURL());
                    } else {
                        module.getAltDDs().put(name, value);
                    }
                }
            }
        }
        final OpenEjbConfiguration configuration = new OpenEjbConfiguration();
        configuration.containerSystem = new ContainerSystemInfo();
        configuration.facilities = new FacilitiesInfo();
        final ConfigurationFactory configurationFactory = new ConfigurationFactory(false, configuration);
        appInfo = configurationFactory.configureApplication(appModule);
        appInfo.autoDeploy = autoDeploy;
        if (properties != null && properties.containsKey(OPENEJB_DEPLOYER_FORCED_APP_ID_PROP)) {
            appInfo.appId = properties.getProperty(OPENEJB_DEPLOYER_FORCED_APP_ID_PROP);
        }
        if (!appInfo.webApps.isEmpty()) {
            appInfo.properties.setProperty("tomcat.unpackWar", "false");
        }
        // create any resources and containers defined in the application itself
        if (!appInfo.webApps.isEmpty()) {
            appInfo.properties.setProperty("tomcat.unpackWar", "false");
        }
        final ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
        final ClassLoader appClassLoader = assembler.createAppClassLoader(appInfo);
        try {
            Thread.currentThread().setContextClassLoader(appClassLoader);
            for (final ResourceInfo resource : configuration.facilities.resources) {
                assembler.createResource(resource);
            }
            for (final ContainerInfo container : configuration.containerSystem.containers) {
                assembler.createContainer(container);
            }
        } finally {
            Thread.currentThread().setContextClassLoader(oldCl);
        }
        assembler.createApplication(appInfo, appClassLoader);
        saveIfNeeded(properties, file, appInfo);
        return appInfo;
    } catch (final Throwable e) {
        // destroy the class loader for the failed application
        if (appModule != null) {
            ClassLoaderUtil.destroyClassLoader(appModule.getJarLocation());
        }
        if (null != appInfo) {
            ClassLoaderUtil.destroyClassLoader(appInfo.appId, appInfo.path);
        }
        LOGGER.error("Can't deploy " + inLocation, e);
        if (e instanceof ValidationException) {
            throw (ValidationException) e;
        }
        final Throwable ex;
        final DeploymentExceptionManager dem = SystemInstance.get().getComponent(DeploymentExceptionManager.class);
        if (dem != null) {
            if (dem.hasDeploymentFailed()) {
                ex = dem.getLastException();
            } else {
                ex = e;
            }
            if (appInfo != null) {
                dem.clearLastException(appInfo);
            }
        } else {
            ex = e;
        }
        if (ex instanceof OpenEJBException) {
            if (ex.getCause() instanceof ValidationException) {
                throw (ValidationException) ex.getCause();
            }
            throw (OpenEJBException) ex;
        }
        throw new OpenEJBException(ex);
    }
}
Also used : OpenEJBException(org.apache.openejb.OpenEJBException) AppModule(org.apache.openejb.config.AppModule) ValidationException(javax.validation.ValidationException) Properties(java.util.Properties) ConfigurationFactory(org.apache.openejb.config.ConfigurationFactory) WebModule(org.apache.openejb.config.WebModule) TreeMap(java.util.TreeMap) DeploymentModule(org.apache.openejb.config.DeploymentModule) File(java.io.File) Map(java.util.Map) TreeMap(java.util.TreeMap)

Example 24 with AppModule

use of org.apache.openejb.config.AppModule in project tomee by apache.

the class TomcatWebAppBuilder method checkHost.

/**
 * {@inheritDoc}
 */
@Override
public synchronized void checkHost(final StandardHost standardHost) {
    if (noHostCheck) {
        return;
    }
    if (standardHost.getAutoDeploy()) {
        // Undeploy any modified application
        for (final Iterator<Map.Entry<String, DeployedApplication>> iterator = deployedApps.entrySet().iterator(); iterator.hasNext(); ) {
            final Map.Entry<String, DeployedApplication> entry = iterator.next();
            final DeployedApplication deployedApplication = entry.getValue();
            if (deployedApplication.isModified()) {
                // TODO: for war use StandardContext.redeploy()
                if (deployedApplication.appInfo != null) {
                    // can happen with badly formed config
                    try {
                        getAssembler().destroyApplication(deployedApplication.appInfo.path);
                    } catch (final Exception e) {
                        logger.error("Unable to application " + deployedApplication.appInfo.path, e);
                    }
                } else {
                    logger.error("appinfo is null for " + deployedApplication);
                }
                iterator.remove();
            }
        }
        // Deploy new applications
        final File appBase = appBase(standardHost);
        final File[] files = appBase.listFiles();
        if (null != files) {
            for (File file : files) {
                if (file.getName().endsWith(".tmp")) {
                    // tomcat is uploading, see org.apache.catalina.manager.ManagerServlet.deploy(java.io.PrintWriter, org.apache.catalina.util.ContextName, java.lang.String, boolean, javax.servlet.http.HttpServletRequest, org.apache.tomcat.util.res.StringManager)
                    continue;
                }
                final String name = file.getName();
                // ignore war files
                if (name.toLowerCase().endsWith(".war") || isRoot(name) || name.equalsIgnoreCase("META-INF") || name.equalsIgnoreCase("WEB-INF")) {
                    continue;
                }
                // Simple fix for TOMEE-23
                if (name.toLowerCase().equals(".ds_store")) {
                    continue;
                }
                // ignore unpacked web apps
                if (file.isDirectory() && new File(file, "WEB-INF").exists()) {
                    continue;
                }
                // ignore unpacked apps where packed version is present (packed version is owner)
                if (file.isDirectory() && (new File(file.getParent(), file.getName() + ".ear").exists() || new File(file.getParent(), file.getName() + ".war").exists() || new File(file.getParent(), file.getName() + ".rar").exists())) {
                    continue;
                }
                // ignore already deployed apps
                if (isDeployed(file, standardHost)) {
                    continue;
                }
                final AppInfo appInfo;
                try {
                    file = file.getCanonicalFile().getAbsoluteFile();
                    final AppModule appModule = deploymentLoader.load(file, null);
                    // Ignore any standalone web modules - this happens when the app is unpaked and doesn't have a WEB-INF dir
                    if (appModule.getDeploymentModule().size() == 1 && appModule.getWebModules().size() == 1) {
                        final WebModule webModule = appModule.getWebModules().iterator().next();
                        if (file.getAbsolutePath().equals(webModule.getJarLocation())) {
                            continue;
                        }
                    }
                    // tell web modules to deploy using this host
                    for (final WebModule webModule : appModule.getWebModules()) {
                        webModule.setHost(standardHost.getName());
                    }
                    appInfo = configurationFactory.configureApplication(appModule);
                    if (file.isFile() && file.getName().toLowerCase().endsWith(".ear")) {
                        // this is to prevent any WARs inside the EARs being unpacked in a directory where they'll then be deployed again
                        appInfo.properties.setProperty("tomcat.unpackWar", "false");
                    }
                    // if this is an unpacked dir, tomcat will pick it up as a webapp so undeploy it first
                    if (file.isDirectory()) {
                        final ContainerBase context = (ContainerBase) standardHost.findChild("/" + name);
                        if (context != null) {
                            try {
                                standardHost.removeChild(context);
                            } catch (final Throwable t) {
                                logger.warning("Error undeploying wep application from Tomcat  " + name, t);
                            }
                            try {
                                context.destroy();
                            } catch (final Throwable t) {
                                logger.warning("Error destroying Tomcat web context " + name, t);
                            }
                        }
                    }
                    getAssembler().createApplication(appInfo);
                    deployedApps.put(file.getAbsolutePath(), new DeployedApplication(file, appInfo));
                } catch (final Throwable e) {
                    logger.warning("Error deploying application " + file.getAbsolutePath(), e);
                }
            }
        }
    }
}
Also used : ContainerBase(org.apache.catalina.core.ContainerBase) AppModule(org.apache.openejb.config.AppModule) WebModule(org.apache.openejb.config.WebModule) 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) AppInfo(org.apache.openejb.assembler.classic.AppInfo) WebAppInfo(org.apache.openejb.assembler.classic.WebAppInfo) EnvEntry(org.apache.openejb.jee.EnvEntry) JarEntry(java.util.jar.JarEntry) Map(java.util.Map) TreeMap(java.util.TreeMap) FilterMap(org.apache.tomcat.util.descriptor.web.FilterMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) File(java.io.File) JarFile(java.util.jar.JarFile)

Example 25 with AppModule

use of org.apache.openejb.config.AppModule in project tomee by apache.

the class TomcatWebAppBuilder method loadApplication.

/**
 * Creates an openejb {@link AppModule} instance
 * from given tomcat context.
 *
 * @param standardContext tomcat context instance
 * @return a openejb application module
 */
private AppModule loadApplication(final StandardContext standardContext) {
    // don't use getId since the app id shouldnt get the host (jndi)
    // final TomcatDeploymentLoader tomcatDeploymentLoader = new TomcatDeploymentLoader(standardContext, getId(standardContext));
    String id = standardContext.getName();
    if (id.startsWith("/")) {
        id = id.substring(1);
    }
    final TomcatDeploymentLoader tomcatDeploymentLoader = new TomcatDeploymentLoader(standardContext, id);
    final AppModule appModule;
    try {
        appModule = tomcatDeploymentLoader.load(Contexts.warPath(standardContext), configuredClasspath(standardContext));
    } catch (final OpenEJBException e) {
        throw new TomEERuntimeException(e);
    }
    // create the web module
    loadWebModule(appModule, standardContext);
    return appModule;
}
Also used : OpenEJBException(org.apache.openejb.OpenEJBException) AppModule(org.apache.openejb.config.AppModule)

Aggregations

AppModule (org.apache.openejb.config.AppModule)51 EjbModule (org.apache.openejb.config.EjbModule)41 EjbJar (org.apache.openejb.jee.EjbJar)40 StatelessBean (org.apache.openejb.jee.StatelessBean)18 InitialContext (javax.naming.InitialContext)15 ConfigurationFactory (org.apache.openejb.config.ConfigurationFactory)15 Properties (java.util.Properties)14 AppInfo (org.apache.openejb.assembler.classic.AppInfo)14 Assembler (org.apache.openejb.assembler.classic.Assembler)14 SingletonBean (org.apache.openejb.jee.SingletonBean)11 Test (org.junit.Test)10 WebModule (org.apache.openejb.config.WebModule)9 OpenejbJar (org.apache.openejb.jee.oejb3.OpenejbJar)8 File (java.io.File)7 IOException (java.io.IOException)6 List (java.util.List)6 OpenEJBException (org.apache.openejb.OpenEJBException)6 SecurityServiceInfo (org.apache.openejb.assembler.classic.SecurityServiceInfo)6 TransactionServiceInfo (org.apache.openejb.assembler.classic.TransactionServiceInfo)6 InitContextFactory (org.apache.openejb.core.ivm.naming.InitContextFactory)6