Search in sources :

Example 1 with ChangeLogSerializer

use of liquibase.serializer.ChangeLogSerializer in project liquibase by liquibase.

the class ConvertCommand method run.

@Override
protected CommandResult run() throws Exception {
    List<ResourceAccessor> openers = new ArrayList<ResourceAccessor>();
    openers.add(new FileSystemResourceAccessor());
    openers.add(new ClassLoaderResourceAccessor());
    if (classpath != null) {
        openers.add(new FileSystemResourceAccessor(classpath));
    }
    ResourceAccessor resourceAccessor = new CompositeResourceAccessor(openers);
    ChangeLogParser sourceParser = ChangeLogParserFactory.getInstance().getParser(src, resourceAccessor);
    ChangeLogSerializer outSerializer = ChangeLogSerializerFactory.getInstance().getSerializer(out);
    DatabaseChangeLog changeLog = sourceParser.parse(src, new ChangeLogParameters(), resourceAccessor);
    File outFile = new File(out);
    if (!outFile.exists()) {
        outFile.getParentFile().mkdirs();
    }
    FileOutputStream outputStream = new FileOutputStream(outFile);
    try {
        outSerializer.write(changeLog.getChangeSets(), outputStream);
    } finally {
        outputStream.flush();
        outputStream.close();
    }
    return new CommandResult("Converted successfully");
}
Also used : CompositeResourceAccessor(liquibase.resource.CompositeResourceAccessor) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) ResourceAccessor(liquibase.resource.ResourceAccessor) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) ArrayList(java.util.ArrayList) ChangeLogSerializer(liquibase.serializer.ChangeLogSerializer) DatabaseChangeLog(liquibase.changelog.DatabaseChangeLog) CommandResult(liquibase.command.CommandResult) CompositeResourceAccessor(liquibase.resource.CompositeResourceAccessor) ChangeLogParameters(liquibase.changelog.ChangeLogParameters) ChangeLogParser(liquibase.parser.ChangeLogParser) FileOutputStream(java.io.FileOutputStream) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) File(java.io.File)

Example 2 with ChangeLogSerializer

use of liquibase.serializer.ChangeLogSerializer in project liquibase by liquibase.

the class HubChangeExecListener method updateHubForRollback.

