org.gitlab.api.models.GitlabProject Java Examples

The following examples show how to use org.gitlab.api.models.GitlabProject. 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: GitlabUploadIT.java    From java-gitlab-api with Apache License 2.0 6 votes vote down vote up
@Test
public void testUploadToProject() throws Exception {
    GitlabProject project;
    try {
        project = api.getProject("root", "project");
    } catch (FileNotFoundException e) {
        project = api.createUserProject(api.getUser().getId(), "project");
    }
    String content = "test file content";
    File tempFile = createTempFile(content);
    try {
        GitlabUpload upload = api.uploadFile(project, tempFile);
        Assert.assertNotNull(upload.getUrl());
    } finally {
        tempFile.delete();
    }
}
 
Example #2
Source File: GitLabMapping.java    From git-as-svn with GNU General Public License v2.0 6 votes vote down vote up
@NotNull
private static Set<String> getBranchesToExpose(@NotNull GitlabProject project) {
  final Set<String> result = new TreeSet<>();
  for (String tag : project.getTagList()) {
    if (!tag.startsWith(tagPrefix))
      continue;

    final String branch = tag.substring(tagPrefix.length());
    if (branch.isEmpty())
      continue;

    result.add(branch);
  }

  return result;
}
 
Example #3
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 #4
Source File: GitLabSCMSourceEvent.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 6 votes vote down vote up
private boolean isMatch(@Nonnull GitLabSCMNavigator navigator) {
    if (!navigator.getListenToWebHooks() || !navigator.getHookListener().id().equals(hookId)) {
        return false;
    }

    switch (getType()) {
        case CREATED:
        case UPDATED:
            GitlabProject project = EventHelper.getMatchingProject(navigator, getPayload());
            if (project == null) {
                return false;
            }

            sourceName = project.getPathWithNamespace();
            return true;
        case REMOVED:
            return true;
        default:
            return false;
    }
}
 
Example #5
Source File: GitLabAuthenticationToken.java    From gitlab-oauth-plugin with MIT License 6 votes vote down vote up
public boolean isPublicRepository(final String repositoryName) {
	try {
		Boolean isPublic = publicRepositoryCache.get(repositoryName, new Callable<Boolean>() {
			@Override
			public Boolean call() throws Exception {
				GitlabProject repository = loadRepository(repositoryName);
				if (repository == null) {
					// We don't have access so it must not be public (it
					// could be non-existant)
					return Boolean.FALSE;
				} else {
					return Boolean.TRUE.equals(repository.isPublic());
				}
			}
		});

		return isPublic.booleanValue();
	} catch (ExecutionException e) {
		LOGGER.log(Level.SEVERE, "an exception was thrown", e);
		throw new RuntimeException("authorization failed for user = " + getName(), e);
	}
}
 
Example #6
Source File: EventHelper.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
private static GitlabProject getGitlabProject(GitLabSCMNavigator navigator, Integer id) {
    try {
        return gitLabAPI(navigator.getSourceSettings()).getProject(id);
    } catch (IOException e) {
        LOGGER.info("could not get project with id " + id);
        return null;
    }
}
 
Example #7
Source File: GitlabJson.java    From java-gitlab-api with Apache License 2.0 5 votes vote down vote up
private int getRandomProject (List<GitlabProject> projects) {
    if (projects.size() > 0) {
        Random rand = new Random();
        return projects.get(rand.nextInt(projects.size())).getId();
    } else
        return 0;
}
 
Example #8
Source File: GitlabJson.java    From java-gitlab-api with Apache License 2.0 5 votes vote down vote up
@Test
public void getProjectJson () throws IOException {
    List<GitlabProject> projects = api.getProjects();
    int randomProjectNumber = getRandomProject(projects);
    if (randomProjectNumber != 0) {
        String p = api.getProjectJson(randomProjectNumber);
        assertTrue("The JSON is 0 length",p.length() > 0);
        assertTrue("Project JSON does not contain 'id'.",p.indexOf("id") > 0);
        assertTrue("Project JSON does not contain 'default_branch'.",p.indexOf("default_branch") > 0);
    } else {
        fail("No projects are defined in the gitlab instance, or something failed.");
    }
}
 
Example #9
Source File: GitlabConnection.java    From mylyn-gitlab with Eclipse Public License 1.0 5 votes vote down vote up
public GitlabConnection(String host, GitlabProject project, String token,
		GitlabAttributeMapper mapper) {
	this.host = host;
	this.project = project;
	this.token = token;
	this.mapper = mapper;
}
 
