Search in sources :

Example 1 with Substitutor

use of org.apache.meecrowave.lang.Substitutor in project meecrowave by apache.

the class Configuration method loadFromProperties.

public void loadFromProperties(final Properties config) {
    // filtering properties with system properties or themself
    final Substitutor strSubstitutor = new Substitutor(emptyMap()) {

        @Override
        public String getOrDefault(final String key, final String or) {
            final String property = System.getProperty(key);
            return property == null ? config.getProperty(key, or) : or;
        }
    };
    final Meecrowave.ValueTransformers transformers = getExtension(Meecrowave.ValueTransformers.class);
    for (final String key : config.stringPropertyNames()) {
        final String val = config.getProperty(key);
        if (val == null || val.trim().isEmpty()) {
            continue;
        }
        final String newVal = transformers.apply(strSubstitutor.replace(config.getProperty(key)));
        if (!val.equals(newVal)) {
            config.setProperty(key, newVal);
        }
    }
    for (final Field field : Configuration.class.getDeclaredFields()) {
        final CliOption annotation = field.getAnnotation(CliOption.class);
        if (annotation == null) {
            continue;
        }
        final String name = field.getName();
        Stream.of(Stream.of(annotation.name()), Stream.of(annotation.alias())).flatMap(a -> a).map(config::getProperty).filter(Objects::nonNull).findAny().ifPresent(val -> {
            final Object toSet;
            if (field.getType() == String.class) {
                toSet = val;
            } else if (field.getType() == int.class) {
                if ("httpPort".equals(name) && "-1".equals(val)) {
                    // special case in case of random port
                    try (final ServerSocket serverSocket = new ServerSocket(0)) {
                        setHttpPort(serverSocket.getLocalPort());
                    } catch (final IOException e) {
                        throw new IllegalStateException(e);
                    }
                    toSet = null;
                } else {
                    toSet = Integer.parseInt(val);
                }
            } else if (field.getType() == boolean.class) {
                toSet = Boolean.parseBoolean(val);
            } else if (field.getType() == File.class) {
                toSet = new File(val);
            } else if (field.getType() == long.class) {
                toSet = Long.parseLong(val);
            } else {
                toSet = null;
            }
            if (toSet == null) {
                // handled elsewhere
                return;
            }
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            try {
                field.set(this, toSet);
            } catch (final IllegalAccessException e) {
                throw new IllegalStateException(e);
            }
        });
    }
    // not trivial types
    for (final String prop : config.stringPropertyNames()) {
        if (prop.startsWith("properties.")) {
            getProperties().setProperty(prop.substring("properties.".length()), config.getProperty(prop));
        } else if (prop.startsWith("users.")) {
            if (users == null) {
                users = new HashMap<>();
            }
            users.put(prop.substring("users.".length()), config.getProperty(prop));
        } else if (prop.startsWith("roles.")) {
            if (roles == null) {
                roles = new HashMap<>();
            }
            roles.put(prop.substring("roles.".length()), config.getProperty(prop));
        } else if (prop.startsWith("cxf.servlet.params.")) {
            if (cxfServletParams == null) {
                cxfServletParams = new HashMap<>();
            }
            cxfServletParams.put(prop.substring("cxf.servlet.params.".length()), config.getProperty(prop));
        } else if (prop.startsWith("connector.")) {
            // created in container
            getProperties().setProperty(prop, config.getProperty(prop));
        } else if (prop.equals("realm")) {
            final ObjectRecipe recipe = newRecipe(config.getProperty(prop));
            for (final String realmConfig : config.stringPropertyNames()) {
                if (realmConfig.startsWith("realm.")) {
                    recipe.setProperty(realmConfig.substring("realm.".length()), config.getProperty(realmConfig));
                }
            }
            this.realm = Realm.class.cast(recipe.create());
        } else if (prop.equals("login")) {
            final ObjectRecipe recipe = newRecipe(Meecrowave.LoginConfigBuilder.class.getName());
            for (final String nestedConfig : config.stringPropertyNames()) {
                if (nestedConfig.startsWith("login.")) {
                    recipe.setProperty(nestedConfig.substring("login.".length()), config.getProperty(nestedConfig));
                }
            }
            loginConfig = Meecrowave.LoginConfigBuilder.class.cast(recipe.create());
        } else if (prop.equals("securityConstraint")) {
            final ObjectRecipe recipe = newRecipe(Meecrowave.SecurityConstaintBuilder.class.getName());
            for (final String nestedConfig : config.stringPropertyNames()) {
                if (nestedConfig.startsWith("securityConstraint.")) {
                    recipe.setProperty(nestedConfig.substring("securityConstraint.".length()), config.getProperty(nestedConfig));
                }
            }
            securityConstraints.add(Meecrowave.SecurityConstaintBuilder.class.cast(recipe.create()));
        } else if (prop.equals("configurationCustomizer")) {
            final ObjectRecipe recipe = newRecipe(prop);
            for (final String nestedConfig : config.stringPropertyNames()) {
                if (nestedConfig.startsWith(prop + '.')) {
                    recipe.setProperty(nestedConfig.substring(prop.length() + 2), config.getProperty(nestedConfig));
                }
            }
            addCustomizer(Consumer.class.cast(recipe.create()));
        }
    }
}
Also used : HashMap(java.util.HashMap) Substitutor(org.apache.meecrowave.lang.Substitutor) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException) CliOption(org.apache.meecrowave.runner.cli.CliOption) Field(java.lang.reflect.Field) ObjectRecipe(org.apache.xbean.recipe.ObjectRecipe) Consumer(java.util.function.Consumer) Objects(java.util.Objects) File(java.io.File) Meecrowave(org.apache.meecrowave.Meecrowave)

