Search in sources :

Example 16 with GitLabApi

use of org.gitlab4j.api.GitLabApi in project legend-sdlc by finos.

the class GitLabUserContext method getGitLabAPI.

public GitLabApi getGitLabAPI(GitLabMode mode, boolean redirectAllowed) {
    GitLabApi api = this.apiCache.get(mode);
    if (api == null) {
        if (!isValidMode(mode)) {
            throw new LegendSDLCServerException("GitLab mode " + mode + " is not supported", Status.BAD_REQUEST);
        }
        GitLabSession gitLabSession = getGitLabSession();
        synchronized (this.apiCache) {
            api = this.apiCache.get(mode);
            if (api == null) {
                GitLabModeInfo modeInfo = gitLabSession.getModeInfo(mode);
                GitLabToken token = gitLabSession.getGitLabToken(mode);
                if (token == null) {
                    try {
                        token = authorizerManager.authorize(session, modeInfo);
                    } catch (GitLabOAuthAuthenticator.UserInputRequiredException e) {
                        URI redirectURI = GitLabOAuthAuthenticator.buildAppAuthorizationURI(e.getModeInfo(), this.httpRequest);
                        throw new LegendSDLCServerException(redirectURI.toString(), Status.FOUND);
                    } catch (GitLabAuthFailureException e) {
                        throw new LegendSDLCServerException(e.getMessage(), Status.FORBIDDEN, e);
                    } catch (GitLabAuthException e) {
                        throw new LegendSDLCServerException(e.getMessage(), Status.INTERNAL_SERVER_ERROR, e);
                    }
                    if (token != null) {
                        gitLabSession.putGitLabToken(mode, token);
                        LegendSDLCWebFilter.setSessionCookie(this.httpResponse, gitLabSession);
                    } else if (redirectAllowed) {
                        URI redirectURI = GitLabOAuthAuthenticator.buildAppAuthorizationURI(modeInfo, this.httpRequest);
                        throw new LegendSDLCServerException(redirectURI.toString(), Status.FOUND);
                    } else {
                        throw new LegendSDLCServerException("{\"message\":\"Authorization required\",\"auth_uri\":\"/auth/authorize\"}", Status.FORBIDDEN);
                    }
                }
                api = new GitLabApi(ApiVersion.V4, modeInfo.getServerInfo().getGitLabURLString(), token.getTokenType(), token.getToken());
                this.apiCache.put(mode, api);
            }
        }
    }
    return api;
}
Also used : GitLabApi(org.gitlab4j.api.GitLabApi) LegendSDLCServerException(org.finos.legend.sdlc.server.error.LegendSDLCServerException) GitLabModeInfo(org.finos.legend.sdlc.server.gitlab.mode.GitLabModeInfo) URI(java.net.URI)

Example 17 with GitLabApi

use of org.gitlab4j.api.GitLabApi in project legend-sdlc by finos.

the class GitLabReviewApi method editReview.

