Search in sources :

Example 1 with Project

use of liquibase.hub.model.Project in project liquibase by liquibase.

the class RegisterChangelogCommandStep method getProjectsFromHub.

// 
// Retrieve the projects and sort them by create date
// 
private List<Project> getProjectsFromHub() throws LiquibaseHubException {
    final HubService service = Scope.getCurrentScope().getSingleton(HubServiceFactory.class).getService();
    List<Project> projects = service.getProjects();
    Collections.sort(projects, new Comparator<Project>() {

        @Override
        public int compare(Project o1, Project o2) {
            Date date1 = o1.getCreateDate();
            Date date2 = o2.getCreateDate();
            return date2.compareTo(date1);
        }
    });
    return projects;
}
Also used : Project(liquibase.hub.model.Project) HubServiceFactory(liquibase.hub.HubServiceFactory) HubService(liquibase.hub.HubService)

Example 2 with Project

use of liquibase.hub.model.Project in project liquibase by liquibase.

the class RegisterChangelogCommandStep method readProjectFromConsole.

private String readProjectFromConsole(List<Project> projects, String changeLogFile) throws CommandLineParsingException {
    final UIService ui = Scope.getCurrentScope().getUI();
    StringBuilder prompt = new StringBuilder("Registering a changelog connects Liquibase operations to a Project for monitoring and reporting.\n");
    prompt.append("Register changelog " + changeLogFile + " to an existing Project, or create a new one.\n");
    prompt.append("Please make a selection:\n");
    prompt.append("[c] Create new Project\n");
    String projFormat = "[%d]";
    if (projects.size() >= 10 && projects.size() < 100) {
        projFormat = "[%2d]";
    } else if (projects.size() >= 100 && projects.size() < 1000) {
        projFormat = "[%3d]";
    } else if (projects.size() >= 1000 && projects.size() < 10000) {
        projFormat = "[%4d]";
    }
    int maxLen = 40;
    for (Project project : projects) {
        if (project.getName() != null && project.getName().length() > maxLen) {
            maxLen = project.getName().length();
        }
    }
    for (int i = 0; i < projects.size(); i++) {
        Project project = projects.get(i);
        prompt.append(String.format(projFormat + " %-" + maxLen + "s (Project ID:%s) %s\n", i + 1, project.getName(), projects.get(i).getId(), projects.get(i).getCreateDate()));
    }
    prompt.append("[N] to not register this changelog right now.\n" + "You can still run Liquibase commands, but no data will be saved in your Liquibase Hub account for monitoring or reports.\n" + " Learn more at https://hub.liquibase.com.\n?");
    return StringUtil.trimToEmpty(ui.prompt(prompt.toString(), "N", null, String.class));
}
Also used : Project(liquibase.hub.model.Project) UIService(liquibase.ui.UIService)

Example 3 with Project

use of liquibase.hub.model.Project in project liquibase by liquibase.

the class RegisterChangelogCommandStep method doRegisterChangelog.

