Search in sources :

Example 31 with ClassLoaderResourceAccessor

use of liquibase.resource.ClassLoaderResourceAccessor 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)

Example 32 with ClassLoaderResourceAccessor

use of liquibase.resource.ClassLoaderResourceAccessor in project liquibase by liquibase.

the class AbstractLiquibaseChangeLogMojo method getResourceAccessor.

@Override
protected ResourceAccessor getResourceAccessor(ClassLoader cl) {
    List<ResourceAccessor> resourceAccessors = new ArrayList<ResourceAccessor>();
    resourceAccessors.add(new MavenResourceAccessor(cl));
    resourceAccessors.add(new FileSystemResourceAccessor(project.getBasedir()));
    resourceAccessors.add(new ClassLoaderResourceAccessor(getClass().getClassLoader()));
    if (changeLogDirectory != null) {
        calculateChangeLogDirectoryAbsolutePath();
        resourceAccessors.add(new FileSystemResourceAccessor(new File(changeLogDirectory)));
    }
    return new CompositeResourceAccessor(resourceAccessors);
}
Also used : CompositeResourceAccessor(liquibase.resource.CompositeResourceAccessor) CompositeResourceAccessor(liquibase.resource.CompositeResourceAccessor) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) ResourceAccessor(liquibase.resource.ResourceAccessor) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) ArrayList(java.util.ArrayList) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) File(java.io.File)

Example 33 with ClassLoaderResourceAccessor

use of liquibase.resource.ClassLoaderResourceAccessor in project collect by openforis.

the class ExternalCodeListIntegrationTest method before.

@SuppressWarnings("deprecation")
@Before
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public void before() throws IdmlParseException, IOException, SurveyImportException, SQLException, LiquibaseException, SurveyValidationException {
    SQLiteDatabase database = new SQLiteDatabase();
    Connection connection = DataSourceUtils.getConnection(transactionAwareDataSource);
    database.setConnection(new JdbcConnection(connection));
    Liquibase liquibase = new Liquibase(LIQUIBASE_CHANGELOG, new ClassLoaderResourceAccessor(), database);
    liquibase.update((String) null);
    survey = loadSurvey();
    createHierarchicalTestList();
    createFlatTestList();
    surveyManager.importModel(survey);
}
Also used : Liquibase(liquibase.Liquibase) SQLiteDatabase(liquibase.database.core.SQLiteDatabase) Connection(java.sql.Connection) JdbcConnection(liquibase.database.jvm.JdbcConnection) JdbcConnection(liquibase.database.jvm.JdbcConnection) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) Before(org.junit.Before) Transactional(org.springframework.transaction.annotation.Transactional)

Example 34 with ClassLoaderResourceAccessor

use of liquibase.resource.ClassLoaderResourceAccessor in project drill by apache.

the class RdbmsMetastore method initTables.

/**
 * Initializes RDBMS Metastore tables structure based on {@link #LIQUIBASE_CHANGELOG_FILE} file.
 * See <a href="https://www.liquibase.org/documentation/core-concepts/index.html"> for more details.
 *
 * @param dataSource data source
 */
private void initTables(DataSource dataSource) {
    try (Connection connection = dataSource.getConnection()) {
        JdbcConnection jdbcConnection = new JdbcConnection(connection);
        Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(jdbcConnection);
        ClassLoaderResourceAccessor resourceAccessor = new ClassLoaderResourceAccessor();
        try (Liquibase liquibase = new Liquibase(LIQUIBASE_CHANGELOG_FILE, resourceAccessor, database)) {
            liquibase.update("");
        }
    } catch (Exception e) {
        throw new RdbmsMetastoreException("Unable to init Metastore tables using Liquibase: " + e.getMessage(), e);
    }
}
Also used : Liquibase(liquibase.Liquibase) RdbmsMetastoreException(org.apache.drill.metastore.rdbms.exception.RdbmsMetastoreException) Connection(java.sql.Connection) JdbcConnection(liquibase.database.jvm.JdbcConnection) Database(liquibase.database.Database) JdbcConnection(liquibase.database.jvm.JdbcConnection) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) RdbmsMetastoreException(org.apache.drill.metastore.rdbms.exception.RdbmsMetastoreException)

Example 35 with ClassLoaderResourceAccessor

use of liquibase.resource.ClassLoaderResourceAccessor in project microservice_framework by CJSCommonPlatform.

the class SnapshotAwareAggregateServiceIT method initEventDatabase.

private void initEventDatabase() throws Exception {
    final Liquibase eventStoreLiquibase = new Liquibase(LIQUIBASE_EVENT_STORE_CHANGELOG_XML, new ClassLoaderResourceAccessor(), new JdbcConnection(dataSource.getConnection()));
    eventStoreLiquibase.dropAll();
    eventStoreLiquibase.update("");
    final Liquibase snapshotLiquidBase = new Liquibase(LIQUIBASE_SNAPSHOT_STORE_CHANGELOG_XML, new ClassLoaderResourceAccessor(), new JdbcConnection(dataSource.getConnection()));
    snapshotLiquidBase.update("");
}
Also used : Liquibase(liquibase.Liquibase) JdbcConnection(liquibase.database.jvm.JdbcConnection) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor)

Aggregations

ClassLoaderResourceAccessor (liquibase.resource.ClassLoaderResourceAccessor)38 Liquibase (liquibase.Liquibase)25 JdbcConnection (liquibase.database.jvm.JdbcConnection)20 SQLException (java.sql.SQLException)11 CompositeResourceAccessor (liquibase.resource.CompositeResourceAccessor)9 Database (liquibase.database.Database)8 LiquibaseException (liquibase.exception.LiquibaseException)8 Connection (java.sql.Connection)7 DatabaseException (liquibase.exception.DatabaseException)7 FileSystemResourceAccessor (liquibase.resource.FileSystemResourceAccessor)7 ResourceAccessor (liquibase.resource.ResourceAccessor)7 File (java.io.File)6 ArrayList (java.util.ArrayList)3 Contexts (liquibase.Contexts)3 FileOutputStream (java.io.FileOutputStream)2 DataSource (javax.sql.DataSource)2 ChangeLogParameters (liquibase.changelog.ChangeLogParameters)2 ChangeSet (liquibase.changelog.ChangeSet)2 DatabaseChangeLog (liquibase.changelog.DatabaseChangeLog)2 DatabaseConnection (liquibase.database.DatabaseConnection)2