org.gitlab.api.GitlabAPI Java Examples

The following examples show how to use org.gitlab.api.GitlabAPI. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GitLabAccess.java    From git-as-svn with GNU General Public License v2.0 7 votes vote down vote up
GitLabAccess(@NotNull LocalContext local, @NotNull GitLabMappingConfig config, int projectId) {
  this.environment = Collections.singletonMap("GL_REPOSITORY", String.format("project-%s", projectId));

  final GitLabContext context = GitLabContext.sure(local.getShared());

  this.cache = CacheBuilder.newBuilder()
      .maximumSize(config.getCacheMaximumSize())
      .expireAfterWrite(config.getCacheTimeSec(), TimeUnit.SECONDS)
      .build(
          new CacheLoader<String, GitlabProject>() {
            @Override
            public GitlabProject load(@NotNull String userId) throws Exception {
              if (userId.isEmpty())
                return GitlabAPI.connect(context.getGitLabUrl(), null).getProject(projectId);

              final GitlabAPI api = context.connect();
              final String tailUrl = GitlabProject.URL + "/" + projectId + "?sudo=" + userId;
              return api.retrieve().to(tailUrl, GitlabProject.class);
            }
          }
      );
}
 
Example #2
Source File: GitlabHTTPRequestorTest.java    From java-gitlab-api with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName(value = "An error is expected, calling the \"setupConnection\" method if the read timeout < 0")
public void unitTest_20180503203635() throws Exception {
    GitlabAPI api = mock(GitlabAPI.class);
    when(api.getResponseReadTimeout()).thenReturn(-555);
    GitlabHTTPRequestor http = new GitlabHTTPRequestor(api);
    URL url = new URL("http://test.url");
    Method method = GitlabHTTPRequestor.class.getDeclaredMethod("setupConnection", URL.class);
    method.setAccessible(true);
    Throwable throwable = null;
    try {
        method.invoke(http, url);
    } catch (Exception e) {
        throwable = e.getCause();
    }
    assertThat(throwable, not(nullValue()));
    assertThat(throwable, is(instanceOf(IllegalArgumentException.class)));
    assertThat(throwable.getMessage(), is("timeouts can't be negative"));
}
 
Example #3
Source File: GitlabHTTPRequestorTest.java    From java-gitlab-api with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName(value = "An error is expected, calling the \"setupConnection\" method if the connection timeout < 0")
public void unitTest_20180503194643() throws Exception {
    GitlabAPI api = mock(GitlabAPI.class);
    when(api.getConnectionTimeout()).thenReturn(-555);
    GitlabHTTPRequestor http = new GitlabHTTPRequestor(api);
    URL url = new URL("http://test.url");
    Method method = GitlabHTTPRequestor.class.getDeclaredMethod("setupConnection", URL.class);
    method.setAccessible(true);
    Throwable throwable = null;
    try {
        method.invoke(http, url);
    } catch (Exception e) {
        throwable = e.getCause();
    }
    assertThat(throwable, not(nullValue()));
    assertThat(throwable, is(instanceOf(IllegalArgumentException.class)));
    assertThat(throwable.getMessage(), is("timeouts can't be negative"));
}
 
Example #4
Source File: GitlabApiClient.java    From nexus3-gitlabauth-plugin with MIT License 6 votes vote down vote up
private GitlabPrincipal doAuthz(String loginName, char[] token) throws GitlabAuthenticationException {
    GitlabUser gitlabUser;
    List<GitlabGroup> groups = null;
    try {
        GitlabAPI gitlabAPI = GitlabAPI.connect(configuration.getGitlabApiUrl(), String.valueOf(token));
        gitlabUser = gitlabAPI.getUser();
    } catch (Exception e) {
        throw new GitlabAuthenticationException(e);
    }

    if (gitlabUser==null || !loginName.equals(gitlabUser.getEmail())) {
        throw new GitlabAuthenticationException("Given username not found or does not match Github Username!");
    }

    GitlabPrincipal principal = new GitlabPrincipal();

    principal.setUsername(gitlabUser.getEmail());
    principal.setGroups(getGroups((gitlabUser.getUsername())));

    return principal;
}
 