@Override
public Review editReview(String projectId, String reviewId, String title, String description, List<String> labels) {
    LegendSDLCServerException.validateNonNull(projectId, "projectId may not be null");
    LegendSDLCServerException.validateNonNull(reviewId, "reviewId may not be null");
    LegendSDLCServerException.validateNonNull(title, "title may not be null");
    LegendSDLCServerException.validateNonNull(description, "description may not be null");
    GitLabProjectId gitLabProjectId = parseProjectId(projectId);
    GitLabApi gitLabApi = getGitLabApi(gitLabProjectId.getGitLabMode());
    MergeRequestApi mergeRequestApi = gitLabApi.getMergeRequestApi();
    MergeRequest mergeRequest = getReviewMergeRequest(mergeRequestApi, gitLabProjectId, reviewId);
    if (!isOpen(mergeRequest)) {
        throw new LegendSDLCServerException("Only open reviews can be edited: state of review " + mergeRequest.getIid() + " in project " + gitLabProjectId.toString() + " is " + getReviewState(mergeRequest));
    }
    try {
        MergeRequestParams mergeRequestParams = new MergeRequestParams().withTitle(title).withDescription(description);
        if (labels != null) {
            mergeRequestParams.withLabels(labels);
        }
        MergeRequest editedRequest = mergeRequestApi.updateMergeRequest(gitLabProjectId.getGitLabId(), mergeRequest.getIid(), mergeRequestParams);
        return fromGitLabMergeRequest(projectId, editedRequest);
    } catch (Exception e) {
        throw buildException(e, () -> "User " + getCurrentUser() + " is not allowed to edit review " + reviewId + " in project " + projectId, () -> "Unknown review in project " + projectId + ": " + reviewId, () -> "Error editing review " + reviewId + " in project " + projectId);
    }
}
Also used : GitLabApi(org.gitlab4j.api.GitLabApi) LegendSDLCServerException(org.finos.legend.sdlc.server.error.LegendSDLCServerException) MergeRequest(org.gitlab4j.api.models.MergeRequest) MergeRequestParams(org.gitlab4j.api.models.MergeRequestParams) GitLabProjectId(org.finos.legend.sdlc.server.gitlab.GitLabProjectId) MergeRequestApi(org.gitlab4j.api.MergeRequestApi) LegendSDLCServerException(org.finos.legend.sdlc.server.error.LegendSDLCServerException) GitLabApiException(org.gitlab4j.api.GitLabApiException)

Example 18 with GitLabApi

use of org.gitlab4j.api.GitLabApi in project legend-sdlc by finos.

the class GitLabRevisionApi method getRevisionStatus.

