Search in sources :

Example 1 with StandardServer

use of org.apache.catalina.core.StandardServer in project tomcat by apache.

the class StandardServerSF method storeChildren.

/**
     * Store the specified server element children.
     *
     * @param aWriter Current output writer
     * @param indent Indentation level
     * @param aObject Server to store
     * @param parentDesc The element description
     * @throws Exception Configuration storing error
     */
@Override
public void storeChildren(PrintWriter aWriter, int indent, Object aObject, StoreDescription parentDesc) throws Exception {
    if (aObject instanceof StandardServer) {
        StandardServer server = (StandardServer) aObject;
        // Store nested <Listener> elements
        LifecycleListener[] listeners = ((Lifecycle) server).findLifecycleListeners();
        storeElementArray(aWriter, indent, listeners);
        /*LifecycleListener listener = null;
            for (int i = 0; listener == null && i < listeners.length; i++)
                if (listeners[i] instanceof ServerLifecycleListener)
                    listener = listeners[i];
            if (listener != null) {
                StoreDescription elementDesc = getRegistry()
                        .findDescription(
                                StandardServer.class.getName()
                                        + ".[ServerLifecycleListener]");
                if (elementDesc != null) {
                    elementDesc.getStoreFactory().store(aWriter, indent,
                            listener);
                }
            }*/
        // Store nested <GlobalNamingResources> element
        NamingResourcesImpl globalNamingResources = server.getGlobalNamingResources();
        StoreDescription elementDesc = getRegistry().findDescription(NamingResourcesImpl.class.getName() + ".[GlobalNamingResources]");
        if (elementDesc != null) {
            elementDesc.getStoreFactory().store(aWriter, indent, globalNamingResources);
        }
        // Store nested <Service> elements
        Service[] services = server.findServices();
        storeElementArray(aWriter, indent, services);
    }
}
Also used : StandardServer(org.apache.catalina.core.StandardServer) Lifecycle(org.apache.catalina.Lifecycle) NamingResourcesImpl(org.apache.catalina.deploy.NamingResourcesImpl) Service(org.apache.catalina.Service) LifecycleListener(org.apache.catalina.LifecycleListener)

Example 2 with StandardServer

use of org.apache.catalina.core.StandardServer in project tomcat by apache.

the class TomcatBaseTest method setUp.

@Before
@Override
public void setUp() throws Exception {
    super.setUp();
    // Trigger loading of catalina.properties
    CatalinaProperties.getProperty("foo");
    File appBase = new File(getTemporaryDirectory(), "webapps");
    if (!appBase.exists() && !appBase.mkdir()) {
        fail("Unable to create appBase for test");
    }
    tomcat = new TomcatWithFastSessionIDs();
    String protocol = getProtocol();
    Connector connector = new Connector(protocol);
    // Listen only on localhost
    connector.setAttribute("address", InetAddress.getByName("localhost").getHostAddress());
    // Use random free port
    connector.setPort(0);
    // Mainly set to reduce timeouts during async tests
    connector.setAttribute("connectionTimeout", "3000");
    tomcat.getService().addConnector(connector);
    tomcat.setConnector(connector);
    // Add AprLifecycleListener if we are using the Apr connector
    if (protocol.contains("Apr")) {
        StandardServer server = (StandardServer) tomcat.getServer();
        AprLifecycleListener listener = new AprLifecycleListener();
        listener.setSSLRandomSeed("/dev/urandom");
        server.addLifecycleListener(listener);
        connector.setAttribute("pollerThreadCount", Integer.valueOf(1));
    }
    File catalinaBase = getTemporaryDirectory();
    tomcat.setBaseDir(catalinaBase.getAbsolutePath());
    tomcat.getHost().setAppBase(appBase.getAbsolutePath());
    accessLogEnabled = Boolean.parseBoolean(System.getProperty("tomcat.test.accesslog", "false"));
    if (accessLogEnabled) {
        String accessLogDirectory = System.getProperty("tomcat.test.reports");
        if (accessLogDirectory == null) {
            accessLogDirectory = new File(getBuildDirectory(), "logs").toString();
        }
        AccessLogValve alv = new AccessLogValve();
        alv.setDirectory(accessLogDirectory);
        alv.setPattern("%h %l %u %t \"%r\" %s %b %I %D");
        tomcat.getHost().getPipeline().addValve(alv);
    }
    // Cannot delete the whole tempDir, because logs are there,
    // but delete known subdirectories of it.
    addDeleteOnTearDown(new File(catalinaBase, "webapps"));
    addDeleteOnTearDown(new File(catalinaBase, "work"));
}
Also used : Connector(org.apache.catalina.connector.Connector) AprLifecycleListener(org.apache.catalina.core.AprLifecycleListener) StandardServer(org.apache.catalina.core.StandardServer) File(java.io.File) AccessLogValve(org.apache.catalina.valves.AccessLogValve) Before(org.junit.Before)

Example 3 with StandardServer

use of org.apache.catalina.core.StandardServer in project tomcat by apache.