Example #10
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 #11
Source File: GitLabMapping.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@Nullable
GitLabProject updateRepository(@NotNull GitlabProject project) throws IOException {
  final Set<String> branches = getBranchesToExpose(project);
  if (branches.isEmpty()) {
    removeRepository(project.getId(), project.getPathWithNamespace());
    return null;
  }

  final String projectKey = StringHelper.normalizeDir(project.getPathWithNamespace());
  final GitLabProject oldProject = mapping.get(projectKey);

  if (oldProject != null && oldProject.getProjectId() == project.getId()) {
    final Set<String> oldBranches = oldProject.getBranches().values().stream().map(GitBranch::getShortBranchName).collect(Collectors.toSet());
    if (oldBranches.equals(branches))
      // Old project is good enough already
      return oldProject;
  }

  // TODO: do not drop entire repo here, instead only apply diff - add missing branches and remove unneeded
  removeRepository(project.getId(), project.getPathWithNamespace());

  final Path basePath = ConfigHelper.joinPath(context.getBasePath(), config.getPath());
  final String sha256 = Hashing.sha256().hashString(project.getId().toString(), Charset.defaultCharset()).toString();
  Path repoPath = basePath.resolve(HASHED_PATH).resolve(sha256.substring(0, 2)).resolve(sha256.substring(2, 4)).resolve(sha256 + ".git");
  if (!Files.exists(repoPath))
    repoPath = ConfigHelper.joinPath(basePath, project.getPathWithNamespace() + ".git");
  final LocalContext local = new LocalContext(context, project.getPathWithNamespace());
  local.add(VcsAccess.class, new GitLabAccess(local, config, project.getId()));
  final GitRepository repository = config.getTemplate().create(local, repoPath, branches);
  final GitLabProject newProject = new GitLabProject(local, repository, project.getId());
  if (mapping.compute(projectKey, (key, value) -> value != null && value.getProjectId() == project.getId() ? value : newProject) == newProject) {
    return newProject;
  }
  return null;
}
 
Example #12
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 #13
Source File: GitLabAuthenticationToken.java    From gitlab-oauth-plugin with MIT License 5 votes vote down vote up
public List<GitlabProject> getGroupProjects(final GitlabGroup group) {
	try {
		List<GitlabProject> groupProjects = groupRepositoriesCache.get(group.getPath(), new Callable<List<GitlabProject>>() {
			@Override
			public List<GitlabProject> call() throws Exception {
				return gitLabAPI.getGroupProjects(group);
			}
		});

		return groupProjects;
	} catch (ExecutionException e) {
		LOGGER.log(Level.SEVERE, "an exception was thrown", e);
		throw new RuntimeException("authorization failed for user = " + getName(), e);
	}
}
 
Example #14
Source File: GitLabAuthenticationToken.java    From gitlab-oauth-plugin with MIT License 5 votes vote down vote up
public GitlabProject loadRepository(String repositoryName) {
	try {
		if (gitLabAPI != null && isAuthenticated()) {
			return gitLabAPI.getProject(repositoryName);
		}
	} catch (IOException e) {
		LOGGER.log(Level.WARNING,
				"Looks like a bad GitLab URL OR the Jenkins user does not have access to the repository{0}",
				repositoryName);
	}
	return null;
}
 
Example #15
Source File: GitLabAuthenticationToken.java    From gitlab-oauth-plugin with MIT License 5 votes vote down vote up
public Set<String> listToNames(Collection<GitlabProject> repositories) throws IOException {
	Set<String> names = new HashSet<String>();
	for (GitlabProject repository : repositories) {
		// String ownerName = repository.getOwner().getUsername();
		// String repoName = repository.getName();
		// names.add(ownerName + "/" + repoName);
           // Do not use owner! Project belongs to group does not have owner!
		names.add(repository.getPathWithNamespace());
	}
	return names;
}
 
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: EventHelper.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
private static GitlabProject getMatchingProject(GitLabSCMNavigator navigator, String visibility, String path, Integer id) {
    if (!ALL.id().equals(navigator.getProjectVisibilityId()) && visibility.equalsIgnoreCase(navigator.getProjectVisibilityId())) {
        return null;
    }

    if (!StringUtils.isEmpty(navigator.getProjectSearchPattern()) && path.contains(navigator.getProjectSearchPattern().toLowerCase())) {
        return null;
    }

    return getGitlabProject(navigator, id);
}
 
