Search in sources :

Example 11 with GitLabApi

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

the class GitLabProjectApi method createProject.

@Override
public Project createProject(String name, String description, ProjectType type, String groupId, String artifactId, Iterable<String> tags) {
    LegendSDLCServerException.validate(name, n -> (n != null) && !n.isEmpty(), "name may not be null or empty");
    LegendSDLCServerException.validateNonNull(description, "description may not be null");
    LegendSDLCServerException.validateNonNull(type, "type may not be null");
    LegendSDLCServerException.validate(groupId, ProjectStructure::isValidGroupId, g -> "Invalid groupId: " + g);
    LegendSDLCServerException.validate(artifactId, ProjectStructure::isValidArtifactId, a -> "Invalid artifactId: " + a);
    validateProjectCreation(name, description, type, groupId, artifactId);
    try {
        GitLabMode mode = getGitLabModeFromProjectType(type);
        GitLabApi gitLabApi = getGitLabApi(mode);
        List<String> tagList = Lists.mutable.empty();
        tagList.add(getLegendSDLCProjectTag());
        if (tags != null) {
            tagList.addAll(toLegendSDLCTagSet(tags));
        }
        org.gitlab4j.api.models.Project gitLabProjectSpec = new org.gitlab4j.api.models.Project().withName(name).withDescription(description).withTagList(tagList).withVisibility(getNewProjectVisibility()).withMergeRequestsEnabled(true).withIssuesEnabled(true).withWikiEnabled(false).withSnippetsEnabled(false);
        org.gitlab4j.api.models.Project gitLabProject = gitLabApi.getProjectApi().createProject(gitLabProjectSpec);
        if (gitLabProject == null) {
            throw new LegendSDLCServerException("Failed to create project: " + name);
        }
        // protect from commits on master
        gitLabApi.getProtectedBranchesApi().protectBranch(gitLabProject.getId(), MASTER_BRANCH, AccessLevel.NONE, AccessLevel.MAINTAINER);
        // build project structure
        ProjectConfigurationUpdateBuilder.newBuilder(getProjectFileAccessProvider(), type, GitLabProjectId.getProjectIdString(mode, gitLabProject)).withMessage("Build project structure").withGroupId(groupId).withArtifactId(artifactId).withProjectStructureVersion(getDefaultProjectStructureVersion()).withProjectStructureExtensionProvider(this.projectStructureExtensionProvider).withProjectStructurePlatformExtensions(this.projectStructurePlatformExtensions).buildProjectStructure();
        return fromGitLabProject(gitLabProject, mode);
    } catch (Exception e) {
        throw buildException(e, () -> "User " + getCurrentUser() + " is not allowed to create project " + name, () -> "Failed to create project: " + name, () -> "Failed to create project: " + name);
    }
}
Also used : GitLabApi(org.gitlab4j.api.GitLabApi) ProjectStructure(org.finos.legend.sdlc.server.project.ProjectStructure) LegendSDLCServerException(org.finos.legend.sdlc.server.error.LegendSDLCServerException) Project(org.finos.legend.sdlc.domain.model.project.Project) LegendSDLCServerException(org.finos.legend.sdlc.server.error.LegendSDLCServerException) GitLabMode(org.finos.legend.sdlc.server.gitlab.mode.GitLabMode)

Example 12 with GitLabApi

use of org.gitlab4j.api.GitLabApi in project dash-licenses by eclipse.

the class GitLabSupport method execute.

void execute(Consumer<GitLabConnection> callable) {
    Map<String, Object> clientConfig = null;
    IProxySettings proxySettings = this.proxySettings.get();
    if (proxySettings != null) {
        // Configure GitLab API for the proxy server
        clientConfig = Maps.newHashMap();
        proxySettings.configureJerseyClient(clientConfig);
    }
    try (GitLabApi gitLabApi = new GitLabApi(settings.getIpLabHostUrl(), settings.getIpLabToken(), clientConfig)) {
        callable.accept(new GitLabConnection(gitLabApi, settings.getIpLabRepositoryPath()));
    }
}
Also used : IProxySettings(org.eclipse.dash.licenses.IProxySettings) GitLabApi(org.gitlab4j.api.GitLabApi)