Example #5
Source File: GitLabContext.java    From git-as-svn with GNU General Public License v2.0 6 votes vote down vote up
@NotNull
public static GitLabToken obtainAccessToken(@NotNull String gitlabUrl, @NotNull String username, @NotNull String password, boolean sudoScope) throws IOException {
  try {
    final OAuthGetAccessToken tokenServerUrl = new OAuthGetAccessToken(gitlabUrl + "/oauth/token?scope=api" + (sudoScope ? "%20sudo" : ""));
    final TokenResponse oauthResponse = new PasswordTokenRequest(transport, JacksonFactory.getDefaultInstance(), tokenServerUrl, username, password).execute();
    return new GitLabToken(TokenType.ACCESS_TOKEN, oauthResponse.getAccessToken());
  } catch (TokenResponseException e) {
    if (sudoScope && e.getStatusCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
      // Fallback for pre-10.2 gitlab versions
      final GitlabSession session = GitlabAPI.connect(gitlabUrl, username, password);
      return new GitLabToken(TokenType.PRIVATE_TOKEN, session.getPrivateToken());
    } else {
      throw new GitlabAPIException(e.getMessage(), e.getStatusCode(), e);
    }
  }
}
 
Example #6
Source File: GitLabProvider.java    From gocd-build-status-notifier with Apache License 2.0 6 votes vote down vote up
@Override
public void updateStatus(String url, PluginSettings pluginSettings, String prIdStr, String revision, String pipelineStage,
                         String result, String trackbackURL) throws Exception {

    String endPointToUse = pluginSettings.getEndPoint();
    String oauthAccessTokenToUse = pluginSettings.getOauthToken();

    if (StringUtils.isEmpty(endPointToUse)) {
        endPointToUse = System.getProperty("go.plugin.build.status.gitlab.endpoint");
    }
    if (StringUtils.isEmpty(oauthAccessTokenToUse)) {
        oauthAccessTokenToUse = System.getProperty("go.plugin.build.status.gitlab.oauth");
    }

    GitlabAPI api = GitlabAPI.connect(endPointToUse, oauthAccessTokenToUse);
    GitlabProject project = api.getProject(getRepository(url));
    api.createCommitStatus(project, revision, GitLabState.stateFor(result), prIdStr, "GoCD", trackbackURL, "");
}
 
Example #7
Source File: GitLabMapping.java    From git-as-svn with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void ready(@NotNull SharedContext context) throws IOException {
  final GitlabAPI api = gitLabContext.connect();

  // Web hook for repository list update.
  final WebServer webServer = context.sure(WebServer.class);
  final URL hookUrl = webServer.toUrl(gitLabContext.getHookPath());
  final String path = hookUrl.getPath();
  webServer.addServlet(StringUtils.isEmptyOrNull(path) ? "/" : path, new GitLabHookServlet());

  try {
    if (!isHookInstalled(api, hookUrl.toString())) {
      api.addSystemHook(hookUrl.toString());
    }
  } catch (GitlabAPIException e) {
    if (e.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN) {
      log.warn("Unable to install gitlab hook {}: {}", hookUrl, e.getMessage());
    } else {
      throw e;
    }
  }

}
 
Example #8
Source File: GitLabMappingConfig.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@NotNull
@Override
public RepositoryMapping create(@NotNull SharedContext context, boolean canUseParallelIndexing) throws IOException {
  final GitLabContext gitlab = context.sure(GitLabContext.class);
  final GitlabAPI api = gitlab.connect();
  // Get repositories.

  final GitLabMapping mapping = new GitLabMapping(context, this, gitlab);
  for (GitlabProject project : api.getProjects())
    mapping.updateRepository(project);

  final Consumer<GitLabProject> init = repository -> {
    try {
      repository.initRevisions();
    } catch (IOException | SVNException e) {
      throw new RuntimeException(String.format("[%s]: failed to initialize", repository), e);
    }
  };

  if (canUseParallelIndexing) {
    mapping.getMapping().values().parallelStream().forEach(init);
  } else {
    mapping.getMapping().values().forEach(init);
  }

  return mapping;
}
 
