use of org.apache.meecrowave.tomcat.LoggingAccessLogPattern 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;
}
Aggregations