public void doRegisterChangelog(String changelogFilepath, UUID hubProjectId, String hubProjectName, CommandResultsBuilder resultsBuilder, boolean skipPromptIfOneProject) throws LiquibaseException, CommandLineParsingException {
    try (PrintWriter output = new PrintWriter(resultsBuilder.getOutputStream())) {
        HubChangeLog hubChangeLog;
        final HubService service = Scope.getCurrentScope().getSingleton(HubServiceFactory.class).getService();
        // 
        // Check for existing changeLog file using the untouched changelog filepath
        // 
        DatabaseChangeLog databaseChangeLog = parseChangeLogFile(changelogFilepath);
        if (databaseChangeLog == null) {
            throw new CommandExecutionException("Cannot parse " + changelogFilepath);
        }
        final String changeLogId = databaseChangeLog.getChangeLogId();
        if (changeLogId != null) {
            hubChangeLog = service.getHubChangeLog(UUID.fromString(changeLogId));
            if (hubChangeLog != null) {
                throw new CommandExecutionException("Changelog '" + changelogFilepath + "' is already registered with changeLogId '" + changeLogId + "' to project '" + hubChangeLog.getProject().getName() + "' with project ID '" + hubChangeLog.getProject().getId().toString() + "'.\n" + "For more information visit https://docs.liquibase.com.", new ChangeLogAlreadyRegisteredException(hubChangeLog));
            } else {
                throw new CommandExecutionException("Changelog '" + changelogFilepath + "' is already registered with changeLogId '" + changeLogId + "'.\n" + "For more information visit https://docs.liquibase.com.", new ChangeLogAlreadyRegisteredException());
            }
        }
        // 
        // Retrieve the projects
        // 
        Project project;
        if (hubProjectId != null) {
            project = service.getProject(hubProjectId);
            if (project == null) {
                throw new CommandExecutionException("Project Id '" + hubProjectId + "' does not exist or you do not have access to it");
            }
        } else if (hubProjectName != null) {
            if (hubProjectName.length() > 255) {
                throw new CommandExecutionException("\nThe project name you gave is longer than 255 characters\n\n");
            }
            project = service.createProject(new Project().setName(hubProjectName));
            if (project == null) {
                throw new CommandExecutionException("Unable to create project '" + hubProjectName + "'.\n" + "Learn more at https://hub.liquibase.com.");
            }
            output.print("\nProject '" + project.getName() + "' created with project ID '" + project.getId() + "'.\n\n");
        } else {
            project = retrieveOrCreateProject(service, changelogFilepath, skipPromptIfOneProject);
            if (project == null) {
                throw new CommandExecutionException("Your changelog " + changelogFilepath + " was not registered to any Liquibase Hub project. You can still run Liquibase commands, but no data will be saved in your Liquibase Hub account for monitoring or reports.  Learn more at https://hub.liquibase.com.");
            }
        }
        // 
        // Go create the Hub Changelog
        // 
        String changelogFilename = Paths.get(databaseChangeLog.getFilePath()).getFileName().toString();
        HubChangeLog newChangeLog = new HubChangeLog();
        newChangeLog.setProject(project);
        newChangeLog.setFileName(changelogFilename);
        newChangeLog.setName(changelogFilename);
        hubChangeLog = service.createChangeLog(newChangeLog);
        // 
        // Update the changelog file
        // Add the registered changelog ID to the results so that
        // the caller can use it
        // 
        ChangelogRewriter.ChangeLogRewriterResult changeLogRewriterResult = ChangelogRewriter.addChangeLogId(changelogFilepath, hubChangeLog.getId().toString(), databaseChangeLog);
        if (changeLogRewriterResult.success) {
            Scope.getCurrentScope().getLog(RegisterChangelogCommandStep.class).info(changeLogRewriterResult.message);
            output.println("* Changelog file '" + changelogFilepath + "' with changelog ID '" + hubChangeLog.getId().toString() + "' has been " + "registered to Project " + project.getName());
            resultsBuilder.addResult("statusCode", 0);
            resultsBuilder.addResult(REGISTERED_CHANGELOG_ID.getName(), hubChangeLog.getId().toString());
        }
    }
}
Also used : Project(liquibase.hub.model.Project) ChangelogRewriter(liquibase.changelog.ChangelogRewriter) ChangeLogAlreadyRegisteredException(liquibase.exception.ChangeLogAlreadyRegisteredException) HubChangeLog(liquibase.hub.model.HubChangeLog) HubServiceFactory(liquibase.hub.HubServiceFactory) CommandExecutionException(liquibase.exception.CommandExecutionException) HubService(liquibase.hub.HubService) DatabaseChangeLog(liquibase.changelog.DatabaseChangeLog) PrintWriter(java.io.PrintWriter)

Example 4 with Project

use of liquibase.hub.model.Project in project liquibase by liquibase.

the class InternalSyncHubCommandStep method run.