Example #9
Source File: GitlabHTTPRequestorTest.java    From java-gitlab-api with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName(value = "Expected success, calling the \"setupConnection\" method if the read timeout > 0")
public void unitTest_20180503203531() throws Exception {
    GitlabAPI api = mock(GitlabAPI.class);
    when(api.getResponseReadTimeout()).thenReturn(555);
    GitlabHTTPRequestor http = new GitlabHTTPRequestor(api);
    URL url = new URL("http://test.url");
    Method method = GitlabHTTPRequestor.class.getDeclaredMethod("setupConnection", URL.class);
    method.setAccessible(true);
    HttpURLConnection connection = (HttpURLConnection) method.invoke(http, url);
    assertThat(connection.getReadTimeout(), is(555));
}
 
Example #10
Source File: GitlabHTTPRequestorTest.java    From java-gitlab-api with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName(value = "Expected success, calling the \"setupConnection\" method if the read timeout = 0")
public void unitTest_20180503202458() throws Exception {
    GitlabAPI api = mock(GitlabAPI.class);
    when(api.getResponseReadTimeout()).thenReturn(0);
    GitlabHTTPRequestor http = new GitlabHTTPRequestor(api);
    URL url = new URL("http://test.url");
    Method method = GitlabHTTPRequestor.class.getDeclaredMethod("setupConnection", URL.class);
    method.setAccessible(true);
    HttpURLConnection connection = (HttpURLConnection) method.invoke(http, url);
    assertThat(connection.getReadTimeout(), is(0));
}
 
Example #11
Source File: GitlabHTTPRequestorTest.java    From java-gitlab-api with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName(value = "Expected success, calling the \"setupConnection\" method if the connection timeout > 0")
public void unitTest_20180503194559() throws Exception {
    GitlabAPI api = mock(GitlabAPI.class);
    when(api.getConnectionTimeout()).thenReturn(456);
    GitlabHTTPRequestor http = new GitlabHTTPRequestor(api);
    URL url = new URL("http://test.url");
    Method method = GitlabHTTPRequestor.class.getDeclaredMethod("setupConnection", URL.class);
    method.setAccessible(true);
    HttpURLConnection connection = (HttpURLConnection) method.invoke(http, url);
    assertThat(connection.getConnectTimeout(), is(456));
}
 
Example #12
Source File: GitlabHTTPRequestorTest.java    From java-gitlab-api with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName(value = "Expected success, calling the \"setupConnection\" method if the connection timeout = 0")
public void unitTest_20180503194340() throws Exception {
    GitlabAPI api = mock(GitlabAPI.class);
    when(api.getConnectionTimeout()).thenReturn(0);
    GitlabHTTPRequestor http = new GitlabHTTPRequestor(api);
    URL url = new URL("http://test.url");
    Method method = GitlabHTTPRequestor.class.getDeclaredMethod("setupConnection", URL.class);
    method.setAccessible(true);
    HttpURLConnection connection = (HttpURLConnection) method.invoke(http, url);
    assertThat(connection.getConnectTimeout(), is(0));
}
 
Example #13
Source File: GitlabHTTPRequestor.java    From java-gitlab-api with Apache License 2.0 5 votes vote down vote up
private void submitAttachments(HttpURLConnection connection) throws IOException {
    String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
    connection.setDoOutput(true);
    connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    String charset = "UTF-8";
    String CRLF = "\r\n"; // Line separator required by multipart/form-data.
    OutputStream output = connection.getOutputStream();
    try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true)) {
        for (Map.Entry<String, Object> paramEntry : data.entrySet()) {
            String paramName = paramEntry.getKey();
            String param = GitlabAPI.MAPPER.writeValueAsString(paramEntry.getValue());
            writer.append("--").append(boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"").append(paramName).append("\"").append(CRLF);
            writer.append("Content-Type: text/plain; charset=").append(charset).append(CRLF);
            writer.append(CRLF).append(param).append(CRLF).flush();
        }
        for (Map.Entry<String, File> attachMentEntry : attachments.entrySet()) {
            File binaryFile = attachMentEntry.getValue();
            writer.append("--").append(boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"").append(attachMentEntry.getKey())
                    .append("\"; filename=\"").append(binaryFile.getName()).append("\"").append(CRLF);
            writer.append("Content-Type: ").append(URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
            writer.append("Content-Transfer-Encoding: binary").append(CRLF);
            writer.append(CRLF).flush();
            try (Reader fileReader = new FileReader(binaryFile)) {
                IOUtils.copy(fileReader, output);
            }
            output.flush(); // Important before continuing with writer!
            writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
        }
        writer.append("--").append(boundary).append("--").append(CRLF).flush();
    }
}
 