@Override
public RevisionStatus getRevisionStatus(String projectId, String revisionId) {
    LegendSDLCServerException.validateNonNull(projectId, "projectId may not be null");
    LegendSDLCServerException.validateNonNull(revisionId, "revisionId may not be null");
    GitLabProjectId gitLabProjectId = parseProjectId(projectId);
    try {
        GitLabApi gitLabApi = getGitLabApi(gitLabProjectId.getGitLabMode());
        CommitsApi commitsApi = gitLabApi.getCommitsApi();
        Revision revision = getProjectRevisionContext(projectId).getRevision(revisionId);
        Pager<CommitRef> commitRefPager = withRetries(() -> commitsApi.getCommitRefs(gitLabProjectId.getGitLabId(), revision.getId(), RefType.ALL, ITEMS_PER_PAGE));
        List<CommitRef> commitRefs = PagerTools.stream(commitRefPager).collect(Collectors.toList());
        boolean isCommitted = commitRefs.stream().anyMatch(cr -> MASTER_BRANCH.equals(cr.getName()));
        List<Version> versions;
        List<String> versionTagNames = commitRefs.stream().filter(cr -> (RefType.TAG == cr.getType()) && isVersionTagName(cr.getName())).map(CommitRef::getName).collect(Collectors.toList());
        if (versionTagNames.isEmpty()) {
            versions = Collections.emptyList();
        } else {
            TagsApi tagsApi = gitLabApi.getTagsApi();
            versions = Lists.mutable.ofInitialCapacity(versionTagNames.size());
            for (String tagName : versionTagNames) {
                Tag tag = withRetries(() -> tagsApi.getTag(gitLabProjectId.getGitLabId(), tagName));
                versions.add(fromGitLabTag(projectId, tag));
            }
            versions.sort(Comparator.comparing(Version::getId));
        }
        List<Workspace> workspaces;
        if (isCommitted) {
            workspaces = Collections.emptyList();
        } else {
            // Note that here we will not account for conflict resolution or backup branch because in the model those are not real workspaces.
            workspaces = commitRefs.stream().filter(cr -> (RefType.BRANCH == cr.getType()) && isWorkspaceBranchName(cr.getName(), ProjectFileAccessProvider.WorkspaceAccessType.WORKSPACE)).map(cr -> fromWorkspaceBranchName(projectId, cr.getName(), WorkspaceType.USER, ProjectFileAccessProvider.WorkspaceAccessType.WORKSPACE)).collect(Collectors.toList());
        }
        return new RevisionStatus() {

            @Override
            public Revision getRevision() {
                return revision;
            }

            @Override
            public boolean isCommitted() {
                return isCommitted;
            }

            @Override
            public List<Workspace> getWorkspaces() {
                return workspaces;
            }

            @Override
            public List<Version> getVersions() {
                return versions;
            }
        };
    } catch (Exception e) {
        throw buildException(e, () -> "User " + getCurrentUser() + " is not allowed to access the status for revision " + revisionId + " of project " + projectId, () -> "Unknown: revision " + revisionId + " of project " + projectId, () -> "Error getting the status for revision " + revisionId + " of project " + projectId);
    }
}
Also used : Workspace(org.finos.legend.sdlc.domain.model.project.workspace.Workspace) CommitsApi(org.gitlab4j.api.CommitsApi) Lists(org.eclipse.collections.api.factory.Lists) GitLabUserContext(org.finos.legend.sdlc.server.gitlab.auth.GitLabUserContext) TagsApi(org.gitlab4j.api.TagsApi) MutableList(org.eclipse.collections.api.list.MutableList) CommitRef(org.gitlab4j.api.models.CommitRef) Function(java.util.function.Function) Inject(javax.inject.Inject) LegendSDLCServerException(org.finos.legend.sdlc.server.error.LegendSDLCServerException) ProjectStructure(org.finos.legend.sdlc.server.project.ProjectStructure) Tag(org.gitlab4j.api.models.Tag) PagerTools(org.finos.legend.sdlc.server.gitlab.tools.PagerTools) BackgroundTaskProcessor(org.finos.legend.sdlc.server.tools.BackgroundTaskProcessor) Status(javax.ws.rs.core.Response.Status) RevisionStatus(org.finos.legend.sdlc.domain.model.revision.RevisionStatus) ProjectFileAccessProvider(org.finos.legend.sdlc.server.project.ProjectFileAccessProvider) Predicate(java.util.function.Predicate) Pager(org.gitlab4j.api.Pager) Iterate(org.eclipse.collections.impl.utility.Iterate) Instant(java.time.Instant) RevisionApi(org.finos.legend.sdlc.server.domain.api.revision.RevisionApi) Collectors(java.util.stream.Collectors) WorkspaceType(org.finos.legend.sdlc.domain.model.project.workspace.WorkspaceType) Version(org.finos.legend.sdlc.domain.model.version.Version) RefType(org.gitlab4j.api.models.CommitRef.RefType) GitLabProjectId(org.finos.legend.sdlc.server.gitlab.GitLabProjectId) List(java.util.List) LazyIterate(org.eclipse.collections.impl.utility.LazyIterate) RevisionAccessContext(org.finos.legend.sdlc.server.domain.api.revision.RevisionAccessContext) ProjectPaths(org.finos.legend.sdlc.server.project.ProjectPaths) ListIterable(org.eclipse.collections.api.list.ListIterable) Revision(org.finos.legend.sdlc.domain.model.revision.Revision) Pattern(java.util.regex.Pattern) Comparator(java.util.Comparator) Collections(java.util.Collections) GitLabApi(org.gitlab4j.api.GitLabApi) GitLabApi(org.gitlab4j.api.GitLabApi) CommitRef(org.gitlab4j.api.models.CommitRef) CommitsApi(org.gitlab4j.api.CommitsApi) LegendSDLCServerException(org.finos.legend.sdlc.server.error.LegendSDLCServerException) RevisionStatus(org.finos.legend.sdlc.domain.model.revision.RevisionStatus) TagsApi(org.gitlab4j.api.TagsApi) Revision(org.finos.legend.sdlc.domain.model.revision.Revision) Version(org.finos.legend.sdlc.domain.model.version.Version) GitLabProjectId(org.finos.legend.sdlc.server.gitlab.GitLabProjectId) Tag(org.gitlab4j.api.models.Tag) Workspace(org.finos.legend.sdlc.domain.model.project.workspace.Workspace)