// 
// Send an update message to Hub for this change set rollback
// 
private void updateHubForRollback(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database, String operationStatusType, String statusMessage) {
    if (operation == null) {
        String apiKey = StringUtil.trimToNull(HubConfiguration.LIQUIBASE_HUB_API_KEY.getCurrentValue());
        boolean hubOn = HubConfiguration.LIQUIBASE_HUB_MODE.getCurrentValue() != HubConfiguration.HubMode.OFF;
        if (apiKey != null && hubOn) {
            String message = "Hub communication failure.\n" + "The data for operation on changeset '" + changeSet.getId() + "' by author '" + changeSet.getAuthor() + "'\n" + "was not successfully recorded in your Liquibase Hub project";
            Scope.getCurrentScope().getUI().sendMessage(message);
            logger.info(message);
        }
        return;
    }
    HubChangeLog hubChangeLog;
    final HubService hubService = Scope.getCurrentScope().getSingleton(HubServiceFactory.class).getService();
    try {
        hubChangeLog = hubService.getHubChangeLog(UUID.fromString(databaseChangeLog.getChangeLogId()));
        if (hubChangeLog == null) {
            logger.warning("The changelog '" + databaseChangeLog.getPhysicalFilePath() + "' has not been registered with Hub");
            return;
        }
    } catch (LiquibaseHubException lhe) {
        logger.warning("The changelog '" + databaseChangeLog.getPhysicalFilePath() + "' has not been registered with Hub");
        return;
    }
    Date dateExecuted = new Date();
    // 
    // POST /organizations/{id}/projects/{id}/operations/{id}/change-events
    // 
    OperationChangeEvent operationChangeEvent = new OperationChangeEvent();
    operationChangeEvent.setEventType("ROLLBACK");
    operationChangeEvent.setStartDate(startDateMap.get(changeSet));
    operationChangeEvent.setEndDate(dateExecuted);
    operationChangeEvent.setDateExecuted(dateExecuted);
    operationChangeEvent.setChangesetId(changeSet.getId());
    operationChangeEvent.setChangesetFilename(changeSet.getFilePath());
    operationChangeEvent.setChangesetAuthor(changeSet.getAuthor());
    List<String> sqlList = new ArrayList<>();
    try {
        if (rollbackScriptContents != null) {
            sqlList.add(rollbackScriptContents);
        } else if (changeSet.hasCustomRollbackChanges()) {
            List<Change> changes = changeSet.getRollback().getChanges();
            for (Change change : changes) {
                SqlStatement[] statements = change.generateStatements(database);
                for (SqlStatement statement : statements) {
                    for (Sql sql : SqlGeneratorFactory.getInstance().generateSql(statement, database)) {
                        sqlList.add(sql.toSql());
                    }
                }
            }
        } else {
            List<Change> changes = changeSet.getChanges();
            for (Change change : changes) {
                SqlStatement[] statements = change.generateRollbackStatements(database);
                for (SqlStatement statement : statements) {
                    for (Sql sql : SqlGeneratorFactory.getInstance().generateSql(statement, database)) {
                        sqlList.add(sql.toSql());
                    }
                }
            }
        }
    } catch (LiquibaseException lbe) {
        logger.warning(lbe.getMessage());
    }
    String[] sqlArray = new String[sqlList.size()];
    sqlArray = sqlList.toArray(sqlArray);
    operationChangeEvent.setGeneratedSql(sqlArray);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ChangeLogSerializer serializer = ChangeLogSerializerFactory.getInstance().getSerializer(".json");
    try {
        serializer.write(Collections.singletonList(changeSet), baos);
        operationChangeEvent.setChangesetBody(baos.toString("UTF-8"));
    } catch (IOException ioe) {
    // 
    // Consume
    // 
    }
    operationChangeEvent.setOperationStatusType(operationStatusType);
    operationChangeEvent.setStatusMessage(statusMessage);
    if ("FAIL".equals(operationStatusType)) {
        operationChangeEvent.setLogs(statusMessage);
    } else {
        String logs = getCurrentLog();
        if (!StringUtil.isEmpty(logs)) {
            operationChangeEvent.setLogs(logs);
        } else {
            operationChangeEvent.setLogs(statusMessage);
        }
    }
    operationChangeEvent.setLogsTimestamp(new Date());
    operationChangeEvent.setProject(hubChangeLog.getProject());
    operationChangeEvent.setOperation(operation);
    try {
        hubService.sendOperationChangeEvent(operationChangeEvent);
        postCount++;
    } catch (LiquibaseException lbe) {
        logger.warning(lbe.getMessage(), lbe);
        logger.warning("Unable to send Operation Change Event for operation '" + operation.getId().toString() + " change set '" + changeSet.toString(false));
    }
}
Also used : HubServiceFactory(liquibase.hub.HubServiceFactory) ChangeLogSerializer(liquibase.serializer.ChangeLogSerializer) Change(liquibase.change.Change) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Sql(liquibase.sql.Sql) SqlStatement(liquibase.statement.SqlStatement) LiquibaseHubException(liquibase.hub.LiquibaseHubException) HubChangeLog(liquibase.hub.model.HubChangeLog) OperationChangeEvent(liquibase.hub.model.OperationChangeEvent) LiquibaseException(liquibase.exception.LiquibaseException) HubService(liquibase.hub.HubService)

Example 3 with ChangeLogSerializer

use of liquibase.serializer.ChangeLogSerializer in project liquibase by liquibase.

the class HubChangeExecListener method updateHub.