Example #14
Source File: GitlabTaskDataHandler.java    From mylyn-gitlab with Eclipse Public License 1.0 5 votes vote down vote up
public TaskData downloadTaskData(TaskRepository repository, Integer ticketId) throws CoreException {
	try {
		GitlabConnection connection = ConnectionManager.get(repository);
		GitlabAPI api = connection.api();
		GitlabIssue issue = api.getIssue(connection.project.getId(), ticketId);
		List<GitlabNote> notes = api.getNotes(issue);

		return createTaskDataFromGitlabIssue(issue, repository, notes);
	} catch (IOException e) {
		throw new GitlabException("Unknown connection error!");
	}
}
 
Example #15
Source File: GitLabIntegrationTest.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@NotNull
private GitlabProject createGitlabProject(@NotNull GitlabAPI rootAPI, @NotNull GitlabGroup group, @NotNull String name, @NotNull GitlabVisibility visibility, @NotNull Set<String> tags) throws IOException {
  // java-gitlab-api doesn't handle tag_list, so we have to do this manually
  final Query query = new Query()
      .append("name", name)
      .appendIf("namespace_id", group.getId())
      .appendIf("visibility", visibility.toString())
      .appendIf("tag_list", String.join(",", tags));

  final String tailUrl = GitlabProject.URL + query.toString();
  return rootAPI.dispatch().to(tailUrl, GitlabProject.class);
}
 
Example #16
Source File: GitlabRepositoryApiImpl.java    From bistoury with GNU General Public License v3.0 5 votes vote down vote up
private ApiResult doFile(final String projectId, final String ref, final String filepath) throws IOException {
    try {
        final GitlabAPI api = createGitlabApi();
        final GitlabProject project = api.getProject(projectId);
        final Query query = new Query().append("file_path", filepath).append("ref", ref);
        final String url = "/projects/" + project.getId() + "/repository/files" + query.toString();
        return ResultHelper.success(api.retrieve().to(url, GitlabFile.class));
    } catch (GitlabAPIException e) {
        Metrics.counter("connect_gitlab_error").inc();
        return ResultHelper.fail(-1, "连接gitlab服务器失败,请核private token", e);
    } catch (FileNotFoundException fnfe) {
        return ResultHelper.fail(-1, "文件不存在,请核对仓库地址", fnfe);
    }
}
 
Example #17
Source File: GitLabAPI.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
public static GitLabAPI connect(String url, String token, boolean ignoreCertificateErrors, int requestTimeout) throws GitLabAPIException {
    try {
        GitlabAPI delegate = GitlabAPI.connect(url, token);
        delegate.ignoreCertificateErrors(ignoreCertificateErrors);
        return new GitLabAPI(delegate);
    } catch (Exception e) {
        throw new GitLabAPIException(e);
    }
}
 
Example #18
Source File: GitlabRepositoryApiImpl.java    From bistoury with GNU General Public License v3.0 5 votes vote down vote up
private GitlabAPI createGitlabApi() {

        if (Strings.isNullOrEmpty(gitEndPoint)) {
            throw new RuntimeException("git 链接配置错误");
        }

        String userCode = LoginContext.getLoginContext().getLoginUser();
        Optional<PrivateToken> token = gitPrivateTokenService.queryToken(userCode);
        if (!token.isPresent()) {
            throw new RuntimeException("尚未设置 Git Private Token");
        }
        return GitlabAPI.connect(gitEndPoint, token.get().getPrivateToken());
    }
 
Example #19
Source File: SonarScanImpl.java    From seppb with MIT License 5 votes vote down vote up
@Override
public List<GitlabBranch> listBranch(BuildInstance buildInstance) throws IOException {
	SystemSetting gitConfig = settingDAO.findSetting(SettingType.GIT.getValue());


	if(gitConfig == null){
		log.info("尚未查询到Git系统配置" );
		return null;
	}
	List<GitProperties.GitConfig> gitConfigs = GitProperties.settingToGitConfig(gitConfig);
	String apiToken = null;
	String repoUrl = null;

	for (GitProperties.GitConfig git : gitConfigs) {
		if (git.getRepoUrl().equals(buildInstance.getRepoUrl())) {
			apiToken = git.getApiToken();
			repoUrl = buildInstance.getRepoUrl();
			break;
		}
	}
	GitlabProject project = GitlabAPI.connect(repoUrl, apiToken).getProject(buildInstance.getNamespace(), buildInstance.getProjectName());
	List<GitlabBranch> ListBraches = GitlabAPI.connect(repoUrl, apiToken).getBranches(project);
	return ListBraches;
}
 