Example 2 with Substitutor

use of org.apache.meecrowave.lang.Substitutor in project meecrowave by apache.

the class MeecrowaveBundleMojo method execute.

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (skip) {
        getLog().warn(getClass().getSimpleName() + " skipped");
        return;
    }
    final File distroFolder = new File(buildDirectory, rootName == null ? artifactId + "-distribution" : rootName);
    if (distroFolder.exists()) {
        delete(distroFolder);
    }
    Stream.of("bin", "conf", "logs", "lib").forEach(i -> new File(distroFolder, i).mkdirs());
    copyProvidedFiles(distroFolder);
    write(new File(distroFolder, "logs/you_can_safely_delete.txt"), DELETE_TEXT);
    final Collection<String> includedArtifacts = project.getArtifacts().stream().filter(this::isIncluded).map(a -> {
        addLib(distroFolder, a.getFile());
        return a.getArtifactId();
    }).collect(toList());
    if (app.exists()) {
        addLib(distroFolder, app);
    }
    if (webapp != null && webapp.isDirectory()) {
        try {
            final Path rootSrc = webapp.toPath().toAbsolutePath();
            final Path rootTarget = distroFolder.toPath().toAbsolutePath().resolve("docBase");
            Files.walkFileTree(rootSrc, new SimpleFileVisitor<Path>() {

                @Override
                public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
                    final Path target = rootTarget.resolve(rootSrc.relativize(file));
                    target.toFile().getParentFile().mkdirs();
                    Files.copy(file, target, StandardCopyOption.REPLACE_EXISTING);
                    return super.visitFile(file, attrs);
                }
            });
        } catch (final IOException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
    }
    if (enforceCommonsCli && !includedArtifacts.contains("commons-cli")) {
        addLib(distroFolder, resolve("commons-cli", "commons-cli", "1.4", ""));
    }
    if (libs != null) {
        libs.forEach(l -> {
            final boolean transitive = l.endsWith("?transitive");
            final String coords = transitive ? l.substring(0, l.length() - "?transitive".length()) : l;
            final String[] c = coords.split(":");
            if (c.length < 3 || c.length > 5) {
                throw new IllegalArgumentException("libs syntax is groupId:artifactId:version[:classifier][:type[?transitive]]");
            }
            if (!transitive) {
                addLib(distroFolder, resolve(c[0], c[1], c[2], c.length == 4 ? c[3] : ""));
            } else {
                addTransitiveDependencies(distroFolder, includedArtifacts, new Dependency() {

                    {
                        setGroupId(c[0]);
                        setArtifactId(c[1]);
                        setVersion(c[2]);
                        if (c.length == 4 && !"-".equals(c[3])) {
                            setClassifier(c[3]);
                        }
                        if (c.length == 5) {
                            setType(c[4]);
                        }
                    }
                });
            }
        });
    }
    if (enforceMeecrowave && !includedArtifacts.contains("meecrowave-core")) {
        addTransitiveDependencies(distroFolder, includedArtifacts, new Dependency() {

            {
                setGroupId("org.apache.meecrowave");
                setArtifactId("meecrowave-core");
                setVersion(findVersion());
            }
        });
    }
    for (final String ext : asList("sh", "bat")) {
        try (final BufferedReader reader = new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("bin/meecrowave." + ext)))) {
            final File target = new File(distroFolder, "bin/meecrowave." + ext);
            if (!target.exists()) {
                write(target, new Substitutor(new HashMap<String, String>() {

                    {
                        put("main", main);
                        put("logManager", hasLog4j(distroFolder) ? "org.apache.logging.log4j.jul.LogManager" : "org.apache.juli.ClassLoaderLogManager");
                    }
                }).replace(reader.lines().collect(joining("\n"))));
            }
        } catch (final IOException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
    }
    if (fakeTomcatScripts) {
        Stream.of("catalina.sh", "shutdown.sh", "startup.sh").forEach(script -> {
            try (final BufferedReader reader = new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("bin/" + script)))) {
                final File target = new File(distroFolder, "bin/" + script);
                if (!target.exists()) {
                    write(target, reader.lines().collect(joining("\n")));
                }
            } catch (final IOException e) {
                throw new IllegalStateException(e.getMessage(), e);
            }
        });
    }
    final Path prefix = skipArchiveRootFolder ? distroFolder.toPath() : distroFolder.getParentFile().toPath();
    for (final String format : formats) {
        getLog().info(format + "-ing Custom Meecrowave Distribution");
        final File output = new File(buildDirectory, artifactId + "-meecrowave-distribution." + format);
        switch(format.toLowerCase(ENGLISH)) {
            case "tar.gz":
                try (final TarArchiveOutputStream tarGz = new TarArchiveOutputStream(new GZIPOutputStream(new FileOutputStream(output)))) {
                    tarGz.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
                    for (final String entry : distroFolder.list()) {
                        tarGz(tarGz, new File(distroFolder, entry), prefix);
                    }
                } catch (final IOException e) {
                    throw new MojoExecutionException(e.getMessage(), e);
                }
                break;
            case "zip":
                try (final ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new FileOutputStream(output))) {
                    for (final String entry : distroFolder.list()) {
                        zip(zos, new File(distroFolder, entry), prefix);
                    }
                } catch (final IOException e) {
                    throw new MojoExecutionException(e.getMessage(), e);
                }
                break;
            default:
                throw new IllegalArgumentException(format + " is not supported");
        }
        attach(format, output);
    }
    if (!keepExplodedFolder) {
        delete(distroFolder);
    }
}
Also used : ZipArchiveEntry(org.apache.commons.compress.archivers.zip.ZipArchiveEntry) DependencyResolutionException(org.apache.maven.project.DependencyResolutionException) Parameter(org.apache.maven.plugins.annotations.Parameter) TarArchiveOutputStream(org.apache.commons.compress.archivers.tar.TarArchiveOutputStream) MavenProject(org.apache.maven.project.MavenProject) Arrays.asList(java.util.Arrays.asList) ProjectDependenciesResolver(org.apache.maven.project.ProjectDependenciesResolver) DependencyVisitor(org.eclipse.aether.graph.DependencyVisitor) Artifact(org.apache.maven.artifact.Artifact) DependencyGraphBuilder(org.apache.maven.shared.dependency.graph.DependencyGraphBuilder) Path(java.nio.file.Path) ENGLISH(java.util.Locale.ENGLISH) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) DependencyResolutionRequest(org.apache.maven.project.DependencyResolutionRequest) Collection(java.util.Collection) StandardOpenOption(java.nio.file.StandardOpenOption) Substitutor(org.apache.meecrowave.lang.Substitutor) StandardCharsets(java.nio.charset.StandardCharsets) Collectors.joining(java.util.stream.Collectors.joining) FileVisitResult(java.nio.file.FileVisitResult) List(java.util.List) Stream(java.util.stream.Stream) LocalRepositoryManager(org.eclipse.aether.repository.LocalRepositoryManager) ArtifactRequest(org.eclipse.aether.resolution.ArtifactRequest) GZIPOutputStream(java.util.zip.GZIPOutputStream) AbstractMojo(org.apache.maven.plugin.AbstractMojo) RepositorySystem(org.eclipse.aether.RepositorySystem) MavenProjectHelper(org.apache.maven.project.MavenProjectHelper) Dependency(org.apache.maven.model.Dependency) Component(org.apache.maven.plugins.annotations.Component) HashMap(java.util.HashMap) RepositorySystemSession(org.eclipse.aether.RepositorySystemSession) StandardCopyOption(java.nio.file.StandardCopyOption) Mojo(org.apache.maven.plugins.annotations.Mojo) TarArchiveEntry(org.apache.commons.compress.archivers.tar.TarArchiveEntry) ZipArchiveOutputStream(org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream) ArtifactResolutionException(org.eclipse.aether.resolution.ArtifactResolutionException) Properties(java.util.Properties) DependencyNode(org.eclipse.aether.graph.DependencyNode) DefaultArtifact(org.eclipse.aether.artifact.DefaultArtifact) Files(java.nio.file.Files) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) Log(org.apache.maven.plugin.logging.Log) ArtifactResult(org.eclipse.aether.resolution.ArtifactResult) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) InputStreamReader(java.io.InputStreamReader) File(java.io.File) MojoFailureException(org.apache.maven.plugin.MojoFailureException) RemoteRepository(org.eclipse.aether.repository.RemoteRepository) RUNTIME_PLUS_SYSTEM(org.apache.maven.plugins.annotations.ResolutionScope.RUNTIME_PLUS_SYSTEM) Collectors.toList(java.util.stream.Collectors.toList) ArtifactResolver(org.eclipse.aether.impl.ArtifactResolver) DefaultDependencyResolutionRequest(org.apache.maven.project.DefaultDependencyResolutionRequest) BufferedReader(java.io.BufferedReader) InputStream(java.io.InputStream) Path(java.nio.file.Path) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) InputStreamReader(java.io.InputStreamReader) Substitutor(org.apache.meecrowave.lang.Substitutor) ZipArchiveOutputStream(org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) Dependency(org.apache.maven.model.Dependency) GZIPOutputStream(java.util.zip.GZIPOutputStream) FileOutputStream(java.io.FileOutputStream) BufferedReader(java.io.BufferedReader) TarArchiveOutputStream(org.apache.commons.compress.archivers.tar.TarArchiveOutputStream) File(java.io.File) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 3 with Substitutor