// 
// Send an update message to Hub for this change set
// 
private void updateHub(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database, String eventType, String operationStatusType, String statusMessage) {
    // 
    if (operation == null) {
        String apiKey = StringUtil.trimToNull(HubConfiguration.LIQUIBASE_HUB_API_KEY.getCurrentValueObfuscated());
        boolean hubOn = HubConfiguration.LIQUIBASE_HUB_MODE.getCurrentValue() != HubConfiguration.HubMode.OFF;
        if (apiKey != null && hubOn) {
            String message;
            if (databaseChangeLog.getChangeLogId() == null) {
                message = "The changelog '" + databaseChangeLog.getPhysicalFilePath() + "' has not been registered with Liquibase Hub.\n" + "To register the changelog with your Hub Project run 'liquibase registerChangeLog'.\n" + "Learn more at https://hub.liquibase.com.";
            } else {
                message = "The changelog file specified is not registered with any Liquibase Hub project, so the results will not be recorded in Liquibase Hub.\n" + "To register the changelog with your Hub Project run 'liquibase registerChangeLog'.\n" + "Learn more at https://hub.liquibase.com.";
            }
            Scope.getCurrentScope().getUI().sendMessage(message);
            logger.info(message);
        }
        return;
    }
    HubChangeLog hubChangeLog;
    final HubService hubService = Scope.getCurrentScope().getSingleton(HubServiceFactory.class).getService();
    try {
        hubChangeLog = hubService.getHubChangeLog(UUID.fromString(databaseChangeLog.getChangeLogId()));
        if (hubChangeLog == null) {
            logger.warning("The changelog '" + databaseChangeLog.getPhysicalFilePath() + "' has not been registered with Hub");
            return;
        }
    } catch (LiquibaseHubException lhe) {
        logger.warning("The changelog '" + databaseChangeLog.getPhysicalFilePath() + "' has not been registered with Hub");
        return;
    }
    // 
    // POST /organizations/{id}/projects/{id}/operations/{id}/change-events
    // Do not send generated SQL or changeset body for changeLogSync operation
    // 
    OperationChangeEvent operationChangeEvent = new OperationChangeEvent();
    List<String> sqlList = new ArrayList<>();
    if (!eventType.equals("SYNC")) {
        List<Change> changes = changeSet.getChanges();
        for (Change change : changes) {
            try {
                Sql[] sqls = SqlGeneratorFactory.getInstance().generateSql(change, database);
                for (Sql sql : sqls) {
                    sqlList.add(sql.toSql());
                }
            } catch (Exception e) {
                logger.warning("Unable to generate SQL for Hub failure message: " + e.getMessage());
            }
        }
        String[] sqlArray = new String[sqlList.size()];
        sqlArray = sqlList.toArray(sqlArray);
        operationChangeEvent.setGeneratedSql(sqlArray);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ChangeLogSerializer serializer = ChangeLogSerializerFactory.getInstance().getSerializer(".json");
        try {
            serializer.write(Collections.singletonList(changeSet), baos);
            operationChangeEvent.setChangesetBody(baos.toString("UTF-8"));
        } catch (IOException ioe) {
            // 
            // Just log message
            // 
            logger.warning("Unable to serialize change set '" + changeSet.toString(false) + "' for Hub.");
        }
    }
    Date dateExecuted = new Date();
    String[] sqlArray = new String[sqlList.size()];
    sqlArray = sqlList.toArray(sqlArray);
    operationChangeEvent.setEventType(eventType);
    operationChangeEvent.setStartDate(startDateMap.get(changeSet));
    operationChangeEvent.setEndDate(dateExecuted);
    operationChangeEvent.setDateExecuted(dateExecuted);
    operationChangeEvent.setChangesetId(changeSet.getId());
    operationChangeEvent.setChangesetFilename(changeSet.getFilePath());
    operationChangeEvent.setChangesetAuthor(changeSet.getAuthor());
    operationChangeEvent.setOperationStatusType(operationStatusType);
    operationChangeEvent.setStatusMessage(statusMessage);
    operationChangeEvent.setGeneratedSql(sqlArray);
    operationChangeEvent.setOperation(operation);
    operationChangeEvent.setLogsTimestamp(new Date());
    if ("FAIL".equals(operationStatusType)) {
        operationChangeEvent.setLogs(statusMessage);
    } else {
        String logs = getCurrentLog();
        if (!StringUtil.isEmpty(logs)) {
            operationChangeEvent.setLogs(logs);
        } else {
            operationChangeEvent.setLogs(statusMessage);
        }
    }
    operationChangeEvent.setProject(hubChangeLog.getProject());
    operationChangeEvent.setOperation(operation);
    try {
        hubService.sendOperationChangeEvent(operationChangeEvent);
        postCount++;
    } catch (LiquibaseException lbe) {
        logger.warning(lbe.getMessage(), lbe);
        logger.warning("Unable to send Operation Change Event for operation '" + operation.getId().toString() + " change set '" + changeSet.toString(false));
        failedToPostCount++;
    }
}
Also used : HubServiceFactory(liquibase.hub.HubServiceFactory) ChangeLogSerializer(liquibase.serializer.ChangeLogSerializer) Change(liquibase.change.Change) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) LiquibaseHubException(liquibase.hub.LiquibaseHubException) PreconditionErrorException(liquibase.exception.PreconditionErrorException) IOException(java.io.IOException) PreconditionFailedException(liquibase.exception.PreconditionFailedException) LiquibaseException(liquibase.exception.LiquibaseException) Sql(liquibase.sql.Sql) LiquibaseHubException(liquibase.hub.LiquibaseHubException) HubChangeLog(liquibase.hub.model.HubChangeLog) OperationChangeEvent(liquibase.hub.model.OperationChangeEvent) LiquibaseException(liquibase.exception.LiquibaseException) HubService(liquibase.hub.HubService)