@Override
public void run(CommandResultsBuilder resultsBuilder) throws Exception {
    CommandScope commandScope = resultsBuilder.getCommandScope();
    final HubServiceFactory hubServiceFactory = Scope.getCurrentScope().getSingleton(HubServiceFactory.class);
    if (!hubServiceFactory.isOnline()) {
        if (commandScope.getArgumentValue(FAIL_IF_OFFLINE_ARG)) {
            throw new CommandExecutionException("The command syncHub requires access to Liquibase Hub: " + hubServiceFactory.getOfflineReason() + ".  Learn more at https://hub.liquibase.com");
        } else {
            Scope.getCurrentScope().getUI().sendMessage("Sync skipped, offline");
            return;
        }
    }
    // 
    // Check for both connection and project specified
    // unless we have said to favor the connectionID
    // 
    final Boolean favorConnectionId = commandScope.getArgumentValue(CONTINUE_IF_CONNECTION_AND_PROJECT_ID_BOTH_SET_ARG);
    final UUID hubConnectionId = commandScope.getArgumentValue(HUB_CONNECTION_ID_ARG);
    if (!favorConnectionId && hubConnectionId != null && commandScope.getArgumentValue(HUB_PROJECT_ID_ARG) != null) {
        String message = "The syncHub command requires only one valid hubConnectionId or hubProjectId or unique URL. Please remove extra values.";
        Scope.getCurrentScope().getLog(getClass()).severe(message);
        throw new CommandExecutionException(message);
    }
    HubChangeLog hubChangeLog = null;
    final HubService hubService = Scope.getCurrentScope().getSingleton(HubServiceFactory.class).getService();
    Connection connectionToSync;
    if (hubConnectionId == null) {
        Project project = null;
        if (StringUtil.isNotEmpty(commandScope.getArgumentValue(CHANGELOG_FILE_ARG))) {
            final ResourceAccessor resourceAccessor = Scope.getCurrentScope().getResourceAccessor();
            final String changelogFile = commandScope.getArgumentValue(CHANGELOG_FILE_ARG);
            final DatabaseChangeLog databaseChangeLog = ChangeLogParserFactory.getInstance().getParser(changelogFile, resourceAccessor).parse(changelogFile, new ChangeLogParameters(), resourceAccessor);
            final String changeLogId = databaseChangeLog.getChangeLogId();
            if (changeLogId == null) {
                Scope.getCurrentScope().getLog(getClass()).info("Changelog " + changelogFile + " has not been registered with Liquibase Hub. Cannot use it to help determine project.");
            } else {
                hubChangeLog = hubService.getHubChangeLog(UUID.fromString(changeLogId), "*");
                if (hubChangeLog == null) {
                    throw new CommandExecutionException("Changelog " + changelogFile + " has an unrecognized changeLogId.");
                }
                if (hubChangeLog.isDeleted()) {
                    // 
                    // Complain and stop the operation
                    // 
                    String message = "\n" + "The operation did not complete and will not be reported to Hub because the\n" + "" + "registered changelog has been deleted by someone in your organization.\n" + "Learn more at http://hub.liquibase.com";
                    throw new LiquibaseHubException(message);
                }
                project = hubChangeLog.getProject();
            }
        } else if (commandScope.getArgumentValue(HUB_PROJECT_ID_ARG) != null) {
            project = hubService.getProject(commandScope.getArgumentValue(HUB_PROJECT_ID_ARG));
            if (project == null) {
                throw new CommandExecutionException("Project Id '" + commandScope.getArgumentValue(HUB_PROJECT_ID_ARG) + "' does not exist or you do not have access to it");
            }
        } else {
            Scope.getCurrentScope().getLog(getClass()).info("No project, connection, or changeLogFile specified. Searching for jdbcUrl across the entire organization.");
        }
        final String url = commandScope.getArgumentValue(URL_ARG);
        final Connection searchConnection = new Connection().setJdbcUrl(url).setProject(project);
        final List<Connection> connections = hubService.getConnections(searchConnection);
        if (connections.size() == 0) {
            if (project == null) {
                throw new CommandExecutionException("The url " + url + " does not match any defined connections. To auto-create a connection, please specify a 'changeLogFile=<changeLogFileName>' in liquibase.properties or the command line which contains a registered changeLogId.");
            }
            Connection inputConnection = new Connection();
            inputConnection.setJdbcUrl(url);
            inputConnection.setProject(project);
            connectionToSync = hubService.createConnection(inputConnection);
        } else if (connections.size() == 1) {
            connectionToSync = connections.get(0);
        } else {
            throw new CommandExecutionException("The url " + url + " is used by more than one connection. Please specify 'hubConnectionId=<hubConnectionId>' or 'changeLogFile=<changeLogFileName>' in liquibase.properties or the command line.");
        }
    } else {
        final List<Connection> connections = hubService.getConnections(new Connection().setId(hubConnectionId));
        if (connections.size() == 0) {
            throw new CommandExecutionException("Hub connection Id " + hubConnectionId + " was either not found, or you do not have access");
        } else {
            connectionToSync = connections.get(0);
        }
    }
    final Database database = commandScope.getArgumentValue(DATABASE_ARG);
    Scope.child(Scope.Attr.database, database, () -> {
        final ChangeLogHistoryService historyService = ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database);
        final List<RanChangeSet> ranChangeSets = historyService.getRanChangeSets();
        hubService.setRanChangeSets(connectionToSync, ranChangeSets);
    });
    // 
    if (hubChangeLog != null && hubChangeLog.isInactive()) {
        String message = "\n" + "The command completed and reported to Hub, but the changelog has been deactivated by someone in your organization.\n" + "To synchronize your changelog, checkout the latest from source control or run \"deactivatechangelog\".\n" + "After that, commands run against this changelog will not be reported to Hub until \"registerchangelog\" is run again.\n" + "Learn more at http://hub.liquibase.com";
        Scope.getCurrentScope().getLog(HubUpdater.class).warning(message);
        Scope.getCurrentScope().getUI().sendMessage("WARNING: " + message);
    }
}
Also used : ResourceAccessor(liquibase.resource.ResourceAccessor) Connection(liquibase.hub.model.Connection) HubServiceFactory(liquibase.hub.HubServiceFactory) Project(liquibase.hub.model.Project) LiquibaseHubException(liquibase.hub.LiquibaseHubException) HubUpdater(liquibase.hub.HubUpdater) HubChangeLog(liquibase.hub.model.HubChangeLog) Database(liquibase.database.Database) CommandExecutionException(liquibase.exception.CommandExecutionException) UUID(java.util.UUID) HubService(liquibase.hub.HubService)

