Search in sources :

Example 1 with Installer

use of org.apache.tomee.installer.Installer in project tomee by apache.

the class TomcatLoader method initialize.

public void initialize(final Properties properties) throws Exception {
    // better than static (we are sure we don't hit it too eagerly) and doesn't cost more since uses static block
    Warmup.warmup();
    // Install Log
    OptionsLog.install();
    // install conf/openejb.xml and conf/logging.properties files
    final String openejbWarDir = properties.getProperty("tomee.war");
    if (openejbWarDir != null) {
        final Paths paths = new Paths(new File(openejbWarDir));
        if (paths.verify()) {
            final Installer installer = new Installer(paths);
            if (installer.getStatus() != Status.INSTALLED) {
                installer.installConfigFiles(false);
            }
        }
    }
    // Not thread safe
    if (OpenEJB.isInitialized()) {
        ejbServer = SystemInstance.get().getComponent(EjbServer.class);
        return;
    }
    final File conf = new File(SystemInstance.get().getBase().getDirectory(), "conf");
    for (final String possibleTomeePaths : ConfigUtils.deducePaths("tomee.xml")) {
        final File tomeeXml = new File(conf, possibleTomeePaths);
        if (tomeeXml.exists()) {
            // use tomee.xml instead of openejb.xml
            SystemInstance.get().setProperty("openejb.configuration", tomeeXml.getAbsolutePath());
            SystemInstance.get().setProperty("openejb.configuration.class", Tomee.class.getName());
        }
    }
    // set tomcat pool
    try {
        // in embedded mode we can easily remove it so check we can use it before setting it
        final Class<?> creatorClass = TomcatLoader.class.getClassLoader().loadClass("org.apache.tomee.jdbc.TomEEDataSourceCreator");
        SystemInstance.get().setProperty(ConfigurationFactory.OPENEJB_JDBC_DATASOURCE_CREATOR, creatorClass.getName());
    } catch (final Throwable ignored) {
    // will use the defaul tone
    }
    // tomcat default behavior is webapp, simply keep it, it is overridable by system property too
    SystemInstance.get().setProperty("openejb.default.deployment-module", System.getProperty("openejb.default.deployment-module", "org.apache.openejb.config.WebModule"));
    // Those are set by TomcatHook, why re-set here???
    System.setProperty("openejb.home", SystemInstance.get().getHome().getDirectory().getAbsolutePath());
    System.setProperty("openejb.base", SystemInstance.get().getBase().getDirectory().getAbsolutePath());
    // Install tomcat thread context listener
    ThreadContext.addThreadContextListener(threadContextListener);
    // set ignorable libraries from a tomee property instead of using the standard openejb one
    // don't ignore standard openejb exclusions file
    final Class<?> scanner = Class.forName("org.apache.tomcat.util.scan.StandardJarScanFilter", true, TomcatLoader.class.getClassLoader());
    final Set<String> forcedScanJar = Set.class.cast(Reflections.get(scanner, null, "defaultScanSet"));
    final Set<String> forcedSkipJar = Set.class.cast(Reflections.get(scanner, null, "defaultSkipSet"));
    NewLoaderLogic.addAdditionalCustomFilter(forcedSkipJar.isEmpty() ? null : new TomcatToXbeanFilter(forcedSkipJar), forcedScanJar.isEmpty() ? null : new TomcatToXbeanFilter(forcedScanJar));
    // now we use the default tomcat filter so no need to do it
    // System.setProperty(Constants.SKIP_JARS_PROPERTY, Join.join(",", exclusions));
    // Install tomcat war builder
    TomcatWebAppBuilder tomcatWebAppBuilder = (TomcatWebAppBuilder) SystemInstance.get().getComponent(WebAppBuilder.class);
    if (tomcatWebAppBuilder == null) {
        tomcatWebAppBuilder = new TomcatWebAppBuilder();
        tomcatWebAppBuilder.start();
        SystemInstance.get().setComponent(WebAppBuilder.class, tomcatWebAppBuilder);
    }
    SystemInstance.get().setComponent(ParentClassLoaderFinder.class, tomcatWebAppBuilder);
    // set webapp deployer reusing tomcat deployer instead of our custom deployer for war
    SystemInstance.get().setComponent(WebAppDeployer.class, new TomcatWebappDeployer());
    // for compatibility purpose, no more used normally by our trunk
    SystemInstance.get().setComponent(WebDeploymentListeners.class, new WebDeploymentListeners());
    optionalService(properties, "org.apache.tomee.microprofile.TomEEMicroProfileService");
    // tomee webapp enricher
    final TomEEClassLoaderEnricher classLoaderEnricher = new TomEEClassLoaderEnricher();
    SystemInstance.get().setComponent(WebAppEnricher.class, classLoaderEnricher);
    // add common lib even in ear "lib" part (if the ear provides myfaces for instance)
    final ClassLoaderEnricher enricher = SystemInstance.get().getComponent(ClassLoaderEnricher.class);
    if (null != enricher) {
        for (final URL url : classLoaderEnricher.enrichment(null)) {
            // we rely on the fact we know what the impl does with null but that's fine
            enricher.addUrl(url);
        }
    }
    // optional services
    if (optionalService(properties, "org.apache.tomee.webservices.TomeeJaxRsService")) {
        // in embedded mode we use regex, in tomcat we use tomcat servlet mapping
        SystemInstance.get().setProperty("openejb.rest.wildcard", "*");
    }
    optionalService(properties, "org.apache.tomee.webservices.TomeeJaxWsService");
    // Start OpenEJB
    ejbServer = new EjbServer();
    SystemInstance.get().setComponent(EjbServer.class, ejbServer);
    OpenEJB.init(properties, new ServerFederation());
    TomcatJndiBuilder.importOpenEJBResourcesInTomcat(SystemInstance.get().getComponent(OpenEjbConfiguration.class).facilities.resources, TomcatHelper.getServer());
    final Properties ejbServerProps = new Properties();
    ejbServerProps.putAll(properties);
    for (final String prop : new String[] { "serializer", "gzip" }) {
        // ensure -Dejbd.xxx are read
        final String value = SystemInstance.get().getProperty("ejbd." + prop);
        if (value != null) {
            ejbServerProps.put(prop, value);
        }
    }
    ejbServerProps.setProperty("openejb.ejbd.uri", "http://127.0.0.1:8080/tomee/ejb");
    ejbServer.init(ejbServerProps);
    // Add our naming context listener to the server which registers all Tomcat resources with OpenEJB
    final StandardServer standardServer = TomcatHelper.getServer();
    final OpenEJBNamingContextListener namingContextListener = new OpenEJBNamingContextListener(standardServer);
    // Standard server has no state property, so we check global naming context to determine if server is started yet
    if (standardServer.getGlobalNamingContext() != null) {
        namingContextListener.start();
    }
    standardServer.addLifecycleListener(namingContextListener);
    // Process all applications already started.  This deploys EJBs, PersistenceUnits
    // and modifies JNDI ENC references to OpenEJB managed objects such as EJBs.
    processRunningApplications(tomcatWebAppBuilder, standardServer);
    final ClassLoader cl = TomcatLoader.class.getClassLoader();
    if (SystemInstance.get().getOptions().get("openejb.servicemanager.enabled", true)) {
        final String clazz = SystemInstance.get().getOptions().get("openejb.service.manager.class", (String) null);
        try {
            manager = clazz == null ? new TomEEServiceManager() : (ServiceManager) cl.loadClass(clazz).newInstance();
        } catch (final ClassNotFoundException cnfe) {
            LOGGER.severe("can't find the service manager " + clazz + ", the TomEE one will be used");
            manager = new TomEEServiceManager();
        }
        manager.init();
        manager.start(false);
    } else {
        // WS
        try {
            final ServerService cxfService = (ServerService) cl.loadClass("org.apache.openejb.server.cxf.CxfService").newInstance();
            cxfService.init(properties);
            cxfService.start();
            services.add(cxfService);
        } catch (final ClassNotFoundException ignored) {
        // no-op
        } catch (final Exception e) {
            LOGGER.log(Level.SEVERE, "Webservices failed to start", e);
        }
        // REST
        try {
            final ServerService restService = (ServerService) cl.loadClass("org.apache.openejb.server.cxf.rs.CxfRSService").newInstance();
            restService.init(properties);
            restService.start();
            services.add(restService);
        } catch (final ClassNotFoundException ignored) {
        // no-op
        } catch (final Exception e) {
            LOGGER.log(Level.SEVERE, "REST failed to start", e);
        }
    }
    if (SystemInstance.get().getOptions().get(TOMEE_NOSHUTDOWNHOOK_PROP, (String) null) != null) {
        final Field daemonField = Bootstrap.class.getDeclaredField("daemon");
        final boolean acc = daemonField.isAccessible();
        try {
            daemonField.setAccessible(true);
            final Bootstrap daemon = (Bootstrap) daemonField.get(null);
            if (daemon != null) {
                final Field catalinaField = Bootstrap.class.getDeclaredField("catalinaDaemon");
                final boolean catalinaAcc = catalinaField.isAccessible();
                catalinaField.setAccessible(true);
                try {
                    Catalina.class.getMethod("setUseShutdownHook", boolean.class).invoke(catalinaField.get(daemon), false);
                } finally {
                    catalinaField.setAccessible(catalinaAcc);
                }
            }
        } finally {
            daemonField.setAccessible(acc);
        }
    }
}
Also used : Tomee(org.apache.openejb.config.sys.Tomee) Installer(org.apache.tomee.installer.Installer) Properties(java.util.Properties) WebAppBuilder(org.apache.openejb.assembler.classic.WebAppBuilder) URL(java.net.URL) OpenEjbConfiguration(org.apache.openejb.assembler.classic.OpenEjbConfiguration) Field(java.lang.reflect.Field) StandardServer(org.apache.catalina.core.StandardServer) ServiceManager(org.apache.openejb.server.ServiceManager) ServerService(org.apache.openejb.server.ServerService) EjbServer(org.apache.openejb.server.ejbd.EjbServer) Bootstrap(org.apache.catalina.startup.Bootstrap) Paths(org.apache.tomee.installer.Paths) ServerFederation(org.apache.openejb.core.ServerFederation) ClassLoaderEnricher(org.apache.openejb.component.ClassLoaderEnricher) ServiceException(org.apache.openejb.server.ServiceException) TomcatWebappDeployer(org.apache.tomee.catalina.deployment.TomcatWebappDeployer) File(java.io.File) Catalina(org.apache.catalina.startup.Catalina)

