Search in sources :

Example 1 with ConfigurableBus

use of org.apache.meecrowave.cxf.ConfigurableBus in project meecrowave by apache.

the class Meecrowave method start.

public Meecrowave start() {
    final Map<String, String> systemPropsToRestore = new HashMap<>();
    if (configuration.getMeecrowaveProperties() != null && !"meecrowave.properties".equals(configuration.getMeecrowaveProperties())) {
        configuration.loadFrom(configuration.getMeecrowaveProperties());
    }
    if (configuration.isUseLog4j2JulLogManager()) {
        // /!\ don't move this line or add anything before without checking log setup
        System.setProperty("java.util.logging.manager", "org.apache.logging.log4j.jul.LogManager");
    }
    if (configuration.loggingGlobalSetup) {
        setSystemProperty(systemPropsToRestore, "log4j.shutdownHookEnabled", "false");
        setSystemProperty(systemPropsToRestore, "openwebbeans.logging.factory", Log4j2LoggerFactory.class.getName());
        setSystemProperty(systemPropsToRestore, "org.apache.cxf.Logger", Log4j2Logger.class.getName());
        setSystemProperty(systemPropsToRestore, "org.apache.tomcat.Logger", Log4j2Log.class.getName());
        postTask = () -> {
            new Log4j2Shutdown().shutodwn();
            systemPropsToRestore.entrySet().forEach(entry -> {
                if (entry.getValue() == null) {
                    System.clearProperty(entry.getKey());
                } else {
                    System.setProperty(entry.getKey(), entry.getValue());
                }
            });
        };
    }
    setupJmx(configuration.isTomcatNoJmx());
    clearCatalinaSystemProperties = System.getProperty("catalina.base") == null && System.getProperty("catalina.home") == null;
    if (configuration.quickSession) {
        tomcat = new TomcatWithFastSessionIDs();
    } else {
        tomcat = new InternalTomcat();
    }
    {
        // setup
        base = new File(newBaseDir());
        final File conf = createDirectory(base, "conf");
        createDirectory(base, "lib");
        createDirectory(base, "logs");
        createDirectory(base, "temp");
        createDirectory(base, "work");
        createDirectory(base, "webapps");
        synchronize(conf, configuration.conf);
    }
    final Properties props = configuration.properties;
    StrSubstitutor substitutor = null;
    for (final String s : props.stringPropertyNames()) {
        final String v = props.getProperty(s);
        if (v != null && v.contains("${")) {
            if (substitutor == null) {
                final Map<String, String> placeHolders = new HashMap<>();
                placeHolders.put("meecrowave.embedded.http", Integer.toString(configuration.httpPort));
                placeHolders.put("meecrowave.embedded.https", Integer.toString(configuration.httpsPort));
                placeHolders.put("meecrowave.embedded.stop", Integer.toString(configuration.stopPort));
                substitutor = new StrSubstitutor(placeHolders);
            }
            props.put(s, substitutor.replace(v));
        }
    }
    final File conf = new File(base, "conf");
    final File webapps = new File(base, "webapps");
    tomcat.setBaseDir(base.getAbsolutePath());
    tomcat.setHostname(configuration.host);
    final boolean initialized;
    if (configuration.serverXml != null) {
        final File file = new File(conf, "server.xml");
        if (!file.equals(configuration.serverXml)) {
            try (final InputStream is = new FileInputStream(configuration.serverXml);
                final FileOutputStream fos = new FileOutputStream(file)) {
                IO.copy(is, fos);
            } catch (final IOException e) {
                throw new IllegalStateException(e);
            }
        }
        // respect config (host/port) of the Configuration
        final QuickServerXmlParser ports = QuickServerXmlParser.parse(file);
        if (configuration.keepServerXmlAsThis) {
            configuration.httpPort = Integer.parseInt(ports.http());
            configuration.stopPort = Integer.parseInt(ports.stop());
        } else {
            final Map<String, String> replacements = new HashMap<>();
            replacements.put(ports.http(), String.valueOf(configuration.httpPort));
            replacements.put(ports.https(), String.valueOf(configuration.httpsPort));
            replacements.put(ports.stop(), String.valueOf(configuration.stopPort));
            String serverXmlContent;
            try (final InputStream stream = new FileInputStream(file)) {
                serverXmlContent = IO.toString(stream);
                for (final Map.Entry<String, String> pair : replacements.entrySet()) {
                    serverXmlContent = serverXmlContent.replace(pair.getKey(), pair.getValue());
                }
            } catch (final IOException e) {
                throw new IllegalStateException(e);
            }
            try (final OutputStream os = new FileOutputStream(file)) {
                os.write(serverXmlContent.getBytes(StandardCharsets.UTF_8));
            } catch (final IOException e) {
                throw new IllegalStateException(e);
            }
        }
        tomcat.server(createServer(file.getAbsolutePath()));
        initialized = true;
    } else {
        tomcat.getServer().setPort(configuration.stopPort);
        initialized = false;
    }
    ofNullable(configuration.getSharedLibraries()).map(File::new).filter(File::isDirectory).ifPresent(libRoot -> {
        final Collection<URL> libs = new ArrayList<>();
        try {
            libs.add(libRoot.toURI().toURL());
        } catch (final MalformedURLException e) {
            throw new IllegalStateException(e);
        }
        libs.addAll(ofNullable(libRoot.listFiles((dir, name) -> name.endsWith(".jar") || name.endsWith(".zip"))).map(Stream::of).map(s -> s.map(f -> {
            try {
                return f.toURI().toURL();
            } catch (final MalformedURLException e) {
                throw new IllegalStateException(e);
            }
        }).collect(toList())).orElse(emptyList()));
        tomcat.getServer().setParentClassLoader(new MeecrowaveContainerLoader(libs.toArray(new URL[libs.size()]), Thread.currentThread().getContextClassLoader()));
    });
    if (!initialized) {
        tomcat.setHostname(configuration.host);
        tomcat.getEngine().setDefaultHost(configuration.host);
        final StandardHost host = new StandardHost();
        host.setName(configuration.host);
        host.setAppBase(webapps.getAbsolutePath());
        // forced for now cause OWB doesn't support war:file:// urls
        host.setUnpackWARs(true);
        try {
            host.setWorkDir(new File(base, "work").getCanonicalPath());
        } catch (final IOException e) {
            host.setWorkDir(new File(base, "work").getAbsolutePath());
        }
        tomcat.setHost(host);
    }
    ofNullable(configuration.getTomcatAccessLogPattern()).ifPresent(pattern -> tomcat.getHost().getPipeline().addValve(new LoggingAccessLogPattern(pattern)));
    if (configuration.realm != null) {
        tomcat.getEngine().setRealm(configuration.realm);
    }
    if (tomcat.getRawConnector() == null && !configuration.skipHttp) {
        final Connector connector = createConnector();
        connector.setPort(configuration.httpPort);
        if (connector.getAttribute("connectionTimeout") == null) {
            connector.setAttribute("connectionTimeout", "3000");
        }
        tomcat.getService().addConnector(connector);
        tomcat.setConnector(connector);
    }
    // create https connector
    if (configuration.ssl) {
        final Connector httpsConnector = createConnector();
        httpsConnector.setPort(configuration.httpsPort);
        httpsConnector.setSecure(true);
        httpsConnector.setScheme("https");
        httpsConnector.setProperty("SSLEnabled", "true");
        if (configuration.sslProtocol != null) {
            configuration.property("connector.sslhostconfig.sslProtocol", configuration.sslProtocol);
        }
        if (configuration.properties.getProperty("connector.sslhostconfig.hostName") != null) {
            httpsConnector.setAttribute("defaultSSLHostConfigName", configuration.properties.getProperty("connector.sslhostconfig.hostName"));
        }
        if (configuration.keystoreFile != null) {
            configuration.property("connector.sslhostconfig.certificateKeystoreFile", configuration.keystoreFile);
        }
        if (configuration.keystorePass != null) {
            configuration.property("connector.sslhostconfig.certificateKeystorePassword", configuration.keystorePass);
        }
        configuration.property("connector.sslhostconfig.certificateKeystoreType", configuration.keystoreType);
        if (configuration.clientAuth != null) {
            httpsConnector.setAttribute("clientAuth", configuration.clientAuth);
        }
        if (configuration.keyAlias != null) {
            configuration.property("connector.sslhostconfig.certificateKeyAlias", configuration.keyAlias);
        }
        if (configuration.http2) {
            httpsConnector.addUpgradeProtocol(new Http2Protocol());
        }
        final List<SSLHostConfig> buildSslHostConfig = buildSslHostConfig();
        buildSslHostConfig.forEach(sslHostConf -> {
            if (isCertificateFromClasspath(sslHostConf.getCertificateKeystoreFile())) {
                copyCertificateToConfDir(sslHostConf.getCertificateKeystoreFile());
                sslHostConf.setCertificateKeystoreFile(base.getAbsolutePath() + "/conf/" + sslHostConf.getCertificateKeystoreFile());
            }
            if (isCertificateFromClasspath(sslHostConf.getCertificateKeyFile())) {
                copyCertificateToConfDir(sslHostConf.getCertificateKeyFile());
                sslHostConf.setCertificateKeyFile(base.getAbsolutePath() + "/conf/" + sslHostConf.getCertificateKeyFile());
                copyCertificateToConfDir(sslHostConf.getCertificateFile());
                sslHostConf.setCertificateFile(base.getAbsolutePath() + "/conf/" + sslHostConf.getCertificateFile());
            }
            if (isCertificateFromClasspath(sslHostConf.getTruststoreFile())) {
                copyCertificateToConfDir(sslHostConf.getTruststoreFile());
                sslHostConf.setTruststoreFile(base.getAbsolutePath() + "/conf/" + sslHostConf.getTruststoreFile());
            }
            if (isCertificateFromClasspath(sslHostConf.getCertificateChainFile())) {
                copyCertificateToConfDir(sslHostConf.getCertificateChainFile());
                sslHostConf.setCertificateChainFile(base.getAbsolutePath() + "/conf/" + sslHostConf.getCertificateChainFile());
            }
        });
        buildSslHostConfig.forEach(httpsConnector::addSslHostConfig);
        if (configuration.defaultSSLHostConfigName != null) {
            httpsConnector.setAttribute("defaultSSLHostConfigName", configuration.defaultSSLHostConfigName);
        }
        tomcat.getService().addConnector(httpsConnector);
        if (configuration.skipHttp) {
            tomcat.setConnector(httpsConnector);
        }
    }
    for (final Connector c : configuration.connectors) {
        tomcat.getService().addConnector(c);
    }
    if (!configuration.skipHttp && !configuration.ssl && !configuration.connectors.isEmpty()) {
        tomcat.setConnector(configuration.connectors.iterator().next());
    }
    if (configuration.users != null) {
        for (final Map.Entry<String, String> user : configuration.users.entrySet()) {
            tomcat.addUser(user.getKey(), user.getValue());
        }
    }
    if (configuration.roles != null) {
        for (final Map.Entry<String, String> user : configuration.roles.entrySet()) {
            for (final String role : user.getValue().split(" *, *")) {
                tomcat.addRole(user.getKey(), role);
            }
        }
    }
    StreamSupport.stream(ServiceLoader.load(Meecrowave.InstanceCustomizer.class).spliterator(), false).forEach(c -> c.accept(tomcat));
    configuration.instanceCustomizers.forEach(c -> c.accept(tomcat));
    beforeStart();
    if (configuration.initializeClientBus && BusFactory.getDefaultBus(false) == null) {
        clientBus = new ConfigurableBus();
        clientBus.initProviders(configuration, ofNullable(Thread.currentThread().getContextClassLoader()).orElseGet(ClassLoader::getSystemClassLoader));
        clientBus.addClientLifecycleListener();
    }
    try {
        if (!initialized) {
            tomcat.init();
        }
        tomcat.getHost().addLifecycleListener(event -> {
            if (!Host.class.isInstance(event.getSource())) {
                return;
            }
            broadcastHostEvent(event.getType(), Host.class.cast(event.getSource()));
        });
        tomcat.start();
    } catch (final LifecycleException e) {
        throw new IllegalStateException(e);
    }
    ofNullable(configuration.getPidFile()).ifPresent(pidFile -> {
        if (pidFile.getParentFile() != null && !pidFile.getParentFile().isDirectory() && !pidFile.getParentFile().mkdirs()) {
            throw new IllegalArgumentException("Can't create " + pidFile);
        }
        final String pid = ManagementFactory.getRuntimeMXBean().getName();
        final int at = pid.indexOf('@');
        try (final Writer w = new FileWriter(pidFile)) {
            w.write(at > 0 ? pid.substring(0, at) : pid);
        } catch (final IOException e) {
            throw new IllegalStateException("Can't write the pid in " + pid, e);
        }
    });
    if (configuration.isUseShutdownHook()) {
        hook = new Thread(() -> {
            // prevent close to remove the hook which would throw an exception
            hook = null;
            close();
        }, "meecrowave-stop-hook");
        Runtime.getRuntime().addShutdownHook(hook);
    }
    return this;
}
Also used : MeecrowaveClientLifecycleListener(org.apache.meecrowave.cxf.MeecrowaveClientLifecycleListener) ProvidedLoader(org.apache.meecrowave.tomcat.ProvidedLoader) SecurityCollection(org.apache.tomcat.util.descriptor.web.SecurityCollection) SecretKeySpec(javax.crypto.spec.SecretKeySpec) ServerSocket(java.net.ServerSocket) URLClassLoader(java.net.URLClassLoader) Host(org.apache.catalina.Host) StopListening(org.apache.meecrowave.api.StopListening) Map(java.util.Map) SAXParser(javax.xml.parsers.SAXParser) Path(java.nio.file.Path) Log4j2Log(org.apache.meecrowave.logging.tomcat.Log4j2Log) LifecycleException(org.apache.catalina.LifecycleException) Set(java.util.Set) CDI(javax.enterprise.inject.spi.CDI) CDIInstanceManager(org.apache.meecrowave.tomcat.CDIInstanceManager) StandardCharsets(java.nio.charset.StandardCharsets) WebBeansContext(org.apache.webbeans.config.WebBeansContext) BufferStrategy(org.apache.johnzon.core.BufferStrategy) ResourceFinder(org.apache.xbean.finder.ResourceFinder) Stream(java.util.stream.Stream) ConfigurableBus(org.apache.meecrowave.cxf.ConfigurableBus) JarScanFilter(org.apache.tomcat.JarScanFilter) TomcatAutoInitializer(org.apache.meecrowave.tomcat.TomcatAutoInitializer) Log4j2Logger(org.apache.meecrowave.logging.jul.Log4j2Logger) Connector(org.apache.catalina.connector.Connector) StandardHost(org.apache.catalina.core.StandardHost) AnnotatedType(javax.enterprise.inject.spi.AnnotatedType) StandardCopyOption(java.nio.file.StandardCopyOption) ArrayList(java.util.ArrayList) CreationalContext(javax.enterprise.context.spi.CreationalContext) StrLookup(org.apache.commons.text.StrLookup) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) StreamSupport(java.util.stream.StreamSupport) SSLHostConfig(org.apache.tomcat.util.net.SSLHostConfig) ManagementFactory(java.lang.management.ManagementFactory) Service(org.apache.catalina.Service) Properties(java.util.Properties) LogFacade(org.apache.meecrowave.logging.tomcat.LogFacade) Files(java.nio.file.Files) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) ValueTransformer(org.apache.meecrowave.service.ValueTransformer) Field(java.lang.reflect.Field) File(java.io.File) ObjectRecipe(org.apache.xbean.recipe.ObjectRecipe) DefaultHandler(org.xml.sax.helpers.DefaultHandler) TreeMap(java.util.TreeMap) Paths(java.nio.file.Paths) CliOption(org.apache.meecrowave.runner.cli.CliOption) BeanManager(javax.enterprise.inject.spi.BeanManager) MeecrowaveContextConfig(org.apache.catalina.startup.MeecrowaveContextConfig) URL(java.net.URL) Lifecycle(org.apache.catalina.Lifecycle) Catalina(org.apache.catalina.startup.Catalina) OWBJarScanner(org.apache.meecrowave.tomcat.OWBJarScanner) Http2Protocol(org.apache.coyote.http2.Http2Protocol) IO(org.apache.meecrowave.io.IO) LifecycleState(org.apache.catalina.LifecycleState) Collectors.toSet(java.util.stream.Collectors.toSet) Server(org.apache.catalina.Server) StartListening(org.apache.meecrowave.api.StartListening) Collections.emptyList(java.util.Collections.emptyList) Collection(java.util.Collection) ServiceLoader(java.util.ServiceLoader) FileNotFoundException(java.io.FileNotFoundException) Objects(java.util.Objects) Base64(java.util.Base64) List(java.util.List) Realm(org.apache.catalina.Realm) SAXException(org.xml.sax.SAXException) Writer(java.io.Writer) StandardContext(org.apache.catalina.core.StandardContext) NoDescriptorRegistry(org.apache.meecrowave.tomcat.NoDescriptorRegistry) OWBAutoSetup(org.apache.meecrowave.openwebbeans.OWBAutoSetup) LoginConfig(org.apache.tomcat.util.descriptor.web.LoginConfig) SAXParserFactory(javax.xml.parsers.SAXParserFactory) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Cipher(javax.crypto.Cipher) BiPredicate(java.util.function.BiPredicate) ServletContainerInitializer(javax.servlet.ServletContainerInitializer) Log4j2Shutdown(org.apache.meecrowave.logging.log4j2.Log4j2Shutdown) Attributes(org.xml.sax.Attributes) ROOT(java.util.Locale.ROOT) InjectionTarget(javax.enterprise.inject.spi.InjectionTarget) Manager(org.apache.catalina.Manager) CxfCdiAutoSetup(org.apache.meecrowave.cxf.CxfCdiAutoSetup) LinkedList(java.util.LinkedList) OutputStream(java.io.OutputStream) Collections.emptySet(java.util.Collections.emptySet) MalformedURLException(java.net.MalformedURLException) ManagerBase(org.apache.catalina.session.ManagerBase) Log4j2LoggerFactory(org.apache.meecrowave.logging.openwebbeans.Log4j2LoggerFactory) Optional.ofNullable(java.util.Optional.ofNullable) LoggingAccessLogPattern(org.apache.meecrowave.tomcat.LoggingAccessLogPattern) FileWriter(java.io.FileWriter) Globals(org.apache.catalina.Globals) StandardManager(org.apache.catalina.session.StandardManager) FileInputStream(java.io.FileInputStream) Context(org.apache.catalina.Context) StrSubstitutor(org.apache.commons.text.StrSubstitutor) Registry(org.apache.tomcat.util.modeler.Registry) Consumer(java.util.function.Consumer) Tomcat(org.apache.catalina.startup.Tomcat) Collectors.toList(java.util.stream.Collectors.toList) BusFactory(org.apache.cxf.BusFactory) InputStream(java.io.InputStream) LoggingAccessLogPattern(org.apache.meecrowave.tomcat.LoggingAccessLogPattern) Connector(org.apache.catalina.connector.Connector) Log4j2Logger(org.apache.meecrowave.logging.jul.Log4j2Logger) MalformedURLException(java.net.MalformedURLException) Log4j2LoggerFactory(org.apache.meecrowave.logging.openwebbeans.Log4j2LoggerFactory) HashMap(java.util.HashMap) FileOutputStream(java.io.FileOutputStream) OutputStream(java.io.OutputStream) FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) Properties(java.util.Properties) ConfigurableBus(org.apache.meecrowave.cxf.ConfigurableBus) URL(java.net.URL) Log4j2Shutdown(org.apache.meecrowave.logging.log4j2.Log4j2Shutdown) Http2Protocol(org.apache.coyote.http2.Http2Protocol) LifecycleException(org.apache.catalina.LifecycleException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Host(org.apache.catalina.Host) StandardHost(org.apache.catalina.core.StandardHost) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) StrSubstitutor(org.apache.commons.text.StrSubstitutor) Log4j2Log(org.apache.meecrowave.logging.tomcat.Log4j2Log) StandardHost(org.apache.catalina.core.StandardHost) FileOutputStream(java.io.FileOutputStream) File(java.io.File) Map(java.util.Map) TreeMap(java.util.TreeMap) HashMap(java.util.HashMap) SSLHostConfig(org.apache.tomcat.util.net.SSLHostConfig) Writer(java.io.Writer) FileWriter(java.io.FileWriter)

Aggregations

File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 FileNotFoundException (java.io.FileNotFoundException)1 FileOutputStream (java.io.FileOutputStream)1 FileWriter (java.io.FileWriter)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 Writer (java.io.Writer)1 ManagementFactory (java.lang.management.ManagementFactory)1 Field (java.lang.reflect.Field)1 MalformedURLException (java.net.MalformedURLException)1 ServerSocket (java.net.ServerSocket)1 URL (java.net.URL)1 URLClassLoader (java.net.URLClassLoader)1 StandardCharsets (java.nio.charset.StandardCharsets)1 Files (java.nio.file.Files)1 Path (java.nio.file.Path)1 Paths (java.nio.file.Paths)1 StandardCopyOption (java.nio.file.StandardCopyOption)1