Search in sources :

Example 1 with ConsoleUIService

use of liquibase.ui.ConsoleUIService in project liquibase by liquibase.

the class LiquibaseCommandLine method configureScope.

/**
 * Configures the system, and returns values to add to Scope.
 *
 * @return values to set in the scope
 */
private Map<String, Object> configureScope() throws Exception {
    Map<String, Object> returnMap = new HashMap<>();
    final ClassLoader classLoader = configureClassLoader();
    returnMap.putAll(configureLogging());
    returnMap.putAll(configureResourceAccessor(classLoader));
    ConsoleUIService ui = null;
    List<UIService> uiServices = Scope.getCurrentScope().getServiceLocator().findInstances(UIService.class);
    for (UIService uiService : uiServices) {
        if (uiService instanceof ConsoleUIService) {
            ui = (ConsoleUIService) uiService;
            break;
        }
    }
    if (ui == null) {
        ui = new ConsoleUIService();
    }
    ui.setAllowPrompt(true);
    ui.setOutputStream(System.err);
    returnMap.put(Scope.Attr.ui.name(), ui);
    returnMap.put(LiquibaseCommandLineConfiguration.ARGUMENT_CONVERTER.getKey(), (LiquibaseCommandLineConfiguration.ArgumentConverter) argument -> "--" + StringUtil.toKabobCase(argument));
    return returnMap;
}
Also used : LicenseService(liquibase.license.LicenseService) java.util.logging(java.util.logging) CommandLineParsingException(liquibase.exception.CommandLineParsingException) java.util(java.util) CompositeResourceAccessor(liquibase.resource.CompositeResourceAccessor) SystemUtil.isWindows(liquibase.util.SystemUtil.isWindows) LicenseServiceFactory(liquibase.license.LicenseServiceFactory) URL(java.net.URL) ConfiguredValue(liquibase.configuration.ConfiguredValue) LogService(liquibase.logging.LogService) ConfigurationValueProvider(liquibase.configuration.ConfigurationValueProvider) URLClassLoader(java.net.URLClassLoader) ConsoleUIService(liquibase.ui.ConsoleUIService) LogMessageFilter(liquibase.logging.LogMessageFilter) Scope(liquibase.Scope) JavaLogService(liquibase.logging.core.JavaLogService) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) CommandLine(picocli.CommandLine) ResourceBundle.getBundle(java.util.ResourceBundle.getBundle) liquibase.command(liquibase.command) liquibase.command.core(liquibase.command.core) MalformedURLException(java.net.MalformedURLException) PrivilegedAction(java.security.PrivilegedAction) LiquibaseUtil(liquibase.util.LiquibaseUtil) StringUtil(liquibase.util.StringUtil) Collectors(java.util.stream.Collectors) ConfigurationDefinition(liquibase.configuration.ConfigurationDefinition) UIService(liquibase.ui.UIService) Stream(java.util.stream.Stream) java.io(java.io) Paths(java.nio.file.Paths) CommandValidationException(liquibase.exception.CommandValidationException) LiquibaseConfiguration(liquibase.configuration.LiquibaseConfiguration) AccessController(java.security.AccessController) DefaultsFileValueProvider(liquibase.configuration.core.DefaultsFileValueProvider) HubConfiguration(liquibase.hub.HubConfiguration) ConsoleUIService(liquibase.ui.ConsoleUIService) URLClassLoader(java.net.URLClassLoader) ConsoleUIService(liquibase.ui.ConsoleUIService) UIService(liquibase.ui.UIService)

Example 2 with ConsoleUIService

use of liquibase.ui.ConsoleUIService in project liquibase by liquibase.

the class Scope method getCurrentScope.

public static Scope getCurrentScope() {
    if (scopeManager == null) {
        scopeManager = new SingletonScopeManager();
    }
    if (scopeManager.getCurrentScope() == null) {
        Scope rootScope = new Scope();
        scopeManager.setCurrentScope(rootScope);
        rootScope.values.put(Attr.logService.name(), new JavaLogService());
        rootScope.values.put(Attr.resourceAccessor.name(), new ClassLoaderResourceAccessor());
        rootScope.values.put(Attr.serviceLocator.name(), new StandardServiceLocator());
        rootScope.values.put(Attr.ui.name(), new ConsoleUIService());
        rootScope.getSingleton(LiquibaseConfiguration.class).init(rootScope);
        LogService overrideLogService = rootScope.getSingleton(LogServiceFactory.class).getDefaultLogService();
        if (overrideLogService == null) {
            throw new UnexpectedLiquibaseException("Cannot find default log service");
        }
        rootScope.values.put(Attr.logService.name(), overrideLogService);
        // check for higher-priority serviceLocator
        ServiceLocator serviceLocator = rootScope.getServiceLocator();
        for (ServiceLocator possibleLocator : serviceLocator.findInstances(ServiceLocator.class)) {
            if (possibleLocator.getPriority() > serviceLocator.getPriority()) {
                serviceLocator = possibleLocator;
            }
        }
        rootScope.values.put(Attr.serviceLocator.name(), serviceLocator);
        rootScope.values.put(Attr.osgiPlatform.name(), Activator.OSGIContainerChecker.isOsgiPlatform());
    }
    return scopeManager.getCurrentScope();
}
Also used : StandardServiceLocator(liquibase.servicelocator.StandardServiceLocator) ServiceLocator(liquibase.servicelocator.ServiceLocator) ConsoleUIService(liquibase.ui.ConsoleUIService) StandardServiceLocator(liquibase.servicelocator.StandardServiceLocator) JavaLogService(liquibase.logging.core.JavaLogService) LiquibaseConfiguration(liquibase.configuration.LiquibaseConfiguration) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) LogServiceFactory(liquibase.logging.core.LogServiceFactory) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) LogService(liquibase.logging.LogService) JavaLogService(liquibase.logging.core.JavaLogService)

Example 3 with ConsoleUIService

use of liquibase.ui.ConsoleUIService 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

JavaLogService (liquibase.logging.core.JavaLogService)3 ConsoleUIService (liquibase.ui.ConsoleUIService)3 MalformedURLException (java.net.MalformedURLException)2 java.util (java.util)2 LiquibaseConfiguration (liquibase.configuration.LiquibaseConfiguration)2 LogService (liquibase.logging.LogService)2 ClassLoaderResourceAccessor (liquibase.resource.ClassLoaderResourceAccessor)2 java.io (java.io)1 URL (java.net.URL)1 URLClassLoader (java.net.URLClassLoader)1 Paths (java.nio.file.Paths)1 AccessController (java.security.AccessController)1 PrivilegedAction (java.security.PrivilegedAction)1 ParseException (java.text.ParseException)1 ResourceBundle.getBundle (java.util.ResourceBundle.getBundle)1 java.util.logging (java.util.logging)1 Collectors (java.util.stream.Collectors)1 Stream (java.util.stream.Stream)1 Scope (liquibase.Scope)1 liquibase.command (liquibase.command)1