Example 13 with GitLabApi

use of org.gitlab4j.api.GitLabApi in project octane-gitlab-service by MicroFocus.

the class OctaneServices method getJobBuildStatus.

@Override
public CIBuildStatusInfo getJobBuildStatus(String jobCiId, String parameterName, String parameterValue) {
    ParsedPath parsedPath = new ParsedPath(jobCiId, gitLabApi, PathType.PIPELINE);
    try {
        List<Pipeline> pipelines = gitLabApi.getPipelineApi().getPipelines(parsedPath.getPathWithNameSpace());
        Optional<Pipeline> chosenPipeline = pipelines.stream().map(pipeline -> {
            try {
                List<Variable> pipelineVariables = gitLabApi.getPipelineApi().getPipelineVariables(parsedPath.getPathWithNameSpace(), pipeline.getId());
                for (Variable variable : pipelineVariables) {
                    if (variable.getKey().equals(parameterName) && variable.getValue().equals(parameterValue)) {
                        return pipeline;
                    }
                }
                return null;
            } catch (GitLabApiException e) {
                log.error("Failed to get variables from pipeline", e);
                throw new RuntimeException(e);
            }
        }).filter(Objects::nonNull).findAny();
        if (chosenPipeline.isPresent()) {
            String status = chosenPipeline.get().getStatus().toValue();
            CIBuildStatus currentCIBuildStatus = getCIBuildStatus(status);
            Optional<CIBuildStatus> buildStatus = Arrays.stream(CIBuildStatus.values()).filter(ciBuildStatus -> Objects.equals(ciBuildStatus, currentCIBuildStatus)).findAny();
            if (!buildStatus.isPresent()) {
                throw new RuntimeException("Failed to get the correct build status");
            }
            return dtoFactory.newDTO(CIBuildStatusInfo.class).setJobCiId(jobCiId).setBuildStatus(buildStatus.get()).setBuildCiId(getBuildCiId(chosenPipeline.get())).setParamName(parameterName).setParamValue(parameterValue).setResult(getCiBuildResult(status));
        }
        throw new RuntimeException("Failed to get information about the pipeline");
    } catch (GitLabApiException e) {
        log.error("Failed to get job build status of the pipeline run", e);
        throw new RuntimeException(e);
    }
}
Also used : java.util(java.util) com.hp.octane.integrations.dto.tests(com.hp.octane.integrations.dto.tests) CIBuildStatus(com.hp.octane.integrations.dto.snapshots.CIBuildStatus) Branch(org.gitlab4j.api.models.Branch) Job(org.gitlab4j.api.models.Job) URL(java.net.URL) EncodeCiJobBase64Parameter(com.hp.octane.integrations.services.configurationparameters.EncodeCiJobBase64Parameter) HttpStatus(org.apache.http.HttpStatus) Autowired(org.springframework.beans.factory.annotation.Autowired) Scope(org.springframework.context.annotation.Scope) Variable(org.gitlab4j.api.models.Variable) ConfigStructure(com.microfocus.octane.gitlab.model.ConfigStructure) TestResultsHelper(com.microfocus.octane.gitlab.helpers.TestResultsHelper) CIParameter(com.hp.octane.integrations.dto.parameters.CIParameter) DTOFactory(com.hp.octane.integrations.dto.DTOFactory) PipelineNode(com.hp.octane.integrations.dto.pipelines.PipelineNode) CIBuildResult(com.hp.octane.integrations.dto.snapshots.CIBuildResult) CIBuildStatusInfo(com.hp.octane.integrations.dto.general.CIBuildStatusInfo) PermissionException(com.hp.octane.integrations.exceptions.PermissionException) PREFIX(com.microfocus.octane.gitlab.helpers.PasswordEncryption.PREFIX) CIServerInfo(com.hp.octane.integrations.dto.general.CIServerInfo) CIPluginServices(com.hp.octane.integrations.CIPluginServices) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) JunitTestResultsProvider(com.microfocus.octane.gitlab.testresults.JunitTestResultsProvider) Application(com.microfocus.octane.gitlab.app.Application) Pipeline(org.gitlab4j.api.models.Pipeline) ApplicationSettings(com.microfocus.octane.gitlab.app.ApplicationSettings) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) CIPluginInfo(com.hp.octane.integrations.dto.general.CIPluginInfo) Component(org.springframework.stereotype.Component) Logger(org.apache.logging.log4j.Logger) OctaneConfiguration(com.hp.octane.integrations.OctaneConfiguration) CIParameters(com.hp.octane.integrations.dto.parameters.CIParameters) java.io(java.io) CIJobsList(com.hp.octane.integrations.dto.general.CIJobsList) GitLabApiException(org.gitlab4j.api.GitLabApiException) com.microfocus.octane.gitlab.helpers(com.microfocus.octane.gitlab.helpers) ConfigurationParameterFactory(com.hp.octane.integrations.services.configurationparameters.factory.ConfigurationParameterFactory) LogManager(org.apache.logging.log4j.LogManager) CIProxyConfiguration(com.hp.octane.integrations.dto.configuration.CIProxyConfiguration) GitLabApi(org.gitlab4j.api.GitLabApi) CIBuildStatus(com.hp.octane.integrations.dto.snapshots.CIBuildStatus) Variable(org.gitlab4j.api.models.Variable) GitLabApiException(org.gitlab4j.api.GitLabApiException) Pipeline(org.gitlab4j.api.models.Pipeline)