Example 2 with Installer

use of org.apache.tomee.installer.Installer in project tomee by apache.

the class InstallerServlet method doPost.

@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    final ServletContext ctx = req.getServletContext();
    final String rootPath = ctx.getRealPath("/");
    final Runner installer = new Runner(new Installer(new Paths(new File(rootPath))));
    if (req.getParameter("catalinaBaseDir") != null && "".equals(req.getParameter("catalinaBaseDir").trim())) {
        installer.setCatalinaBaseDir(req.getParameter("catalinaBaseDir").trim());
    }
    if (req.getParameter("catalinaHome") != null && "".equals(req.getParameter("catalinaHome").trim())) {
        installer.setCatalinaHome(req.getParameter("catalinaHome").trim());
    }
    if (req.getParameter("serverXmlFile") != null && "".equals(req.getParameter("serverXmlFile").trim())) {
        installer.setServerXmlFile(req.getParameter("serverXmlFile").trim());
    }
    resp.setContentType("application/json");
    resp.getOutputStream().print(getJsonList(installer.execute(true)));
}
Also used : Installer(org.apache.tomee.installer.Installer) ServletContext(javax.servlet.ServletContext) Paths(org.apache.tomee.installer.Paths) File(java.io.File)

Example 3 with Installer

use of org.apache.tomee.installer.Installer in project tomee by apache.