Example #20
Source File: GitlabService.java    From jhipster-online with Apache License 2.0 5 votes vote down vote up
/**
 * Create a GitLab repository and add the JHipster Bot as collaborator.
 */
@Async
@Override
public void createGitProviderRepository(User user, String applicationId, String applicationConfiguration, String
    group,
    String repositoryName) {
    StopWatch watch = new StopWatch();
    watch.start();
    try {
        log.info("Beginning to create repository {} / {}", group, repositoryName);
        this.logsService.addLog(applicationId, "Creating GitLab repository");
        GitlabAPI gitlab = getConnection(user);
        if (user.getGitlabUser().equals(group)) {
            log.debug("Repository {} belongs to user {}", repositoryName, group);
            log.info("Creating repository {} / {}", group, repositoryName);
            gitlab.createProject(repositoryName);
            this.logsService.addLog(applicationId, "GitLab repository created!");
        } else {
            log.debug("Repository {} belongs to organization {}", repositoryName, group);
            log.info("Creating repository {} / {}", group, repositoryName);
            gitlab.createProjectForGroup(repositoryName, gitlab.getGroup(group));
            this.logsService.addLog(applicationId, "GitLab repository created!");
        }

        this.generatorService.generateGitApplication(user, applicationId, applicationConfiguration, group,
            repositoryName, GitProvider.GITLAB);

        this.logsService.addLog(applicationId, "Generation finished");
    } catch (Exception e) {
        this.logsService.addLog(applicationId, "Error during generation: " + e.getMessage());
        this.logsService.addLog(applicationId, "Generation failed");
    }
    watch.stop();
}
 
Example #21
Source File: GitlabService.java    From jhipster-online with Apache License 2.0 5 votes vote down vote up
@Override
public int createPullRequest(User user, String group, String repositoryName,
    String title, String branchName, String body) throws Exception {
    log.info("Creating Merge Request on repository {} / {}", group, repositoryName);
    GitlabAPI gitlab = getConnection(user);
    int number = gitlab.getProject(group, repositoryName).getId();
    GitlabMergeRequest mergeRequest = gitlab.createMergeRequest(number, branchName, "master", null, title);
    log.info("Merge Request created!");
    return mergeRequest.getIid();
}
 
Example #22
Source File: GitlabService.java    From jhipster-online with Apache License 2.0 5 votes vote down vote up
/**
 * Connect to GitLab as the current logged in user.
 */
private GitlabAPI getConnection(User user) throws Exception {
    log.debug("Authenticating user `{}` on GitLab", user.getLogin());
    if (user.getGitlabOAuthToken() == null) {
        log.info("No GitLab token configured");
        throw new Exception("GitLab is not configured.");
    }
    GitlabAPI gitlab = GitlabAPI.connect(applicationProperties.getGitlab().getHost(), user.getGitlabOAuthToken(),
        TokenType.ACCESS_TOKEN);

    log.debug("User `{}` authenticated as `{}` on GitLab", user.getLogin(), gitlab.getUser().getUsername());
    return gitlab;
}
 
Example #23
Source File: GitLabClient.java    From git-changelog-lib with Apache License 2.0 5 votes vote down vote up
private static List<GitlabIssue> getAllIssues(GitLabProjectIssuesCacheKey cacheKey)
    throws IOException {
  String hostUrl = cacheKey.getHostUrl();
  String apiToken = cacheKey.getApiToken();
  GitlabAPI gitLabApi = GitlabAPI.connect(hostUrl, apiToken);
  GitlabProject project = new GitlabProject();
  project.setId(cacheKey.getProjectId());
  return gitLabApi.getIssues(project);
}
 