Example #18
Source File: GitLabLinkAction.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Nonnull
private static GitLabLinkAction create(@CheckForNull String displayName, @Nonnull String iconName, @Nonnull GitlabProject project, String path) {
    return new GitLabLinkAction(
            displayName == null ? "" : displayName,
            iconName,
            project.getWebUrl() + "/" + path);
}
 
Example #19
Source File: GitLabAPI.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
private String projectUrl(GitLabProjectSelector selector, GitLabProjectVisibility visibility, String searchPattern) {
    StringBuilder urlBuilder = new StringBuilder(GitlabProject.URL).append("?membership=true");
    if (!VISIBLE.equals(selector)) {
        urlBuilder.append("&").append(selector.id()).append("=true");
    }
    if (!ALL.equals(visibility)) {
        urlBuilder.append("&visibility=").append(visibility.id());
    }
    if (!StringUtils.isEmpty(searchPattern)) {
        urlBuilder.append("&search=").append(searchPattern);
    }
    return urlBuilder.toString();
}
 
Example #20
Source File: GitLabAPI.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
private boolean unregisterProjectHook(String url, int projectId) throws IOException {
    LOGGER.finer("looking up project-hooks for project " + projectId + "...");
    for (GitlabProjectHook hook : delegate.getProjectHooks(projectId)) {
        if (hook.getUrl().equals(url)) {
            LOGGER.fine("un-registering project-hook for project " + projectId + ": " + url + "...");
            String tailUrl = GitlabProject.URL + PATH_SEP + hook.getProjectId() + GitlabProjectHook.URL + PATH_SEP + hook.getId();
            delegate.retrieve().method("DELETE").to(tailUrl, GitlabProjectHook[].class);
            return true;
        }
    }
    return false;
}
 
Example #21
Source File: GitLabAPI.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
public List<GitlabRepositoryTree> getTree(int id, String ref, String path) throws GitLabAPIException {
    try {
        Query query = new Query()
                .appendIf("path", path)
                .appendIf("ref", ref);

        query.append("per_page","10000");
        String tailUrl = GitlabProject.URL + "/" + id + "/repository" + GitlabRepositoryTree.URL + query.toString();
        LOGGER.fine("tailurl: " + tailUrl);
        GitlabRepositoryTree[] tree = delegate.retrieve().to(tailUrl, GitlabRepositoryTree[].class);
        return Arrays.asList(tree);
    } catch (Exception e) {
        throw new GitLabAPIException(e);
    }
}
 
Example #22
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 #23
Source File: EventHelper.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 4 votes vote down vote up
static GitlabProject getMatchingProject(GitLabSCMNavigator navigator, PushHook hook) {
    Project project = hook.getProject();
    return getMatchingProject(navigator, GitLabProjectVisibility.byLevel(project.getVisibilityLevel()).id(), project.getPathWithNamespace(), hook.getProjectId());
}
 
Example #24
Source File: EventHelper.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 4 votes vote down vote up
static GitlabProject getMatchingProject(GitLabSCMNavigator navigator, SystemHook hook) {
    return getMatchingProject(navigator, hook.getProjectVisibility(), hook.getPathWithNamespace(), hook.getProjectId());
}
 
Example #25
Source File: GitLabSCMIcons.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 4 votes vote down vote up
private static String groupAvatarUrl(GitlabProject project, String connectionName) throws GitLabAPIException {
    GitlabNamespace namespace = project.getNamespace();
    GitLabGroup group = gitLabAPI(connectionName).getGroup(namespace.getId());
    return group.getAvatarUrl();
}
 
Example #26
Source File: GitLabLinkAction.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 4 votes vote down vote up
@Nonnull
public static GitLabLinkAction toCommit(GitlabProject project, String hash) {
    return create(Messages.GitLabLink_DisplayName_Commit(), ICON_COMMIT, project,
            "commits/" + hash);
}
 
Example #27
Source File: GitLabLinkAction.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 4 votes vote down vote up
@Nonnull
public static GitLabLinkAction toBranch(GitlabProject project, String branchName) {
    return create(Messages.GitLabLink_DisplayName_Branch(), ICON_BRANCH, project, "tree/" + branchName);
}
 
Example #28
Source File: GitLabLinkAction.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 4 votes vote down vote up
@Nonnull
public static GitLabLinkAction toProject(GitlabProject project) {
    return create(Messages.GitLabLink_DisplayName_Project(), ICON_PROJECT, project.getWebUrl());
}