Search in sources :

Example 1 with Scope

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

use of liquibase.Scope in project liquibase by liquibase.

the class DiffToChangeLog method print.

public void print(String changeLogFile, ChangeLogSerializer changeLogSerializer) throws ParserConfigurationException, IOException, DatabaseException {
    this.changeSetPath = changeLogFile;
    File file = new File(changeLogFile);
    final Map<String, Object> newScopeObjects = new HashMap<>();
    File objectsDir = null;
    if (changeLogFile.toLowerCase().endsWith("sql")) {
        DeprecatedConfigurationValueProvider.setData("liquibase.pro.sql.inline", "true");
    } else if (this.diffResult.getComparisonSnapshot() instanceof EmptyDatabaseSnapshot) {
        objectsDir = new File(file.getParentFile(), "objects");
    } else {
        objectsDir = new File(file.getParentFile(), "objects-" + new Date().getTime());
    }
    if (objectsDir != null) {
        if (objectsDir.exists()) {
            throw new UnexpectedLiquibaseException("The generatechangelog command would overwrite your existing stored logic files. To run this command please remove or rename the '" + objectsDir.getCanonicalPath() + "' dir in your local project directory");
        }
        newScopeObjects.put(EXTERNAL_FILE_DIR_SCOPE_KEY, objectsDir);
    }
    newScopeObjects.put(DIFF_OUTPUT_CONTROL_SCOPE_KEY, diffOutputControl);
    try {
        // 
        // Get a Database instance and save it in the scope for later use
        // 
        DatabaseSnapshot snapshot = diffResult.getReferenceSnapshot();
        Database database = determineDatabase(diffResult.getReferenceSnapshot());
        if (database == null) {
            database = determineDatabase(diffResult.getComparisonSnapshot());
        }
        newScopeObjects.put(DIFF_SNAPSHOT_DATABASE, database);
        Scope.child(newScopeObjects, new Scope.ScopedRunner() {

            @Override
            public void run() {
                try {
                    if (!file.exists()) {
                        // print changeLog only if there are available changeSets to print instead of printing it always
                        printNew(changeLogSerializer, file);
                    } else {
                        Scope.getCurrentScope().getLog(getClass()).info(file + " exists, appending");
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        print(new PrintStream(out, true, GlobalConfiguration.OUTPUT_FILE_ENCODING.getCurrentValue()), changeLogSerializer);
                        String xml = new String(out.toByteArray(), GlobalConfiguration.OUTPUT_FILE_ENCODING.getCurrentValue());
                        String innerXml = xml.replaceFirst("(?ms).*<databaseChangeLog[^>]*>", "");
                        innerXml = innerXml.replaceFirst(DATABASE_CHANGE_LOG_CLOSING_XML_TAG, "");
                        innerXml = innerXml.trim();
                        if ("".equals(innerXml)) {
                            Scope.getCurrentScope().getLog(getClass()).info("No changes found, nothing to do");
                            return;
                        }
                        try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw")) {
                            String line;
                            long offset = 0;
                            boolean foundEndTag = false;
                            while ((line = randomAccessFile.readLine()) != null) {
                                int index = line.indexOf(DATABASE_CHANGE_LOG_CLOSING_XML_TAG);
                                if (index >= 0) {
                                    foundEndTag = true;
                                    break;
                                } else {
                                    offset = randomAccessFile.getFilePointer();
                                }
                            }
                            String lineSeparator = GlobalConfiguration.OUTPUT_LINE_SEPARATOR.getCurrentValue();
                            if (foundEndTag) {
                                randomAccessFile.seek(offset);
                                randomAccessFile.writeBytes("    ");
                                randomAccessFile.write(innerXml.getBytes(GlobalConfiguration.OUTPUT_FILE_ENCODING.getCurrentValue()));
                                randomAccessFile.writeBytes(lineSeparator);
                                randomAccessFile.writeBytes(DATABASE_CHANGE_LOG_CLOSING_XML_TAG + lineSeparator);
                            } else {
                                randomAccessFile.seek(0);
                                long length = randomAccessFile.length();
                                randomAccessFile.seek(length);
                                randomAccessFile.write(xml.getBytes(GlobalConfiguration.OUTPUT_FILE_ENCODING.getCurrentValue()));
                            }
                        }
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });
    } catch (Exception e) {
        // rethrow known exceptions. TODO: Fix this up with final Scope API
        final Throwable cause = e.getCause();
        if (cause instanceof ParserConfigurationException) {
            throw (ParserConfigurationException) cause;
        }
        if (cause instanceof IOException) {
            throw (IOException) cause;
        }
        if (cause instanceof DatabaseException) {
            throw (DatabaseException) cause;
        }
        throw new RuntimeException(e);
    }
}
Also used : UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) DatabaseException(liquibase.exception.DatabaseException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Scope(liquibase.Scope) EmptyDatabaseSnapshot(liquibase.snapshot.EmptyDatabaseSnapshot) DatabaseObject(liquibase.structure.DatabaseObject) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) DatabaseSnapshot(liquibase.snapshot.DatabaseSnapshot) EmptyDatabaseSnapshot(liquibase.snapshot.EmptyDatabaseSnapshot) DatabaseException(liquibase.exception.DatabaseException)

Aggregations

Scope (liquibase.Scope)2 java.io (java.io)1 MalformedURLException (java.net.MalformedURLException)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 java.util (java.util)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 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)1 liquibase.command (liquibase.command)1 liquibase.command.core (liquibase.command.core)1 ConfigurationDefinition (liquibase.configuration.ConfigurationDefinition)1 ConfigurationValueProvider (liquibase.configuration.ConfigurationValueProvider)1 ConfiguredValue (liquibase.configuration.ConfiguredValue)1 LiquibaseConfiguration (liquibase.configuration.LiquibaseConfiguration)1