Example #24
Source File: GitLabMapping.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
private boolean isHookInstalled(@NotNull GitlabAPI api, @NotNull String hookUrl) throws IOException {
  final List<GitlabSystemHook> hooks = api.getSystemHooks();
  for (GitlabSystemHook hook : hooks) {
    if (hook.getUrl().equals(hookUrl)) {
      return true;
    }
  }
  return false;
}
 
Example #25
Source File: GitLabContext.java    From git-as-svn with GNU General Public License v2.0 4 votes vote down vote up
@NotNull
public GitlabAPI connect() {
  return connect(getGitLabUrl(), config.getToken());
}
 
Example #26
Source File: GitLabIntegrationTest.java    From git-as-svn with GNU General Public License v2.0 4 votes vote down vote up
@BeforeClass
void before() throws Exception {
  SvnTestHelper.skipTestIfDockerUnavailable();

  String gitlabVersion = System.getenv("GITLAB_VERSION");
  if (gitlabVersion == null) {
    SvnTestHelper.skipTestIfRunningOnCI();

    gitlabVersion = "9.3.3-ce.0";
  }

  final int hostPort = 9999;
  // containerPort is supposed to be 80, but GitLab binds to port from external_url
  // See https://stackoverflow.com/questions/39351563/gitlab-docker-not-working-if-external-url-is-set
  final int containerPort = 9999;
  final String hostname = DockerClientFactory.instance().dockerHostIpAddress();

  gitlabUrl = String.format("http://%s:%s", hostname, hostPort);

  gitlab = new FixedHostPortGenericContainer<>("gitlab/gitlab-ce:" + gitlabVersion)
      // We have a chicken-and-egg problem here. In order to set external_url, we need to know container address,
      // but we do not know container address until container is started.
      // So, for now use fixed port :(
      .withFixedExposedPort(hostPort, containerPort)
      // This is kinda stupid that we need to do withExposedPorts even when we have withFixedExposedPort
      .withExposedPorts(containerPort)
      .withEnv("GITLAB_OMNIBUS_CONFIG", String.format("external_url '%s'", gitlabUrl))
      .withEnv("GITLAB_ROOT_PASSWORD", rootPassword)
      .waitingFor(Wait.forHttp("/users/sign_in")
          .withStartupTimeout(Duration.of(10, ChronoUnit.MINUTES)));

  gitlab.start();

  rootToken = createToken(root, rootPassword, true);

  final GitlabAPI rootAPI = GitLabContext.connect(gitlabUrl, rootToken);

  final CreateUserRequest createUserRequest = new CreateUserRequest(user, user, "git-as-svn@localhost")
      .setPassword(userPassword)
      .setSkipConfirmation(true);

  final GitlabUser gitlabUser = rootAPI.createUser(createUserRequest);
  Assert.assertNotNull(gitlabUser);

  final GitlabGroup group = rootAPI.createGroup(new CreateGroupRequest("testGroup").setVisibility(GitlabVisibility.PUBLIC), null);
  Assert.assertNotNull(group);

  Assert.assertNotNull(rootAPI.addGroupMember(group.getId(), gitlabUser.getId(), GitlabAccessLevel.Developer));

  gitlabProject = createGitlabProject(rootAPI, group, "test", GitlabVisibility.INTERNAL, Collections.singleton("git-as-svn:master"));
  gitlabPublicProject = createGitlabProject(rootAPI, group, "publik", GitlabVisibility.PUBLIC, Collections.singleton("git-as-svn:master"));
}
 
Example #27
Source File: GitLabAPI.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 4 votes vote down vote up
private GitLabAPI(GitlabAPI delegate) {
    this.delegate = delegate;
}
 