Example 19 with GitLabApi

use of org.gitlab4j.api.GitLabApi in project legend-sdlc by finos.

the class GitLabWorkspaceApi method isWorkspaceOutdatedByAccessType.

private boolean isWorkspaceOutdatedByAccessType(String projectId, String workspaceId, WorkspaceType workspaceType, ProjectFileAccessProvider.WorkspaceAccessType workspaceAccessType) {
    LegendSDLCServerException.validateNonNull(projectId, "projectId may not be null");
    LegendSDLCServerException.validateNonNull(workspaceId, "workspaceId may not be null");
    LegendSDLCServerException.validateNonNull(workspaceType, "workspaceType may not be null");
    LegendSDLCServerException.validateNonNull(workspaceAccessType, "workspaceAccessType may not be null");
    GitLabProjectId gitLabProjectId = parseProjectId(projectId);
    String workspaceBranchName = getBranchName(workspaceId, workspaceType, workspaceAccessType);
    GitLabApi gitLabApi = getGitLabApi(gitLabProjectId.getGitLabMode());
    RepositoryApi repositoryApi = gitLabApi.getRepositoryApi();
    // Get the workspace branch
    Branch workspaceBranch;
    try {
        workspaceBranch = withRetries(() -> repositoryApi.getBranch(gitLabProjectId.getGitLabId(), workspaceBranchName));
    } catch (Exception e) {
        throw buildException(e, () -> "User " + getCurrentUser() + " is not allowed to access " + workspaceType.getLabel() + " " + workspaceAccessType.getLabel() + " " + workspaceId + " in project " + projectId, () -> "Unknown " + workspaceType.getLabel() + " " + workspaceAccessType.getLabel() + " in project " + projectId + ": " + workspaceId, () -> "Error accessing " + workspaceType.getLabel() + " " + workspaceAccessType.getLabel() + " " + workspaceId + " in project " + projectId);
    }
    String workspaceRevisionId = workspaceBranch.getCommit().getId();
    // Get HEAD of master
    Branch masterBranch;
    try {
        masterBranch = withRetries(() -> repositoryApi.getBranch(gitLabProjectId.getGitLabId(), MASTER_BRANCH));
    } catch (Exception e) {
        throw buildException(e, () -> "User " + getCurrentUser() + " is not allowed to access the latest revision in project " + projectId, () -> "Unknown project: " + projectId, () -> "Error accessing latest revision for project " + projectId);
    }
    String masterRevisionId = masterBranch.getCommit().getId();
    CommitsApi commitsApi = gitLabApi.getCommitsApi();
    // Check if the workspace does not have the latest revision of the project, i.e. it is outdated
    try {
        if (masterRevisionId.equals(workspaceRevisionId)) {
            return false;
        }
        Pager<CommitRef> masterHeadCommitRefsPager = withRetries(() -> commitsApi.getCommitRefs(gitLabProjectId.getGitLabId(), masterRevisionId, RefType.BRANCH, ITEMS_PER_PAGE));
        Stream<CommitRef> masterHeadCommitRefs = PagerTools.stream(masterHeadCommitRefsPager);
        // This will check if the branch contains the master HEAD commit by looking up the list of references the commit is pushed to
        return masterHeadCommitRefs.noneMatch(cr -> workspaceBranchName.equals(cr.getName()));
    } catch (Exception e) {
        throw buildException(e, () -> "User " + getCurrentUser() + " is not allowed to check if " + workspaceType.getLabel() + " " + workspaceAccessType.getLabel() + " " + workspaceId + " in project " + projectId + " is outdated", () -> "Unknown revision (" + masterRevisionId + "), or " + workspaceType.getLabel() + " " + workspaceAccessType.getLabel() + " (" + workspaceId + ") or project (" + projectId + ")", () -> "Error checking if " + workspaceType.getLabel() + " " + workspaceAccessType.getLabel() + " " + workspaceId + " of project " + projectId + " is outdated");
    }
}
Also used : GitLabApi(org.gitlab4j.api.GitLabApi) GitLabProjectId(org.finos.legend.sdlc.server.gitlab.GitLabProjectId) Branch(org.gitlab4j.api.models.Branch) RepositoryApi(org.gitlab4j.api.RepositoryApi) CommitRef(org.gitlab4j.api.models.CommitRef) LegendSDLCServerException(org.finos.legend.sdlc.server.error.LegendSDLCServerException) GitLabApiException(org.gitlab4j.api.GitLabApiException) CommitsApi(org.gitlab4j.api.CommitsApi)