the class InstallerServlet method doGet.

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    final ServletContext ctx = req.getServletContext();
    final String rootPath = ctx.getRealPath("/");
    final Runner installer = new Runner(new Installer(new Paths(new File(rootPath))));
    resp.setContentType("application/json");
    resp.getOutputStream().print(getJsonList(installer.execute(false)));
}
Also used : Installer(org.apache.tomee.installer.Installer) ServletContext(javax.servlet.ServletContext) Paths(org.apache.tomee.installer.Paths) File(java.io.File)

Example 4 with Installer

use of org.apache.tomee.installer.Installer in project tomee by apache.

the class TomEEWebappContainer method start.

@Override
public void start() throws LifecycleException {
    // see if TomEE is already running by checking the http port
    final int httpPort = configuration.getHttpPort();
    if (Setup.isRunning(configuration.getHost(), httpPort)) {
        logger.info(String.format("Tomcat found running on port %s", httpPort));
        return;
    }
    shutdown = true;
    final String s = File.separator;
    try {
        final File workingDirectory = new File(configuration.getDir());
        if (workingDirectory.exists()) {
            Files.assertDir(workingDirectory);
        } else {
            Files.mkdir(workingDirectory);
            Files.deleteOnExit(workingDirectory);
        }
        Files.readable(workingDirectory);
        Files.writable(workingDirectory);
        openejbHome = Setup.findHome(workingDirectory);
        Installer installer = null;
        if (openejbHome == null) {
            downloadTomcat(workingDirectory, configuration.getTomcatVersion(), configuration.getDir());
            openejbHome = Setup.findHome(workingDirectory);
            Files.deleteOnExit(openejbHome);
            final File webapp = new File(openejbHome, "webapps" + s + "tomee");
            Files.mkdir(webapp);
            downloadOpenEJBWebapp(webapp, configuration.getDir());
            System.setProperty("catalina.home", openejbHome.getAbsolutePath());
            System.setProperty("catalina.base", openejbHome.getAbsolutePath());
            System.setProperty("openejb.deploymentId.format", System.getProperty("openejb.deploymentId.format", "{appId}/{ejbJarId}/{ejbName}"));
            final Paths paths = new Paths(webapp);
            installer = new Installer(paths, true);
            if (!configuration.isUseInstallerServlet()) {
                installer.installAll();
            }
            wereOpenejbHomeSet = false;
        }
        Files.assertDir(openejbHome);
        Files.readable(openejbHome);
        Files.writable(openejbHome);
        Setup.configureServerXml(openejbHome, configuration);
        Setup.configureSystemProperties(openejbHome, configuration);
        Setup.exportProperties(openejbHome, configuration, true);
        final URL logging = Thread.currentThread().getContextClassLoader().getResource("default.remote.logging.properties");
        if (logging != null) {
            write(logging, new File(openejbHome, "conf" + s + "logging.properties"));
        }
        if (configuration.isRemoveUnusedWebapps()) {
            Setup.removeUselessWebapps(openejbHome, "tomee");
        }
        if (logger.isLoggable(Level.FINE)) {
            final Map<Object, Object> map = new TreeMap<>(System.getProperties());
            for (final Map.Entry<Object, Object> entry : map.entrySet()) {
                System.out.printf("%s = %s\n", entry.getKey(), entry.getValue());
            }
        }
        Setup.installArquillianBeanDiscoverer(openejbHome);
        if (!wereOpenejbHomeSet && configuration.isUseInstallerServlet()) {
            // instead of calling the Installer, let's just do like users do
            // call the servlet installer instead
            final String baseUrl = "http://" + configuration.getHost() + ":" + httpPort + "/tomee/installer";
            assert installer != null;
            installer.addTomEEAdminConfInTomcatUsers(true);
            final RemoteServer tmpContainer = new RemoteServer();
            tmpContainer.setPortStartup(httpPort);
            try {
                tmpContainer.start();
            } catch (final Exception e) {
                tmpContainer.destroy();
                throw e;
            }
            final URL url = new URL(baseUrl);
            logger.info("Calling TomEE Installer Servlet on " + url);
            for (int i = 0; i < Integer.getInteger("tomee.webapp.container.client.retries", 3); i++) {
                final URLConnection uc = url.openConnection();
                // dG9tZWU6dG9tZWU= --> Base64 of tomee:tomee
                final String authorizationString = "Basic dG9tZWU6dG9tZWU=";
                final int timeout = Integer.getInteger("tomee.webapp.container.client.timeout", 60000);
                uc.setConnectTimeout(timeout);
                uc.setReadTimeout(timeout);
                uc.setRequestProperty("Authorization", authorizationString);
                try {
                    final InputStream is = uc.getInputStream();
                    org.apache.openejb.loader.IO.slurp(is);
                    is.close();
                    break;
                } catch (final Exception e) {
                    logger.warning(e.getMessage());
                    Thread.sleep(1000);
                }
            }
            tmpContainer.stop();
            tmpContainer.getServer().waitFor();
        }
        container = new RemoteServer();
        container.setPortStartup(httpPort);
        container.start(Arrays.asList("-Dopenejb.system.apps=true", "-Dtomee.remote.support=true", "-Dorg.apache.openejb.servlet.filters=" + ArquillianFilterRunner.class.getName() + "=" + ServletMethodExecutor.ARQUILLIAN_SERVLET_MAPPING), "start", true);
        container.killOnExit();
    } catch (final Exception e) {
        if (null != container) {
            container.destroy();
        }
        throw new LifecycleException("Unable to start remote container on port: " + httpPort, e);
    }
}
Also used : ArquillianFilterRunner(org.apache.openejb.arquillian.common.ArquillianFilterRunner) LifecycleException(org.jboss.arquillian.container.spi.client.container.LifecycleException) Installer(org.apache.tomee.installer.Installer) InputStream(java.io.InputStream) TreeMap(java.util.TreeMap) URL(java.net.URL) LifecycleException(org.jboss.arquillian.container.spi.client.container.LifecycleException) IOException(java.io.IOException) URLConnection(java.net.URLConnection) Paths(org.apache.tomee.installer.Paths) File(java.io.File) TreeMap(java.util.TreeMap) Map(java.util.Map) RemoteServer(org.apache.openejb.config.RemoteServer)

Aggregations

File (java.io.File)4 Installer (org.apache.tomee.installer.Installer)4 Paths (org.apache.tomee.installer.Paths)4 URL (java.net.URL)2 ServletContext (javax.servlet.ServletContext)2 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 Field (java.lang.reflect.Field)1 URLConnection (java.net.URLConnection)1 Map (java.util.Map)1 Properties (java.util.Properties)1 TreeMap (java.util.TreeMap)1 StandardServer (org.apache.catalina.core.StandardServer)1 Bootstrap (org.apache.catalina.startup.Bootstrap)1 Catalina (org.apache.catalina.startup.Catalina)1 ArquillianFilterRunner (org.apache.openejb.arquillian.common.ArquillianFilterRunner)1 OpenEjbConfiguration (org.apache.openejb.assembler.classic.OpenEjbConfiguration)1 WebAppBuilder (org.apache.openejb.assembler.classic.WebAppBuilder)1 ClassLoaderEnricher (org.apache.openejb.component.ClassLoaderEnricher)1 RemoteServer (org.apache.openejb.config.RemoteServer)1