Search in sources :

Example 6 with IntegrationDetails

use of liquibase.integration.IntegrationDetails in project liquibase by liquibase.

the class Main method run.

/**
 * Process the command line arguments and perform the appropriate main action (update, rollback etc.)
 *
 * @param args the command line arguments
 * @return the errorlevel to be returned to the operating system, e.g. for further processing by scripts
 * @throws LiquibaseException a runtime exception
 */
public static int run(String[] args) throws Exception {
    Map<String, Object> scopeObjects = new HashMap<>();
    final IntegrationDetails integrationDetails = new IntegrationDetails();
    integrationDetails.setName("cli");
    final ListIterator<String> argIterator = Arrays.asList(args).listIterator();
    while (argIterator.hasNext()) {
        final String arg = argIterator.next();
        if (arg.startsWith("--")) {
            if (arg.contains("=")) {
                String[] splitArg = arg.split("=", 2);
                String argKey = "argument__" + splitArg[0].replaceFirst("^--", "");
                if (splitArg.length == 2) {
                    integrationDetails.setParameter(argKey, splitArg[1]);
                } else {
                    integrationDetails.setParameter(argKey, "true");
                }
            } else {
                String argKey = "argument__" + arg.replaceFirst("^--", "");
                if (argIterator.hasNext()) {
                    final String next = argIterator.next();
                    if (next.startsWith("--") || isCommand(next)) {
                        integrationDetails.setParameter(argKey, "true");
                        // put value back
                        argIterator.previous();
                    } else {
                        integrationDetails.setParameter(argKey, next);
                    }
                } else {
                    integrationDetails.setParameter(argKey, "true");
                }
            }
        }
    }
    scopeObjects.put("integrationDetails", integrationDetails);
    if (!Main.runningFromNewCli) {
        ConsoleUIService ui = new ConsoleUIService();
        ui.setAllowPrompt(true);
        scopeObjects.put(Scope.Attr.ui.name(), ui);
    }
    return Scope.child(scopeObjects, new Scope.ScopedRunnerWithReturn<Integer>() {

        @Override
        public Integer run() throws Exception {
            Main main = new Main();
            try {
                if ((args.length == 0) || ((args.length == 1) && ("--" + OPTIONS.HELP).equals(args[0]))) {
                    main.printHelp(outputStream);
                    return Integer.valueOf(0);
                } else if (("--" + OPTIONS.VERSION).equals(args[0])) {
                    main.command = "";
                    main.parseDefaultPropertyFiles();
                    Scope.getCurrentScope().getUI().sendMessage(CommandLineUtils.getBanner());
                    Scope.getCurrentScope().getUI().sendMessage(String.format(coreBundle.getString("version.number"), LiquibaseUtil.getBuildVersionInfo()));
                    LicenseService licenseService = Scope.getCurrentScope().getSingleton(LicenseServiceFactory.class).getLicenseService();
                    if (licenseService != null && main.liquibaseProLicenseKey != null) {
                        Location licenseKeyLocation = new Location("property liquibaseProLicenseKey", LocationType.BASE64_STRING, main.liquibaseProLicenseKey);
                        LicenseInstallResult result = licenseService.installLicense(licenseKeyLocation);
                        if (result.code != 0) {
                            String allMessages = String.join("\n", result.messages);
                            Scope.getCurrentScope().getUI().sendErrorMessage(allMessages);
                        }
                    }
                    if (licenseService != null) {
                        Scope.getCurrentScope().getUI().sendMessage(licenseService.getLicenseInfo());
                    }
                    Scope.getCurrentScope().getUI().sendMessage(String.format("Running Java under %s (Version %s)", System.getProperties().getProperty("java.home"), System.getProperty("java.version")));
                    return Integer.valueOf(0);
                }
                // 
                for (int i = 0; i < args.length; i++) {
                    CodePointCheck codePointCheck = checkArg(args[i]);
                    if (codePointCheck != null) {
                        String message = "A non-standard character '" + codePointCheck.ch + "' was detected on the command line at position " + (codePointCheck.position + 1) + " of argument number " + (i + 1) + ".\nIf problems occur, please remove the character and try again.";
                        LOG.warning(message);
                        System.err.println(message);
                    }
                }
                try {
                    main.parseOptions(args);
                    if (main.command == null) {
                        main.printHelp(outputStream);
                        return Integer.valueOf(0);
                    }
                } catch (CommandLineParsingException e) {
                    Scope.getCurrentScope().getUI().sendMessage(CommandLineUtils.getBanner());
                    Scope.getCurrentScope().getUI().sendMessage(coreBundle.getString("how.to.display.help"));
                    throw e;
                }
                if (!Main.runningFromNewCli) {
                    final ConsoleUIService ui = (ConsoleUIService) Scope.getCurrentScope().getUI();
                    System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tF %1$tT] %4$s [%2$s] %5$s%6$s%n");
                    java.util.logging.Logger rootLogger = java.util.logging.Logger.getLogger("");
                    java.util.logging.Logger liquibaseLogger = java.util.logging.Logger.getLogger("liquibase");
                    liquibaseLogger.setParent(rootLogger);
                    final JavaLogService logService = (JavaLogService) Scope.getCurrentScope().get(Scope.Attr.logService, LogService.class);
                    logService.setParent(liquibaseLogger);
                    if (main.logLevel == null) {
                        String defaultLogLevel = System.getProperty("liquibase.log.level");
                        if (defaultLogLevel == null) {
                            setLogLevel(logService, rootLogger, liquibaseLogger, Level.OFF);
                        } else {
                            setLogLevel(logService, rootLogger, liquibaseLogger, parseLogLevel(defaultLogLevel, ui));
                        }
                    } else {
                        setLogLevel(logService, rootLogger, liquibaseLogger, parseLogLevel(main.logLevel, ui));
                    }
                    if (main.logFile != null) {
                        FileHandler fileHandler = new FileHandler(main.logFile, true);
                        fileHandler.setFormatter(new SimpleFormatter());
                        if (liquibaseLogger.getLevel() == Level.OFF) {
                            fileHandler.setLevel(Level.FINE);
                        }
                        rootLogger.addHandler(fileHandler);
                        for (Handler handler : rootLogger.getHandlers()) {
                            if (handler instanceof ConsoleHandler) {
                                handler.setLevel(Level.OFF);
                            }
                        }
                    }
                    if (main.command != null && main.command.toLowerCase().endsWith("sql")) {
                        ui.setOutputStream(System.err);
                    }
                }
                LicenseService licenseService = Scope.getCurrentScope().getSingleton(LicenseServiceFactory.class).getLicenseService();
                if (licenseService != null) {
                    if (main.liquibaseProLicenseKey == null) {
                        if (!Main.runningFromNewCli) {
                            Scope.getCurrentScope().getLog(getClass()).info("No Liquibase Pro license key supplied. Please set liquibaseProLicenseKey on command line or in liquibase.properties to use Liquibase Pro features.");
                        }
                    } else {
                        Location licenseKeyLocation = new Location("property liquibaseProLicenseKey", LocationType.BASE64_STRING, main.liquibaseProLicenseKey);
                        LicenseInstallResult result = licenseService.installLicense(licenseKeyLocation);
                        if (result.code != 0) {
                            String allMessages = String.join("\n", result.messages);
                            if (!Main.runningFromNewCli) {
                                Scope.getCurrentScope().getUI().sendMessage(allMessages);
                            }
                        } else {
                            main.liquibaseProLicenseValid = true;
                        }
                    }
                    // 
                    if (licenseService.daysTilExpiration() < 0) {
                        main.liquibaseProLicenseValid = false;
                    }
                    if (!Main.runningFromNewCli) {
                        Scope.getCurrentScope().getUI().sendMessage(licenseService.getLicenseInfo());
                    }
                }
                if (!Main.runningFromNewCli) {
                    Scope.getCurrentScope().getUI().sendMessage(CommandLineUtils.getBanner());
                }
                if (!LiquibaseCommandLineConfiguration.SHOULD_RUN.getCurrentValue()) {
                    Scope.getCurrentScope().getUI().sendErrorMessage((String.format(coreBundle.getString("did.not.run.because.param.was.set.to.false"), LiquibaseCommandLineConfiguration.SHOULD_RUN.getCurrentConfiguredValue().getProvidedValue().getActualKey())));
                    return Integer.valueOf(0);
                }
                if (setupNeeded(main)) {
                    List<String> setupMessages = main.checkSetup();
                    if (!setupMessages.isEmpty()) {
                        main.printHelp(setupMessages, isStandardOutputRequired(main.command) ? System.err : outputStream);
                        return Integer.valueOf(1);
                    }
                }
                // 
                if (StringUtil.isNotEmpty(main.liquibaseHubApiKey)) {
                    DeprecatedConfigurationValueProvider.setData(HubConfiguration.LIQUIBASE_HUB_API_KEY, main.liquibaseHubApiKey);
                }
                // 
                if (StringUtil.isNotEmpty(main.liquibaseHubUrl)) {
                    DeprecatedConfigurationValueProvider.setData(HubConfiguration.LIQUIBASE_HUB_URL, main.liquibaseHubUrl);
                }
                main.applyDefaults();
                Map<String, Object> innerScopeObjects = new HashMap<>();
                innerScopeObjects.put("defaultsFile", LiquibaseCommandLineConfiguration.DEFAULTS_FILE.getCurrentValue());
                if (!Main.runningFromNewCli) {
                    innerScopeObjects.put(Scope.Attr.resourceAccessor.name(), new ClassLoaderResourceAccessor(main.configureClassLoader()));
                }
                Scope.child(innerScopeObjects, () -> {
                    main.doMigration();
                    if (!Main.runningFromNewCli) {
                        if (COMMANDS.UPDATE.equals(main.command)) {
                            Scope.getCurrentScope().getUI().sendMessage(coreBundle.getString("update.successful"));
                        } else if (main.command.startsWith(COMMANDS.ROLLBACK)) {
                            Scope.getCurrentScope().getUI().sendMessage(coreBundle.getString("rollback.successful"));
                        } else {
                            Scope.getCurrentScope().getUI().sendMessage(String.format(coreBundle.getString("command.successful"), main.command));
                        }
                    }
                });
            } catch (Throwable e) {
                String message = e.getMessage();
                if (e.getCause() != null) {
                    message = e.getCause().getMessage();
                }
                if (message == null) {
                    message = coreBundle.getString("unknown.reason");
                }
                // trace because the logger already did that upstream.
                try {
                    if (e.getCause() instanceof ValidationFailedException) {
                        ((ValidationFailedException) e.getCause()).printDescriptiveError(outputStream);
                    } else {
                        if (!Main.runningFromNewCli) {
                            if (main.outputsLogMessages) {
                                Scope.getCurrentScope().getUI().sendErrorMessage((String.format(coreBundle.getString("unexpected.error"), message)), e);
                            } else {
                                Scope.getCurrentScope().getUI().sendMessage((String.format(coreBundle.getString("unexpected.error"), message)));
                                Scope.getCurrentScope().getUI().sendMessage(coreBundle.getString("for.more.information.use.loglevel.flag"));
                                // send it to the LOG in case we're using logFile
                                Scope.getCurrentScope().getLog(getClass()).severe((String.format(coreBundle.getString("unexpected.error"), message)), e);
                            }
                        }
                    }
                } catch (IllegalFormatException e1) {
                    if (Main.runningFromNewCli) {
                        throw e1;
                    }
                    e1.printStackTrace();
                }
                throw new LiquibaseException(String.format(coreBundle.getString("unexpected.error"), message), e);
            }
            if (isHubEnabled(main.command) && HubConfiguration.LIQUIBASE_HUB_API_KEY.getCurrentValue() != null && !Scope.getCurrentScope().getSingleton(HubServiceFactory.class).isOnline()) {
                Scope.getCurrentScope().getUI().sendMessage("WARNING: The command " + main.command + " operations were not synced with your Liquibase Hub account because: " + StringUtil.lowerCaseFirst(Scope.getCurrentScope().getSingleton(HubServiceFactory.class).getOfflineReason()));
            }
            return Integer.valueOf(0);
        }
    });
}
Also used : IntegrationDetails(liquibase.integration.IntegrationDetails) Logger(liquibase.logging.Logger) JavaLogService(liquibase.logging.core.JavaLogService) HubServiceFactory(liquibase.hub.HubServiceFactory) ParseException(java.text.ParseException) CommandFailedException(liquibase.command.CommandFailedException) MalformedURLException(java.net.MalformedURLException) CommandScope(liquibase.command.CommandScope) java.util(java.util) ConsoleUIService(liquibase.ui.ConsoleUIService) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor)

Aggregations

IntegrationDetails (liquibase.integration.IntegrationDetails)6 Field (java.lang.reflect.Field)2 MalformedURLException (java.net.MalformedURLException)2 URLClassLoader (java.net.URLClassLoader)1 ParseException (java.text.ParseException)1 java.util (java.util)1 CommandFailedException (liquibase.command.CommandFailedException)1 CommandScope (liquibase.command.CommandScope)1 LiquibaseConfiguration (liquibase.configuration.LiquibaseConfiguration)1 Database (liquibase.database.Database)1 DatabaseConnection (liquibase.database.DatabaseConnection)1 JdbcConnection (liquibase.database.jvm.JdbcConnection)1 DatabaseException (liquibase.exception.DatabaseException)1 LiquibaseException (liquibase.exception.LiquibaseException)1 UnexpectedLiquibaseException (liquibase.exception.UnexpectedLiquibaseException)1 HubServiceFactory (liquibase.hub.HubServiceFactory)1 Logger (liquibase.logging.Logger)1 JavaLogService (liquibase.logging.core.JavaLogService)1 ClassLoaderResourceAccessor (liquibase.resource.ClassLoaderResourceAccessor)1 ConsoleUIService (liquibase.ui.ConsoleUIService)1