use of org.apache.meecrowave.lang.Substitutor 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() && Log4j2s.IS_PRESENT) {
        // /!\ 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.isLoggingGlobalSetup() && Log4j2s.IS_PRESENT) {
        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 = () -> {
            if (Log4j2s.IS_PRESENT) {
                new Log4j2Shutdown().shutdown();
            }
            systemPropsToRestore.forEach((key, value) -> {
                if (value == null) {
                    System.clearProperty(key);
                } else {
                    System.setProperty(key, value);
                }
            });
        };
    }
    setupJmx(configuration.isTomcatNoJmx());
    clearCatalinaSystemProperties = System.getProperty("catalina.base") == null && System.getProperty("catalina.home") == null;
    tomcat = new InternalTomcat();
    {
        // setup
        base = new File(newBaseDir());
        // create the temp dir folder.
        File tempDir;
        if (configuration.getTempDir() == null || configuration.getTempDir().length() == 0) {
            tempDir = createDirectory(base, "temp");
        } else {
            tempDir = new File(configuration.getTempDir());
            if (!tempDir.exists()) {
                tempDir.mkdirs();
            }
        }
        try {
            workDir = createDirectory(base, "work");
        } catch (final IllegalStateException ise) {
            // in case we could not create that directory we create it in the temp dir folder
            workDir = createDirectory(tempDir, "work");
        }
        synchronize(new File(base, "conf"), configuration.getConf());
    }
    final Properties props = configuration.getProperties();
    Substitutor 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.getHttpPort()));
                placeHolders.put("meecrowave.embedded.https", Integer.toString(configuration.getHttpsPort()));
                placeHolders.put("meecrowave.embedded.stop", Integer.toString(configuration.getStopPort()));
                substitutor = new Substitutor(placeHolders);
            }
            props.put(s, substitutor.replace(v));
        }
    }
    final File conf = new File(base, "conf");
    tomcat.setBaseDir(base.getAbsolutePath());
    tomcat.setHostname(configuration.getHost());
    final boolean initialized;
    if (configuration.getServerXml() != null) {
        final File file = new File(conf, "server.xml");
        if (!file.equals(configuration.getServerXml())) {
            try (final InputStream is = new FileInputStream(configuration.getServerXml());
                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.isKeepServerXmlAsThis()) {
            configuration.setHttpPort(Integer.parseInt(ports.http()));
            configuration.setStopPort(Integer.parseInt(ports.stop()));
        } else {
            final Map<String, String> replacements = new HashMap<>();
            replacements.put(ports.http(), String.valueOf(configuration.getHttpPort()));
            replacements.put(ports.https(), String.valueOf(configuration.getHttpsPort()));
            replacements.put(ports.stop(), String.valueOf(configuration.getStopPort()));
            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.getStopPort());
        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.getHost());
        tomcat.getEngine().setDefaultHost(configuration.getHost());
        final StandardHost host = new StandardHost();
        host.setName(configuration.getHost());
        try {
            final File webapps = createDirectory(base, "webapps");
            host.setAppBase(webapps.getAbsolutePath());
        } catch (final IllegalStateException ise) {
        // never an issue since the webapps are deployed being put in webapps - so no dynamic folder
        // or through their path - so don't need webapps folder
        }
        // forced for now cause OWB doesn't support war:file:// urls
        host.setUnpackWARs(true);
        try {
            host.setWorkDir(workDir.getCanonicalPath());
        } catch (final IOException e) {
            host.setWorkDir(workDir.getAbsolutePath());
        }
        tomcat.setHost(host);
    }
    ofNullable(configuration.getTomcatAccessLogPattern()).ifPresent(pattern -> tomcat.getHost().getPipeline().addValve(new LoggingAccessLogPattern(pattern)));
    final List<Valve> valves = buildValves();
    if (!valves.isEmpty()) {
        final Pipeline pipeline = tomcat.getHost().getPipeline();
        valves.forEach(pipeline::addValve);
    }
    if (configuration.getRealm() != null) {
        tomcat.getEngine().setRealm(configuration.getRealm());
    }
    if (tomcat.getRawConnector() == null && !configuration.isSkipHttp()) {
        final Connector connector = createConnector();
        connector.setPort(configuration.getHttpPort());
        if (connector.getProperty("connectionTimeout") == null) {
            connector.setProperty("connectionTimeout", "3000");
        }
        tomcat.getService().addConnector(connector);
        tomcat.setConnector(connector);
    }
    // create https connector
    if (configuration.isSsl()) {
        final Connector httpsConnector = createConnector();
        httpsConnector.setPort(configuration.getHttpsPort());
        httpsConnector.setSecure(true);
        httpsConnector.setScheme("https");
        httpsConnector.setProperty("SSLEnabled", "true");
        if (configuration.getSslProtocol() != null) {
            configuration.getProperties().setProperty("connector.sslhostconfig.sslProtocol", configuration.getSslProtocol());
        }
        if (configuration.getProperties().getProperty("connector.sslhostconfig.hostName") != null) {
            httpsConnector.setProperty("defaultSSLHostConfigName", configuration.getProperties().getProperty("connector.sslhostconfig.hostName"));
        }
        if (configuration.getKeystoreFile() != null) {
            configuration.getProperties().setProperty("connector.sslhostconfig.certificateKeystoreFile", configuration.getKeystoreFile());
        }
        if (configuration.getKeystorePass() != null) {
            configuration.getProperties().setProperty("connector.sslhostconfig.certificateKeystorePassword", configuration.getKeystorePass());
        }
        configuration.getProperties().setProperty("connector.sslhostconfig.certificateKeystoreType", configuration.getKeystoreType());
        if (configuration.getClientAuth() != null) {
            httpsConnector.setProperty("clientAuth", configuration.getClientAuth());
        }
        if (configuration.getKeyAlias() != null) {
            configuration.getProperties().setProperty("connector.sslhostconfig.certificateKeyAlias", configuration.getKeyAlias());
        }
        if (configuration.isHttp2()) {
            httpsConnector.addUpgradeProtocol(new Http2Protocol());
        }
        final List<SSLHostConfig> buildSslHostConfig = buildSslHostConfig();
        if (!buildSslHostConfig.isEmpty()) {
            createDirectory(base, "conf");
        }
        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.getDefaultSSLHostConfigName() != null) {
            httpsConnector.setProperty("defaultSSLHostConfigName", configuration.getDefaultSSLHostConfigName());
        }
        tomcat.getService().addConnector(httpsConnector);
        if (configuration.isSkipHttp()) {
            tomcat.setConnector(httpsConnector);
        }
    }
    for (final Connector c : configuration.getConnectors()) {
        tomcat.getService().addConnector(c);
    }
    if (!configuration.isSkipHttp() && !configuration.isSsl() && !configuration.getConnectors().isEmpty()) {
        tomcat.setConnector(configuration.getConnectors().iterator().next());
    }
    if (configuration.getUsers() != null) {
        for (final Map.Entry<String, String> user : configuration.getUsers().entrySet()) {
            tomcat.addUser(user.getKey(), user.getValue());
        }
    }
    if (configuration.getRoles() != null) {
        for (final Map.Entry<String, String> user : configuration.getRoles().entrySet()) {
            for (final String role : user.getValue().split(" *, *")) {
                tomcat.addRole(user.getKey(), role);
            }
        }
    }
    StreamSupport.stream(ServiceLoader.load(Meecrowave.InstanceCustomizer.class).spliterator(), false).peek(i -> {
        if (MeecrowaveAwareInstanceCustomizer.class.isInstance(i)) {
            MeecrowaveAwareInstanceCustomizer.class.cast(i).setMeecrowave(this);
        }
    }).sorted(Priotities::sortByPriority).forEach(c -> c.accept(tomcat));
    configuration.getInstanceCustomizers().forEach(c -> c.accept(tomcat));
    StreamSupport.stream(ServiceLoader.load(Meecrowave.ContextCustomizer.class).spliterator(), false).peek(i -> {
        if (MeecrowaveAwareContextCustomizer.class.isInstance(i)) {
            MeecrowaveAwareContextCustomizer.class.cast(i).setMeecrowave(this);
        }
    }).sorted(Priotities::sortByPriority).forEach(configuration::addGlobalContextCustomizer);
    beforeStart();
    if (configuration.isInitializeClientBus() && Cxfs.IS_PRESENT && !Cxfs.hasDefaultBus()) {
        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 : MeecrowaveContextConfig(org.apache.meecrowave.tomcat.MeecrowaveContextConfig) ProvidedLoader(org.apache.meecrowave.tomcat.ProvidedLoader) SessionCookieConfig(javax.servlet.SessionCookieConfig) 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) ResourceFinder(org.apache.xbean.finder.ResourceFinder) Stream(java.util.stream.Stream) ConfigurableBus(org.apache.meecrowave.cxf.ConfigurableBus) JarScanFilter(org.apache.tomcat.JarScanFilter) Log4j2s(org.apache.meecrowave.logging.log4j2.Log4j2s) 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) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) StreamSupport(java.util.stream.StreamSupport) SSLHostConfig(org.apache.tomcat.util.net.SSLHostConfig) ManagementFactory(java.lang.management.ManagementFactory) Properties(java.util.Properties) LogFacade(org.apache.meecrowave.logging.tomcat.LogFacade) Files(java.nio.file.Files) Cxfs(org.apache.meecrowave.cxf.Cxfs) 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) StringReader(java.io.StringReader) TreeMap(java.util.TreeMap) Paths(java.nio.file.Paths) Pipeline(org.apache.catalina.Pipeline) BeanManager(javax.enterprise.inject.spi.BeanManager) URL(java.net.URL) Lifecycle(org.apache.catalina.Lifecycle) Priotities(org.apache.meecrowave.service.Priotities) 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) StandardSessionIdGenerator(org.apache.catalina.util.StandardSessionIdGenerator) ServiceLoader(java.util.ServiceLoader) Substitutor(org.apache.meecrowave.lang.Substitutor) 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) OWBAutoSetup(org.apache.meecrowave.openwebbeans.OWBAutoSetup) LoginConfig(org.apache.tomcat.util.descriptor.web.LoginConfig) SAXParserFactory(javax.xml.parsers.SAXParserFactory) Valve(org.apache.catalina.Valve) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Cipher(javax.crypto.Cipher) Option(org.apache.xbean.recipe.Option) BiPredicate(java.util.function.BiPredicate) ServletContainerInitializer(javax.servlet.ServletContainerInitializer) Log4j2Shutdown(org.apache.meecrowave.logging.log4j2.Log4j2Shutdown) Attributes(org.xml.sax.Attributes) Comparator.comparing(java.util.Comparator.comparing) ROOT(java.util.Locale.ROOT) InjectionTarget(javax.enterprise.inject.spi.InjectionTarget) CxfCdiAutoSetup(org.apache.meecrowave.cxf.CxfCdiAutoSetup) OutputStream(java.io.OutputStream) Collections.emptySet(java.util.Collections.emptySet) MalformedURLException(java.net.MalformedURLException) 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) Configuration(org.apache.meecrowave.configuration.Configuration) StandardManager(org.apache.catalina.session.StandardManager) FileInputStream(java.io.FileInputStream) Context(org.apache.catalina.Context) 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) InputStream(java.io.InputStream) MalformedURLException(java.net.MalformedURLException) HashMap(java.util.HashMap) Substitutor(org.apache.meecrowave.lang.Substitutor) FileOutputStream(java.io.FileOutputStream) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) Log4j2Shutdown(org.apache.meecrowave.logging.log4j2.Log4j2Shutdown) Valve(org.apache.catalina.Valve) Http2Protocol(org.apache.coyote.http2.Http2Protocol) FileInputStream(java.io.FileInputStream) Log4j2Log(org.apache.meecrowave.logging.tomcat.Log4j2Log) FileOutputStream(java.io.FileOutputStream) File(java.io.File) Map(java.util.Map) TreeMap(java.util.TreeMap) HashMap(java.util.HashMap) LoggingAccessLogPattern(org.apache.meecrowave.tomcat.LoggingAccessLogPattern) Connector(org.apache.catalina.connector.Connector) Log4j2Logger(org.apache.meecrowave.logging.jul.Log4j2Logger) Log4j2LoggerFactory(org.apache.meecrowave.logging.openwebbeans.Log4j2LoggerFactory) FileWriter(java.io.FileWriter) Properties(java.util.Properties) ConfigurableBus(org.apache.meecrowave.cxf.ConfigurableBus) URL(java.net.URL) 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) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) Pipeline(org.apache.catalina.Pipeline) StandardHost(org.apache.catalina.core.StandardHost) SSLHostConfig(org.apache.tomcat.util.net.SSLHostConfig) Writer(java.io.Writer) FileWriter(java.io.FileWriter)

Aggregations

File (java.io.File)3 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 Substitutor (org.apache.meecrowave.lang.Substitutor)3 FileOutputStream (java.io.FileOutputStream)2 InputStream (java.io.InputStream)2 Field (java.lang.reflect.Field)2 ServerSocket (java.net.ServerSocket)2 StandardCharsets (java.nio.charset.StandardCharsets)2 Files (java.nio.file.Files)2 Path (java.nio.file.Path)2 StandardCopyOption (java.nio.file.StandardCopyOption)2 Collection (java.util.Collection)2 List (java.util.List)2 Properties (java.util.Properties)2 Collectors.toList (java.util.stream.Collectors.toList)2 Stream (java.util.stream.Stream)2 BufferedReader (java.io.BufferedReader)1 FileInputStream (java.io.FileInputStream)1 FileWriter (java.io.FileWriter)1