Example 20 with GitLabApi

use of org.gitlab4j.api.GitLabApi in project catma by forTEXT.

the class GitLabServerManagerTest method tearDown.

@AfterEach
public void tearDown() throws Exception {
    GitLabApi adminGitLabApi = gitlabManagerPrivileged.getGitLabApi();
    GroupApi groupApi = adminGitLabApi.getGroupApi();
    ProjectApi projectApi = adminGitLabApi.getProjectApi();
    UserApi userApi = adminGitLabApi.getUserApi();
    if (groupsToDeleteOnTearDown.size() > 0) {
        for (String groupPath : groupsToDeleteOnTearDown) {
            gitlabManagerRestricted.deleteGroup(groupPath);
            await().until(() -> groupApi.getGroups().isEmpty());
        }
    }
    if (repositoriesToDeleteOnTearDown.size() > 0) {
        for (Integer repositoryId : repositoriesToDeleteOnTearDown) {
            gitlabManagerRestricted.deleteRepository(repositoryId);
            await().until(() -> projectApi.getProjects().isEmpty());
        }
    }
    if (usersToDeleteOnTearDown.size() > 0) {
        for (Integer userId : usersToDeleteOnTearDown) {
            userApi.deleteUser(userId);
            GitLabServerManagerTest.awaitUserDeleted(userApi, userId);
        }
    }
    // delete the GitLab user that we created in setUp, including associated groups/repos
    // TODO: explicit deletion of associated groups/repos (above) is now superfluous since we are doing a hard delete
    userApi.deleteUser(gitlabManagerRestricted.getUser().getUserId(), true);
// GitLabServerManagerTest.awaitUserDeleted(userApi, gitlabManagerRestricted.getUser().getUserId());
}
Also used : GitLabApi(org.gitlab4j.api.GitLabApi) GroupApi(org.gitlab4j.api.GroupApi) ProjectApi(org.gitlab4j.api.ProjectApi) UserApi(org.gitlab4j.api.UserApi) AfterEach(org.junit.jupiter.api.AfterEach)

Aggregations

GitLabApi (org.gitlab4j.api.GitLabApi)27 GitLabApiException (org.gitlab4j.api.GitLabApiException)16 LegendSDLCServerException (org.finos.legend.sdlc.server.error.LegendSDLCServerException)14 GitLabProjectId (org.finos.legend.sdlc.server.gitlab.GitLabProjectId)8 ProvisioningException (com.tremolosecurity.provisioning.core.ProvisioningException)5 Workflow (com.tremolosecurity.provisioning.core.Workflow)5 GitlabUserProvider (com.tremolosecurity.unison.gitlab.provisioning.targets.GitlabUserProvider)5 Branch (org.gitlab4j.api.models.Branch)5 MergeRequest (org.gitlab4j.api.models.MergeRequest)5 Project (org.gitlab4j.api.models.Project)5 CommitsApi (org.gitlab4j.api.CommitsApi)4 CommitRef (org.gitlab4j.api.models.CommitRef)4 IOException (java.io.IOException)3 Collectors (java.util.stream.Collectors)3 ProjectFileAccessProvider (org.finos.legend.sdlc.server.project.ProjectFileAccessProvider)3 RepositoryApi (org.gitlab4j.api.RepositoryApi)3 ConfigStructure (com.microfocus.octane.gitlab.model.ConfigStructure)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 OutputStreamWriter (java.io.OutputStreamWriter)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2