Example 14 with GitLabApi

use of org.gitlab4j.api.GitLabApi in project octane-gitlab-service by MicroFocus.

the class GitLabApiWrapper method initGitlabApiWrapper.

@PostConstruct
public void initGitlabApiWrapper() throws MalformedURLException, GitLabApiException, ConfigurationException {
    ConfigStructure config = applicationSettings.getConfig();
    Map<String, Object> proxyConfig = null;
    URL targetUrl = CIPluginSDKUtils.parseURL(config.getGitlabLocation());
    if (ProxyHelper.isProxyNeeded(applicationSettings, targetUrl)) {
        String protocol = targetUrl.getProtocol().toLowerCase();
        String proxyUrl = config.getProxyField(protocol, "proxyUrl");
        String proxyPassword = config.getProxyField(protocol, "proxyPassword");
        if (proxyPassword != null && proxyPassword.startsWith(PREFIX)) {
            try {
                proxyPassword = PasswordEncryption.decrypt(proxyPassword.substring(PREFIX.length()));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        proxyConfig = ProxyClientConfig.createProxyClientConfig(proxyUrl, config.getProxyField(protocol, "proxyUser"), proxyPassword);
    }
    String gitlabPersonalAccessToken = config.getGitlabPersonalAccessToken();
    if (gitlabPersonalAccessToken != null && gitlabPersonalAccessToken.startsWith(PREFIX)) {
        try {
            gitlabPersonalAccessToken = PasswordEncryption.decrypt(gitlabPersonalAccessToken.substring(PREFIX.length()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    gitLabApi = new GitLabApi(config.getGitlabLocation(), gitlabPersonalAccessToken, null, proxyConfig);
    try {
        gitLabApi.getProjectApi().getOwnedProjects();
    } catch (GitLabApiException e) {
        String message = "GitLab API failed to perform basic operations. Please validate GitLab properties - location, personalAccessToken(including token permissions/scopes in GitLab server)" + " if one of the end points doesnt required proxy, please put it on the non proxy hosts.";
        log.error(message);
        System.out.println(message);
        throw e;
    }
}
Also used : GitLabApi(org.gitlab4j.api.GitLabApi) ConfigStructure(com.microfocus.octane.gitlab.model.ConfigStructure) GitLabApiException(org.gitlab4j.api.GitLabApiException) URL(java.net.URL) MalformedURLException(java.net.MalformedURLException) ConfigurationException(javax.naming.ConfigurationException) GitLabApiException(org.gitlab4j.api.GitLabApiException) PostConstruct(javax.annotation.PostConstruct)

Example 15 with GitLabApi

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

the class GitLabApiTestSetupUtil method prepareGitLabUserContextHelper.

/**
 * Authenticates to GitLab and creates a test GitLabUserContext.
 *
 * @param username   the name of user for whom we create this context.
 * @param password   the password of user for whom we create this context.
 * @param hostUrl    the url of the test host.
 * @param hostScheme the scheme of the test host.
 * @param hostHost   the test host.
 * @param hostPort   the port (if necessary) of the test host.
 */
public static GitLabUserContext prepareGitLabUserContextHelper(String username, String password, String hostUrl, String hostScheme, String hostHost, Integer hostPort) throws LegendSDLCServerException {
    GitLabMode gitLabMode = GitLabMode.PROD;
    TestHttpServletRequest httpServletRequest = new TestHttpServletRequest();
    TestGitLabSession session = new TestGitLabSession(username);
    GitLabApi oauthGitLabApi;
    Version version;
    try {
        oauthGitLabApi = GitLabApi.oauth2Login(hostUrl, username, password, null, null, true);
        Assert.assertNotNull(oauthGitLabApi);
        version = oauthGitLabApi.getVersion();
    } catch (GitLabApiException e) {
        StringBuilder builder = new StringBuilder("Error instantiating GitLabApi via OAuth2; response status: ").append(e.getHttpStatus());
        StringTools.appendThrowableMessageIfPresent(builder, e, "; error message: ");
        if (e.hasValidationErrors()) {
            builder.append("; validation error(s): ").append(e.getValidationErrors());
        }
        throw new LegendSDLCServerException(builder.toString(), e);
    }
    String oauthToken = oauthGitLabApi.getAuthToken();
    LOGGER.info("Retrieved access token: {}", oauthToken);
    Assert.assertNotNull(version);
    GitLabServerInfo gitLabServerInfo = GitLabServerInfo.newServerInfo(hostScheme, hostHost, hostPort);
    GitLabAppInfo gitLabAppInfo = GitLabAppInfo.newAppInfo(gitLabServerInfo, null, null, null);
    GitLabModeInfo gitLabModeInfo = GitLabModeInfo.newModeInfo(gitLabMode, gitLabAppInfo);
    session.setGitLabToken(gitLabMode, oauthToken, TokenType.OAUTH2_ACCESS);
    session.setModeInfo(gitLabModeInfo);
    LegendSDLCWebFilter.setSessionAttributeOnServletRequest(httpServletRequest, session);
    GitLabAuthorizerManager authorizerManager = GitLabAuthorizerManager.newManager(Collections.emptyList());
    return new GitLabUserContext(httpServletRequest, null, authorizerManager);
}
Also used : GitLabServerInfo(org.finos.legend.sdlc.server.gitlab.GitLabServerInfo) GitLabApi(org.gitlab4j.api.GitLabApi) GitLabModeInfo(org.finos.legend.sdlc.server.gitlab.mode.GitLabModeInfo) GitLabAuthorizerManager(org.finos.legend.sdlc.server.gitlab.auth.GitLabAuthorizerManager) GitLabApiException(org.gitlab4j.api.GitLabApiException) TestGitLabSession(org.finos.legend.sdlc.server.gitlab.auth.TestGitLabSession) GitLabAppInfo(org.finos.legend.sdlc.server.gitlab.GitLabAppInfo) LegendSDLCServerException(org.finos.legend.sdlc.server.error.LegendSDLCServerException) Version(org.gitlab4j.api.models.Version) GitLabUserContext(org.finos.legend.sdlc.server.gitlab.auth.GitLabUserContext) GitLabMode(org.finos.legend.sdlc.server.gitlab.mode.GitLabMode)

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