From 88a22991de724dfe9a12b9dbc0783bed17ebcbbd Mon Sep 17 00:00:00 2001 From: Maurizio Turatti Date: Wed, 21 Nov 2018 11:15:09 +0100 Subject: [PATCH] Refacroring of Bootstrapper.java --- src/main/java/org/restheart/Bootstrapper.java | 109 +++++++++--------- 1 file changed, 53 insertions(+), 56 deletions(-) diff --git a/src/main/java/org/restheart/Bootstrapper.java b/src/main/java/org/restheart/Bootstrapper.java index 45a0334e4..753467232 100644 --- a/src/main/java/org/restheart/Bootstrapper.java +++ b/src/main/java/org/restheart/Bootstrapper.java @@ -188,11 +188,8 @@ private static void run() { } else { if (OSChecker.isWindows()) { logWindowsStart(); - LOGGER.error("Fork is not supported on Windows"); - LOGGER.info(ansi().fg(GREEN).bold().a("RESTHeart stopped").reset().toString()); - System.exit(-1); } @@ -215,15 +212,12 @@ private static void run() { } catch (Exception t) { logErrorAndExit("Error staring forked process", t, false, false, -1); } - startServer(true); } else { initLogging(d); - try { logWindowsStart(); logLoggingConfiguration(true); - d.daemonize(); } catch (Throwable t) { logErrorAndExit("Error forking", t, false, false, -1); @@ -249,19 +243,15 @@ private static boolean checkPidFile(Path confFilePath) { if (OSChecker.isWindows()) { return false; } - // pid file name include the hash of the configuration file so that // for each configuration we can have just one instance running - Path pidFilePath = FileUtils.getPidFilePath( - FileUtils.getFileAbsoultePathHash(confFilePath)); - + Path pidFilePath = FileUtils + .getPidFilePath(FileUtils.getFileAbsoultePathHash(confFilePath)); if (Files.exists(pidFilePath)) { LOGGER.warn("Found pid file! If this instance is already " + "running, startup will fail with a BindException"); - return true; } - return false; } @@ -283,14 +273,9 @@ public static void startup(final Path confFilePath) { try { configuration = FileUtils.getConfiguration(confFilePath, false); } catch (ConfigurationException ex) { - if (RESTHEART_VERSION != null) { - LOGGER.info(ansi().fg(RED).bold().a(RESTHEART).reset().toString() + " version {}", - ansi().fg(MAGENTA).bold().a(RESTHEART_VERSION).reset().toString()); - } - + logWindowsStart(); logErrorAndExit(ex.getMessage() + EXITING, ex, false, -1); } - startServer(false); } @@ -339,7 +324,8 @@ private static void logLoggingConfiguration(boolean fork) { } if (configuration.isLogToFile()) { - LOGGER.info("Logging to file {} with level {}", configuration.getLogFilePath(), configuration.getLogLevel()); + LOGGER.info("Logging to file {} with level {}", + configuration.getLogFilePath(), configuration.getLogLevel()); } if (!fork) { @@ -380,7 +366,8 @@ private static void startServer(boolean fork) { logLoggingConfiguration(fork); - LOGGER.debug("Initializing MongoDB connection pool to {} with options {}", configuration.getMongoUri().getHosts(), configuration.getMongoUri().getOptions()); + LOGGER.debug("Initializing MongoDB connection pool to {} with options {}", + configuration.getMongoUri().getHosts(), configuration.getMongoUri().getOptions()); try { MongoDBClientSingleton.init(configuration); @@ -547,36 +534,33 @@ private static void startCoreSystem() { logErrorAndExit("No configuration found. exiting..", null, false, -1); } - if (!configuration.isHttpsListener() && !configuration.isHttpListener() && !configuration.isAjpListener()) { + if (!configuration.isHttpsListener() + && !configuration.isHttpListener() + && !configuration.isAjpListener()) { logErrorAndExit("No listener specified. exiting..", null, false, -1); } final IdentityManager identityManager = loadIdentityManager(); - final AccessManager accessManager = loadAccessManager(); - final AuthenticationMechanism authenticationMechanism = loadAuthenticationMechanism(identityManager); if (configuration.isAuthTokenEnabled()) { - LOGGER.info("Token based authentication enabled with token TTL {} minutes", configuration.getAuthTokenTtl()); + LOGGER.info("Token based authentication enabled with token TTL {} minutes", + configuration.getAuthTokenTtl()); } SSLContext sslContext = null; try { sslContext = SSLContext.getInstance("TLS"); - KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); if (getConfiguration().isUseEmbeddedKeystore()) { char[] storepass = "restheart".toCharArray(); char[] keypass = "restheart".toCharArray(); - String storename = "rakeystore.jks"; - ks.load(Bootstrapper.class.getClassLoader().getResourceAsStream(storename), storepass); kmf.init(ks, keypass); } else { @@ -585,9 +569,7 @@ private static void startCoreSystem() { kmf.init(ks, configuration.getCertPassword().toCharArray()); } } - tmf.init(ks); - sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); } catch (KeyManagementException | NoSuchAlgorithmException @@ -605,17 +587,20 @@ private static void startCoreSystem() { if (configuration.isHttpsListener()) { builder.addHttpsListener(configuration.getHttpsPort(), configuration.getHttpHost(), sslContext); - LOGGER.info("HTTPS listener bound at {}:{}", configuration.getHttpsHost(), configuration.getHttpsPort()); + LOGGER.info("HTTPS listener bound at {}:{}", + configuration.getHttpsHost(), configuration.getHttpsPort()); } if (configuration.isHttpListener()) { builder.addHttpListener(configuration.getHttpPort(), configuration.getHttpsHost()); - LOGGER.info("HTTP listener bound at {}:{}", configuration.getHttpHost(), configuration.getHttpPort()); + LOGGER.info("HTTP listener bound at {}:{}", + configuration.getHttpHost(), configuration.getHttpPort()); } if (configuration.isAjpListener()) { builder.addAjpListener(configuration.getAjpPort(), configuration.getAjpHost()); - LOGGER.info("Ajp listener bound at {}:{}", configuration.getAjpHost(), configuration.getAjpPort()); + LOGGER.info("Ajp listener bound at {}:{}", + configuration.getAjpHost(), configuration.getAjpPort()); } LocalCachesSingleton.init(configuration); @@ -652,7 +637,8 @@ private static void startCoreSystem() { builder.setServerOption( UndertowOptions.ALLOW_UNESCAPED_CHARACTERS_IN_URL, configuration.isAllowUnescapedCharactersInUrl()); - LOGGER.info("Allow unescaped characters in URL: {}", configuration.isAllowUnescapedCharactersInUrl()); + LOGGER.info("Allow unescaped characters in URL: {}", + configuration.isAllowUnescapedCharactersInUrl()); ConfigurationHelper.setConnectionOptions(builder, configuration); @@ -669,7 +655,8 @@ private static AuthenticationMechanism loadAuthenticationMechanism(final Identit AuthenticationMechanism authMechanism = null; if (configuration.getAuthMechanism() != null) { try { - AuthenticationMechanismFactory am = (AuthenticationMechanismFactory) Class.forName(configuration.getAuthMechanism()) + AuthenticationMechanismFactory am = (AuthenticationMechanismFactory) Class + .forName(configuration.getAuthMechanism()) .getConstructor() .newInstance(); @@ -682,10 +669,12 @@ private static AuthenticationMechanism loadAuthenticationMechanism(final Identit | NoSuchMethodException | SecurityException | InvocationTargetException ex) { - logErrorAndExit("Error configuring Authentication Mechanism implementation " + configuration.getAuthMechanism(), ex, false, -3); + logErrorAndExit("Error configuring Authentication Mechanism implementation " + + configuration.getAuthMechanism(), ex, false, -3); } } else { - LOGGER.info("Authentication Mechanism io.undertow.security.impl.BasicAuthenticationMechanism enabled"); + LOGGER.info("Authentication Mechanism " + + "io.undertow.security.impl.BasicAuthenticationMechanism enabled"); } return authMechanism; } @@ -714,7 +703,8 @@ private static IdentityManager loadIdentityManager() { | NoSuchMethodException | SecurityException | InvocationTargetException ex) { - logErrorAndExit("Error configuring Identity Manager implementation " + configuration.getIdmImpl(), ex, false, -3); + logErrorAndExit("Error configuring Identity Manager implementation " + + configuration.getIdmImpl(), ex, false, -3); } } return identityManager; @@ -736,7 +726,6 @@ private static AccessManager loadAccessManager() { Object am = Class.forName(configuration.getAmImpl()) .getConstructor(Map.class) .newInstance(configuration.getAmArgs()); - LOGGER.info("Access Manager {} enabled", configuration.getAmImpl()); accessManager = (AccessManager) am; } catch (ClassNotFoundException @@ -746,7 +735,8 @@ private static AccessManager loadAccessManager() { | NoSuchMethodException | SecurityException | InvocationTargetException ex) { - logErrorAndExit("Error configuring Access Manager implementation " + configuration.getAmImpl(), ex, false, -3); + logErrorAndExit("Error configuring Access Manager implementation " + + configuration.getAmImpl(), ex, false, -3); } } return accessManager; @@ -784,11 +774,9 @@ private static void logErrorAndExit(String message, Throwable t, boolean silent, } private static boolean isPathTemplate(final String url) { - if (url == null) { - return false; - } else { - return url.contains("{") && url.contains("}"); - } + return (url == null) + ? false + : url.contains("{") && url.contains("}"); } /** @@ -865,7 +853,6 @@ private static GracefulShutdownHandler getHandlersPipe( } pipeStaticResourcesHandlers(configuration, paths, authenticationMechanism, identityManager, accessManager); - pipeApplicationLogicHandlers(configuration, paths, authenticationMechanism, identityManager, accessManager); // pipe the auth tokens invalidation handler @@ -943,7 +930,8 @@ private static void pipeStaticResourcesHandlers( } if (where == null || !where.startsWith("/")) { - LOGGER.error("Cannot bind static resources to {}. parameter 'where' must start with /", where); + LOGGER.error("Cannot bind static resources to {}. " + + "parameter 'where' must start with /", where); return; } @@ -956,7 +944,8 @@ private static void pipeStaticResourcesHandlers( if (embedded) { if (path.startsWith("/")) { LOGGER.error("Cannot bind embedded static resources to {}. parameter 'where'" - + "cannot start with /. the path is relative to the jar root dir or classpath directory", where); + + "cannot start with /. the path is relative to the jar root dir" + + " or classpath directory", where); return; } @@ -974,8 +963,10 @@ private static void pipeStaticResourcesHandlers( LOGGER.error("Error extracting embedded static resource {}", path, ex); if ("browser".equals(path)) { - LOGGER.error("**** Have you downloaded the HAL Browser submodule before building?"); - LOGGER.error("**** To fix this, run: $ git submodule update --init --recursive"); + LOGGER.error("**** Have you downloaded the " + + "HAL Browser submodule before building?"); + LOGGER.error("**** To fix this, run: " + + "$ git submodule update --init --recursive"); } return; @@ -1021,13 +1012,16 @@ private static void pipeStaticResourcesHandlers( paths.addPrefixPath(where, ph); - LOGGER.info("URL {} bound to static resources {}. Access Manager: {}", where, file.getAbsolutePath(), secured); + LOGGER.info("URL {} bound to static resources {}. Access Manager: {}", + where, file.getAbsolutePath(), secured); } else { - LOGGER.error("Failed to bind URL {} to static resources {}. Directory does not exist.", where, path); + LOGGER.error("Failed to bind URL {} to static resources {}." + + " Directory does not exist.", where, path); } } catch (Throwable t) { - LOGGER.error("Cannot bind static resources to {}", sr.get(Configuration.STATIC_RESOURCES_MOUNT_WHERE_KEY), t); + LOGGER.error("Cannot bind static resources to {}", + sr.get(Configuration.STATIC_RESOURCES_MOUNT_WHERE_KEY), t); } }); } @@ -1056,13 +1050,15 @@ private static void pipeApplicationLogicHandlers( Object alArgs = al.get(Configuration.APPLICATION_LOGIC_MOUNT_ARGS_KEY); if (alWhere == null || !alWhere.startsWith("/")) { - LOGGER.error("Cannot pipe application logic handler {}. Parameter 'where' must start with /", alWhere); + LOGGER.error("Cannot pipe application logic handler {}." + + " Parameter 'where' must start with /", alWhere); return; } if (alArgs != null && !(alArgs instanceof Map)) { LOGGER.error("Cannot pipe application logic handler {}." - + "Args are not defined as a map. It is a ", alWhere, alWhere.getClass()); + + "Args are not defined as a map. It is a ", + alWhere, alWhere.getClass()); return; } @@ -1106,7 +1102,8 @@ private static void pipeApplicationLogicHandlers( + " Access manager: {}", "/_logic" + alWhere, alClazz, alSecured); } else { LOGGER.error("Cannot pipe application logic handler {}." - + " Class {} does not extend ApplicationLogicHandler", alWhere, alClazz); + + " Class {} does not extend ApplicationLogicHandler", + alWhere, alClazz); } } catch (ClassNotFoundException