Example 5 with Project

use of liquibase.hub.model.Project in project liquibase by liquibase.

the class RegisterChangelogCommandStep method retrieveOrCreateProject.

private Project retrieveOrCreateProject(HubService service, String changeLogFile, boolean skipPromptIfOneProject) throws CommandLineParsingException, LiquibaseException, LiquibaseHubException {
    final UIService ui = Scope.getCurrentScope().getUI();
    Project project = null;
    List<Project> projects = getProjectsFromHub();
    if (skipPromptIfOneProject && projects.size() == 1) {
        return projects.get(0);
    }
    boolean done = false;
    String input = null;
    while (!done) {
        input = readProjectFromConsole(projects, changeLogFile);
        try {
            if (input.equalsIgnoreCase("C")) {
                String projectName = readProjectNameFromConsole();
                if (StringUtil.isEmpty(projectName)) {
                    ui.sendMessage("\nNo project created\n");
                    continue;
                } else if (projectName.length() > 255) {
                    ui.sendMessage("\nThe project name you entered is longer than 255 characters\n");
                    continue;
                }
                project = service.createProject(new Project().setName(projectName));
                if (project == null) {
                    throw new CommandExecutionException("Unable to create project '" + projectName + "'.\n\n");
                }
                ui.sendMessage("\nProject '" + project.getName() + "' created with project ID '" + project.getId() + "'.\n");
                projects = getProjectsFromHub();
                done = true;
                continue;
            } else if (input.equalsIgnoreCase("N")) {
                throw new CommandExecutionException("Your changelog " + changeLogFile + " was not registered to any Liquibase Hub project. You can still run Liquibase commands, but no data will be saved in your Liquibase Hub account for monitoring or reports.  Learn more at https://hub.liquibase.com.");
            }
            int projectIdx = Integer.parseInt(input);
            if (projectIdx > 0 && projectIdx <= projects.size()) {
                project = projects.get(projectIdx - 1);
                if (project != null) {
                    done = true;
                }
            } else {
                ui.sendMessage("\nInvalid project '" + projectIdx + "' selected\n");
            }
        } catch (NumberFormatException nfe) {
            ui.sendMessage("\nInvalid selection '" + input + "'\n");
        }
    }
    return project;
}
Also used : Project(liquibase.hub.model.Project) UIService(liquibase.ui.UIService) CommandExecutionException(liquibase.exception.CommandExecutionException)

Aggregations

Project (liquibase.hub.model.Project)5 CommandExecutionException (liquibase.exception.CommandExecutionException)3 HubService (liquibase.hub.HubService)3 HubServiceFactory (liquibase.hub.HubServiceFactory)3 HubChangeLog (liquibase.hub.model.HubChangeLog)2 UIService (liquibase.ui.UIService)2 PrintWriter (java.io.PrintWriter)1 UUID (java.util.UUID)1 ChangelogRewriter (liquibase.changelog.ChangelogRewriter)1 DatabaseChangeLog (liquibase.changelog.DatabaseChangeLog)1 Database (liquibase.database.Database)1 ChangeLogAlreadyRegisteredException (liquibase.exception.ChangeLogAlreadyRegisteredException)1 HubUpdater (liquibase.hub.HubUpdater)1 LiquibaseHubException (liquibase.hub.LiquibaseHubException)1 Connection (liquibase.hub.model.Connection)1 ResourceAccessor (liquibase.resource.ResourceAccessor)1