the class TesterSupport method initSsl.

protected static void initSsl(Tomcat tomcat, String keystore, String keystorePass, String keyPass) {
    String protocol = tomcat.getConnector().getProtocolHandlerClassName();
    if (protocol.indexOf("Apr") == -1) {
        Connector connector = tomcat.getConnector();
        String sslImplementation = System.getProperty("tomcat.test.sslImplementation");
        if (sslImplementation != null && !"${test.sslImplementation}".equals(sslImplementation)) {
            StandardServer server = (StandardServer) tomcat.getServer();
            AprLifecycleListener listener = new AprLifecycleListener();
            listener.setSSLRandomSeed("/dev/urandom");
            server.addLifecycleListener(listener);
            tomcat.getConnector().setAttribute("sslImplementationName", sslImplementation);
        }
        connector.setProperty("sslProtocol", "tls");
        File keystoreFile = new File("test/org/apache/tomcat/util/net/" + keystore);
        connector.setAttribute("keystoreFile", keystoreFile.getAbsolutePath());
        File truststoreFile = new File("test/org/apache/tomcat/util/net/ca.jks");
        connector.setAttribute("truststoreFile", truststoreFile.getAbsolutePath());
        if (keystorePass != null) {
            connector.setAttribute("keystorePass", keystorePass);
        }
        if (keyPass != null) {
            connector.setAttribute("keyPass", keyPass);
        }
    } else {
        File keystoreFile = new File("test/org/apache/tomcat/util/net/localhost-cert.pem");
        tomcat.getConnector().setAttribute("SSLCertificateFile", keystoreFile.getAbsolutePath());
        keystoreFile = new File("test/org/apache/tomcat/util/net/localhost-key.pem");
        tomcat.getConnector().setAttribute("SSLCertificateKeyFile", keystoreFile.getAbsolutePath());
    }
    tomcat.getConnector().setSecure(true);
    tomcat.getConnector().setProperty("SSLEnabled", "true");
}
Also used : Connector(org.apache.catalina.connector.Connector) AprLifecycleListener(org.apache.catalina.core.AprLifecycleListener) StandardServer(org.apache.catalina.core.StandardServer) File(java.io.File)

Example 4 with StandardServer

use of org.apache.catalina.core.StandardServer in project tomee by apache.

the class OpenEJBListener method lifecycleEvent.

@Override
public void lifecycleEvent(final LifecycleEvent event) {
    // only install once
    if (listenerInstalled || !Lifecycle.AFTER_INIT_EVENT.equals(event.getType())) {
        return;
    }
    try {
        File webappDir = findOpenEjbWar();
        if (webappDir == null && event.getSource() instanceof StandardServer) {
            final StandardServer server = (StandardServer) event.getSource();
            webappDir = tryToFindAndExtractWar(server);
            if (webappDir != null) {
                // we are using webapp startup
                final File exploded = extractDirectory(webappDir);
                if (exploded != null) {
                    extract(webappDir, exploded);
                }
                webappDir = exploded;
                TomcatHelper.setServer(server);
            }
        }
        if (webappDir != null) {
            LOGGER.info("found the tomee webapp on " + webappDir.getPath());
            final Properties properties = new Properties();
            properties.setProperty("tomee.war", webappDir.getAbsolutePath());
            properties.setProperty("openejb.embedder.source", OpenEJBListener.class.getSimpleName());
            TomcatEmbedder.embed(properties, StandardServer.class.getClassLoader());
            listenerInstalled = true;
        } else if (logWebappNotFound) {
            LOGGER.info("tomee webapp not found from the listener, will try from the webapp if exists");
            logWebappNotFound = false;
        }
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, "TomEE Listener can't start OpenEJB", e);
    // e.printStackTrace(System.err);
    }
}
Also used : StandardServer(org.apache.catalina.core.StandardServer) Properties(java.util.Properties) JarFile(java.util.jar.JarFile) File(java.io.File) IOException(java.io.IOException)

Example 5 with StandardServer

use of org.apache.catalina.core.StandardServer 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(new TomcatThreadContextListener());
    // 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());
    // 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)

Aggregations

StandardServer (org.apache.catalina.core.StandardServer)11 File (java.io.File)5 Properties (java.util.Properties)3 Service (org.apache.catalina.Service)3 IOException (java.io.IOException)2 Method (java.lang.reflect.Method)2 URL (java.net.URL)2 Connector (org.apache.catalina.connector.Connector)2 AprLifecycleListener (org.apache.catalina.core.AprLifecycleListener)2 StandardHost (org.apache.catalina.core.StandardHost)2 Field (java.lang.reflect.Field)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 MalformedURLException (java.net.MalformedURLException)1 URLClassLoader (java.net.URLClassLoader)1 ArrayList (java.util.ArrayList)1 JarFile (java.util.jar.JarFile)1 MBeanServer (javax.management.MBeanServer)1 ObjectName (javax.management.ObjectName)1 Container (org.apache.catalina.Container)1 Engine (org.apache.catalina.Engine)1