Example 4 with ChangeLogSerializer

use of liquibase.serializer.ChangeLogSerializer in project liquibase by liquibase.

the class ConvertCommandStep method run.

@Override
public void run(CommandResultsBuilder resultsBuilder) throws Exception {
    CommandScope commandScope = resultsBuilder.getCommandScope();
    String src = commandScope.getArgumentValue(SRC_ARG);
    String out = commandScope.getArgumentValue(OUT_ARG);
    String classpath = commandScope.getArgumentValue(CLASSPATH_ARG);
    List<ResourceAccessor> openers = new ArrayList<>();
    openers.add(new FileSystemResourceAccessor());
    openers.add(new ClassLoaderResourceAccessor());
    if (classpath != null) {
        openers.add(new FileSystemResourceAccessor(new File(classpath)));
    }
    ResourceAccessor resourceAccessor = new CompositeResourceAccessor(openers);
    ChangeLogParser sourceParser = ChangeLogParserFactory.getInstance().getParser(src, resourceAccessor);
    ChangeLogSerializer outSerializer = ChangeLogSerializerFactory.getInstance().getSerializer(out);
    DatabaseChangeLog changeLog = sourceParser.parse(src, new ChangeLogParameters(), resourceAccessor);
    File outFile = new File(out);
    if (!outFile.exists()) {
        outFile.getParentFile().mkdirs();
    }
    try (FileOutputStream outputStream = new FileOutputStream(outFile)) {
        outSerializer.write(changeLog.getChangeSets(), outputStream);
    }
    Scope.getCurrentScope().getUI().sendMessage("Converted successfully");
}
Also used : CompositeResourceAccessor(liquibase.resource.CompositeResourceAccessor) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) ResourceAccessor(liquibase.resource.ResourceAccessor) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) ArrayList(java.util.ArrayList) ChangeLogSerializer(liquibase.serializer.ChangeLogSerializer) DatabaseChangeLog(liquibase.changelog.DatabaseChangeLog) CompositeResourceAccessor(liquibase.resource.CompositeResourceAccessor) ChangeLogParameters(liquibase.changelog.ChangeLogParameters) ChangeLogParser(liquibase.parser.ChangeLogParser) FileOutputStream(java.io.FileOutputStream) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) File(java.io.File)

