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);
}
}
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()));
}
}
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);
}
}
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;
}
}
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);
}
Aggregations