Example #28
Source File: GitlabTaskDataHandler.java    From mylyn-gitlab with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public RepositoryResponse postTaskData(TaskRepository repository, TaskData data,
		Set<TaskAttribute> attributes, IProgressMonitor monitor)
		throws CoreException {

	GitlabAttributeMapper attributeMapper = (GitlabAttributeMapper) data.getAttributeMapper();

	TaskAttribute root = data.getRoot();
	String labels = root.getAttribute(GitlabAttribute.LABELS.getTaskKey()).getValue();
	String title = root.getAttribute(GitlabAttribute.TITLE.getTaskKey()).getValue();
	String body = root.getAttribute(GitlabAttribute.BODY.getTaskKey()).getValue();

	Integer assigneeId = 0;

	// We have to check, if the assignee has changed. The gitlab api leaves three posiblities for the assignee ID:
	// 0: leave as it is
	// -1: unassign
	// real id: assign
	// If we didnt do this, Gitlab would create a comment everytime we edit the issue and there is still no
	// assignee
	for(TaskAttribute a : attributes) {
		if(a.getId().equals(GitlabAttribute.ASSIGNEE.getTaskKey())) {
			GitlabProjectMember assignee = attributeMapper.findProjectMemberByName(
					root.getAttribute(GitlabAttribute.ASSIGNEE.getTaskKey()).getValue());
			assigneeId = (assignee == null ? -1 : assignee.getId());
		}
	}

	GitlabMilestone milestone = attributeMapper.findMilestoneByName(
			root.getAttribute(GitlabAttribute.MILESTONE.getTaskKey()).getValue());
	Integer milestoneId = (milestone == null ? 0 : milestone.getId());

	GitlabConnection connection = ConnectionManager.get(repository);
	GitlabAPI api = connection.api();

	try {
		monitor.beginTask("Uploading task", IProgressMonitor.UNKNOWN);
		GitlabIssue issue = null;
		if(data.isNew()) {
			issue = api.createIssue(connection.project.getId(), assigneeId, milestoneId, labels, body, title);
			return new RepositoryResponse(ResponseKind.TASK_CREATED, "" + issue.getIid());
		} else {

			if(root.getAttribute(TaskAttribute.COMMENT_NEW) != null &&
					!root.getAttribute(TaskAttribute.COMMENT_NEW).getValue().equals("")) {
				api.createNote(connection.project.getId(), GitlabConnector.getTicketId(data.getTaskId()),
						root.getAttribute(TaskAttribute.COMMENT_NEW).getValue());
			}

			String action = root.getAttribute(TaskAttribute.OPERATION).getValue();

			issue = api.editIssue(connection.project.getId(), GitlabConnector.getTicketId(data.getTaskId()), assigneeId,
					milestoneId, labels, body, title, GitlabAction.find(action).getGitlabIssueAction());
			return new RepositoryResponse(ResponseKind.TASK_UPDATED, "" + issue.getIid());
		}
	} catch (IOException e) {
		throw new GitlabException("Unknown connection error!");
	} finally {
		monitor.done();
	}
}
 
Example #29
Source File: GitLabMapping.java    From git-as-svn with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  log.info("GitLab system hook fire ...");
  final GitLabHookEvent event = parseEvent(req);
  final String msg = "Can't parse event data";
  if (event == null || event.getEventName() == null) {
    log.warn(msg);
    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
    return;
  }
  try {
    log.debug(event.getEventName() + " event happened, process ...");
    switch (event.getEventName()) {
      case "project_create":
      case "project_update":
      case "project_rename":
      case "project_transfer":
        if (event.getProjectId() == null || event.getPathWithNamespace() == null) {
          log.warn(msg);
          resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
          return;
        }
        final GitlabAPI api = gitLabContext.connect();
        final GitLabProject project = updateRepository(api.getProject(event.getProjectId()));
        if (project != null) {
          log.info(event.getEventName() + " event happened, init project revisions ...");
          project.initRevisions();
        } else {
          log.warn(event.getEventName() + " event happened, but can not found project!");
        }
        return;
      case "project_destroy":
        if (event.getProjectId() == null || event.getPathWithNamespace() == null) {
          resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Can't parse event data");
          return;
        }
        removeRepository(event.getProjectId(), event.getPathWithNamespace());
        break;
      default:
        // Ignore hook.
        log.info(event.getEventName() + " event not process, ignore this hook event.");
        return;
    }
    super.doPost(req, resp);
  } catch (FileNotFoundException inored) {
    log.warn("Event repository not exists: " + event.getProjectId());
  } catch (SVNException e) {
    log.error("Event processing error: " + event.getEventName(), e);
    resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
  }
}
 
Example #30
Source File: GitlabConnection.java    From mylyn-gitlab with Eclipse Public License 1.0 4 votes vote down vote up
public GitlabAPI api() {
	return GitlabAPI.connect(host, token);
}