Example 5 with ChangeLogSerializer

use of liquibase.serializer.ChangeLogSerializer in project liquibase by liquibase.

the class DiffDatabaseToChangeLogTask method executeWithLiquibaseClassloader.

@Override
protected void executeWithLiquibaseClassloader() throws BuildException {
    for (ChangeLogOutputFile changeLogOutputFile : changeLogOutputFiles) {
        PrintStream printStream = null;
        String encoding = getOutputEncoding(changeLogOutputFile);
        try {
            FileResource outputFile = changeLogOutputFile.getOutputFile();
            ChangeLogSerializer changeLogSerializer = changeLogOutputFile.getChangeLogSerializer();
            printStream = new PrintStream(outputFile.getOutputStream(), true, encoding);
            DiffResult diffResult = getDiffResult();
            DiffOutputControl diffOutputControl = getDiffOutputControl();
            DiffToChangeLog diffToChangeLog = new DiffToChangeLog(diffResult, diffOutputControl);
            diffToChangeLog.print(printStream, changeLogSerializer);
        } catch (UnsupportedEncodingException e) {
            throw new BuildException("Unable to diff databases to change log file. Encoding [" + encoding + "] is not supported.", e);
        } catch (IOException e) {
            throw new BuildException("Unable to diff databases to change log file. Error creating output stream.", e);
        } catch (ParserConfigurationException e) {
            throw new BuildException("Unable to diff databases to change log file. Error configuring parser.", e);
        } catch (DatabaseException e) {
            throw new BuildException("Unable to diff databases to change log file: " + e.getMessage(), e);
        } finally {
            FileUtils.close(printStream);
        }
    }
}
Also used : PrintStream(java.io.PrintStream) FileResource(org.apache.tools.ant.types.resources.FileResource) DiffOutputControl(liquibase.diff.output.DiffOutputControl) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ChangeLogSerializer(liquibase.serializer.ChangeLogSerializer) JsonChangeLogSerializer(liquibase.serializer.core.json.JsonChangeLogSerializer) StringChangeLogSerializer(liquibase.serializer.core.string.StringChangeLogSerializer) IOException(java.io.IOException) ChangeLogOutputFile(liquibase.integration.ant.type.ChangeLogOutputFile) DiffToChangeLog(liquibase.diff.output.changelog.DiffToChangeLog) DiffResult(liquibase.diff.DiffResult) BuildException(org.apache.tools.ant.BuildException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) DatabaseException(liquibase.exception.DatabaseException)

Aggregations

ChangeLogSerializer (liquibase.serializer.ChangeLogSerializer)7 IOException (java.io.IOException)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 File (java.io.File)2 FileOutputStream (java.io.FileOutputStream)2 PrintStream (java.io.PrintStream)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 ArrayList (java.util.ArrayList)2 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)2 Change (liquibase.change.Change)2 ChangeLogParameters (liquibase.changelog.ChangeLogParameters)2 DatabaseChangeLog (liquibase.changelog.DatabaseChangeLog)2 DiffOutputControl (liquibase.diff.output.DiffOutputControl)2 DiffToChangeLog (liquibase.diff.output.changelog.DiffToChangeLog)2 DatabaseException (liquibase.exception.DatabaseException)2 LiquibaseException (liquibase.exception.LiquibaseException)2 HubService (liquibase.hub.HubService)2 HubServiceFactory (liquibase.hub.HubServiceFactory)2 LiquibaseHubException (liquibase.hub.LiquibaseHubException)2 HubChangeLog (liquibase.hub.model.HubChangeLog)2