GitLab4J™ API (gitlab4j-api) provides a full featured and easy to consume Java library for working with GitLab repositories via the GitLab REST API. Additionally, full support for working with GitLab webhooks and system hooks is also provided.
- GitLab Server Version Support
- Using GitLab4J-API
- Making API Calls
GitLab4J-API supports version 11.0+ of GitLab Community Edition (gitlab-ce) and GitLab Enterprise Edition (gitlab-ee).
GitLab released GitLab Version 11.0 in June of 2018 which included many major changes to GitLab. If you are using GitLab server earlier than version 11.0, it is highly recommended that you either update your GitLab install or use a version of this library that was released around the same time as the version of GitLab you are using.
注意:
As of GitLab 11.0 support for the GitLab API v3 has been removed from the GitLab server (see https://about.gitlab.com/2018/06/01/api-v3-removal-impending/). Support for GitLab API v3 will be removed from this library sometime in 2019. If you are utilizing the v3 support, please update your code to use GitLab API v4.
As of GitLab4J-API 4.8.0, Java 8+ is now required to use GitLab4J-API.
To utilize GitLab4J™ API in your Java project, simply add the following dependency to your project's build file:
Gradle: build.gradle
dependencies {
...
compile group: 'org.gitlab4j', name: 'gitlab4j-api', version: '4.14.27'
}
NOTE: 在使用4.5之前的Gradle时,拉取依赖关系可能会失败。. See Gradle issue 3065
Maven: pom.xml
<dependency>
<groupId>org.gitlab4j</groupId>
<artifactId>gitlab4j-api</artifactId>
<version>4.14.27</version>
</dependency>
Ivy and SBT
There have been reports of problems resolving some dependencies when using Ivy or SBT, for help resolving those issues see:
JAX-RS API Issue #571
JAX-RS API Issue #572
GitLab4J-API is quite simple to use, all you need is the URL to your GitLab server and the Personal Access Token from your GitLab Account Settings page. Once you have that info it is as simple as:
// 创建一个GitLabApi实例与GitLab服务器进行通信
GitLabApi gitLabApi = new GitLabApi("http://your.gitlab.server.com", "YOUR_PERSONAL_ACCESS_TOKEN");
// 获取您的账户可以访问的项目列表
List<Project> projects = gitLabApi.getProjectApi().getProjects();
你也可以用用户名和密码登录到你的GitLab服务器:
// Log in to the GitLab server using a username and password
GitLabApi gitLabApi = GitLabApi.oauth2Login("http://your.gitlab.server.com", "username", "password");
在GitLab4J-API 4.6.6 版本中,所有的API请求都支持像其他用户一样执行API调用,前提是你是管理员:
// 创建一个GitLabApi实例来与GitLab服务器通信(必须是管理员)
GitLabApi gitLabApi = new GitLabApi("http://your.gitlab.server.com", "YOUR_PERSONAL_ACCESS_TOKEN");
// sudo为不同的用户,本例中的用户名为 "johndoe",以后所有的调用都将以 "johndoe "的身份进行。
gitLabApi.sudo("johndoe")
// 要关闭sudo模式
gitLabApi.unsudo();
从 GitLab4J-API 4.14.21开始,增加了对API客户端的连接和读取超时设置的支持。:
GitLabApi gitLabApi = new GitLabApi("http://your.gitlab.com", "YOUR_PERSONAL_ACCESS_TOKEN", proxyConfig);
// Set the connect timeout to 1 second and the read timeout to 5 seconds
gitLabApi.setRequestTimeout(1000, 5000);
从GitLab4J-API 4.8.2开始,增加了对使用HTTP代理服务器连接到GitLab服务器的支持。:
// Log in to the GitLab server using a proxy server (with basic auth on proxy)
Map<String, Object> proxyConfig = ProxyClientConfig.createProxyClientConfig(
"http://your-proxy-server", "proxy-username", "proxy-password");
GitLabApi gitLabApi = new GitLabApi("http://your.gitlab.com", "YOUR_PERSONAL_ACCESS_TOKEN", null, proxyConfig);
// Log in to the GitLab server using a proxy server (no auth on proxy)
Map<String, Object> proxyConfig = ProxyClientConfig.createProxyClientConfig("http://your-proxy-server");
GitLabApi gitLabApi = new GitLabApi("http://your.gitlab.com", "YOUR_PERSONAL_ACCESS_TOKEN", null, proxyConfig);
// Log in to the GitLab server using an NTLM (Windows DC Microsoft安全协议) proxy
Map<String, Object> ntlmProxyConfig = ProxyClientConfig.createNtlmProxyClientConfig(
"http://your-proxy-server", "windows-username", "windows-password", "windows-workstation", "windows-domain");
GitLabApi gitLabApi = new GitLabApi("http://your.gitlab.com", "YOUR_PERSONAL_ACCESS_TOKEN", null, ntlmProxyConfig);
关于接受代理配置(clientConfiguration parameter)的完整方法列表,请参见GitLabApi类的Javadoc
从GitLab4J-API 4.2.0开始已经增加了对GitLab API V4的支持。如果您的应用程序需要GitLab API V3。 您仍然可以通过以下方式创建GitLab4J-API实例来使用GitLab4J-API。:
// Create a GitLabApi instance to communicate with your GitLab server using GitLab API V3
GitLabApi gitLabApi = new GitLabApi(ApiVersion.V3, "http://your.gitlab.server.com", "YOUR_PRIVATE_TOKEN");
注意:
从GitLab 11.0开始,GitLab服务器上已经删除了对GitLab API v3的支持(见https://about.gitlab.com/2018/06/01/api-v3-removal-impending/)。对 GitLab API v3 的支持将在 2019 年的某个时候从这个库中删除。如果您正在使用 v3 支持,请更新您的代码以使用 GitLab API v4。
As of GitLab4J-API 4.8.39 support has been added to log the requests to and the responses from the
GitLab API.
在GitLabApi实例上使用以下方法之一启用日志记录:
GitLabApi gitLabApi = new GitLabApi("http://your.gitlab.server.com", "YOUR_PERSONAL_ACCESS_TOKEN");
// Log using the shared logger and default level of FINE
gitLabApi.enableRequestResponseLogging();
// Log using the shared logger and the INFO level
gitLabApi.enableRequestResponseLogging(java.util.logging.Level.INFO);
// Log using the specified logger and the INFO level
gitLabApi.enableRequestResponseLogging(yourLoggerInstance, java.util.logging.Level.INFO);
// Log using the shared logger, at the INFO level, and include up to 1024 bytes of entity logging
gitLabApi.enableRequestResponseLogging(java.util.logging.Level.INFO, 1024);
// Log using the specified logger, at the INFO level, and up to 1024 bytes of entity logging
gitLabApi.enableRequestResponseLogging(yourLoggerInstance, java.util.logging.Level.INFO, 1024);
GitLab4J-API提供了一个易于使用的分页机制,可以从GitLab API中翻阅结果列表。 下面是几个关于如何使用分页器的例子。
// Get a Pager instance that will page through the projects with 10 projects per page
Pager<Project> projectPager = gitlabApi.getProjectApi().getProjects(10);
// Iterate through the pages and print out the name and description
while (projectsPager.hasNext()) {
for (Project project : projectPager.next()) {
System.out.println(project.getName() + " -: " + project.getDescription());
}
}
从GitLab4J-API 4.9.2开始,你还可以使用Pager实例将所有项目作为一个单独的列表来获取:
// Get a Pager instance so we can load all the projects into a single list, 10 items at a time:
Pager<Project> projectPager = gitlabApi.getProjectsApi().getProjects(10);
List<Project> allProjects = projectPager.all();
从GitLab4J-API 4.9.2开始,所有返回List结果的GitLabJ-API方法都有一个类似于Java 8的Stream方法。 返回Stream的方法使用以下命名方法: getXxxxxStream()
.
重要的
The built-in methods that return a Stream do so using eager evaluation, meaning all items are pre-fetched from the GitLab server and a Stream is returned which will stream those items. Eager evaluation不支持从服务器上并行读取数据,但是它允许在数据获取后并行处理Stream.
To stream using lazy evaluation, use the GitLab4J-API methods that return a Pager
instance, and then call the lazyStream()
method on the Pager
instance to create a lazy evaluation Stream. The Stream utilizes the Pager
instance to page through the available items. A lazy Stream 不支持并行操作或跳过.
// Stream the visible projects printing out the project name.
Stream<Project> projectStream = gitlabApi.getProjectApi().getProjectsStream();
projectStream.map(Project::getName).forEach(name -> System.out.println(name));
// Operate on the stream in parallel, this example sorts User instances by username
// NOTE: Fetching of the users is not done in parallel,
// only the sorting of the users is a parallel operation.
Stream<User> stream = gitlabApi.getUserApi().getUsersStream();
List<User> users = stream.parallel().sorted(comparing(User::getUsername)).collect(toList());
// Get a Pager instance to that will be used to lazily stream Project instances.
// In this example, 10 Projects per page will be pre-fetched.
Pager<Project> projectPager = gitlabApi.getProjectApi().getProjects(10);
// Lazily stream the Projects, printing out each project name, limit the output to 5 project names
projectPager.lazyStream().limit(5).map(Project::getName).forEach(name -> System.out.println(name));
GitLab4J-API supports Java 8 Optional<T> 可实现单项返回. Here is an example on how to use the Java 8 Optional<T> API calls:
Optional<Group> optionalGroup = gitlabApi.getGroupApi().getOptionalGroup("my-group-path");
if (optionalGroup.isPresent())
return optionalGroup.get();
return gitlabApi.getGroupApi().addGroup("my-group-name", "my-group-path");
GitLab issues allow for time tracking. The following time units are currently available:
- months (mo)
- weeks (w)
- days (d)
- hours (h)
- minutes (m)
Conversion rates are 1mo = 4w, 1w = 5d and 1d = 8h.
为了便于消费,并将关注点分开,API被分解成了子API类。. GitLab4J 子 API 类通常与 GitLab API中的 API 文档有一对一的关系。以下是 GitLab4J 子 API 类与 GitLab API 文档的映射示例。:
org.gitlab4j.api.GroupApi
-> https://docs.gitlab.com/ce/api/groups.html
org.gitlab4j.api.MergeRequestApi
-> https://docs.gitlab.com/ce/api/merge_requests.html
org.gitlab4j.api.ProjectApi
-> https://docs.gitlab.com/ce/api/projects.html
org.gitlab4j.api.UserApi
-> https://docs.gitlab.com/ce/api/users.html
以下是可用的子 API 列表以及每个 API 的使用示例。请参阅Javadocs了解每个子 API 的可用方法的完整列表。
ApplicationsApi
ApplicationSettingsApi
AwardEmojiApi
BoardsApi
CommitsApi
ContainerRegistryApi
DeployKeysApi
DiscussionsApi
EnvironmentsApi
EpicsApi
EventsApi
GroupApi
HealthCheckApi
ImportExportApi
IssuesApi
JobApi
LabelsApi
LicenseApi
LicenseTemplatesApi
LabelsApi
MergeRequestApi
MilestonesApi
NamespaceApi
NotesApi
NotificationSettingsApi
PackagesApi
PipelineApi
ProjectApi
ProtectedBranchesApi
ReleasesApi
RepositoryApi
RepositoryFileApi
ReourceLabelEventsApi
RunnersApi
SearchApi
ServicesApi
SessionApi
SnippetsApi
SystemHooksApi
TodosApi
UserApi
WikisApi
// Add an OAUTH Application to GitLab
ApplicationScope[] scopes = {ApplicationScope.SUDO, ApplicationScope.PROFILE};
gitLabApi.getApplicationsApi().createApplication("My OAUTH Application", "https//example.com/myapp/callback", scopes);
// Get the current GitLab server application settings
ApplicationSettings appSettings = gitLabApi.getApplicationSettingsApi().getAppliationSettings();
// Get a list of AwardEmoji belonging to the specified issue (group ID = 1, issues IID = 1)
List<AwardEmoji> awardEmojis = gitLabApi.getAwardEmojiApi().getIssuAwardEmojis(1, 1);
// Get a list of the Issue Boards belonging to the specified project
List<Board> boards = gitLabApi.getBoardsApi().getBoards(projectId);
// 获取在指定的时间窗口内与指定分支相关的提交列表
// Get a list of commits associated with the specified branch that fall within the specified time window
// This uses the ISO8601 date utilities the in org.gitlab4j.api.utils.ISO8601 class
Date since = ISO8601.toDate("2017-01-01T00:00:00Z");
Date until = new Date(); // now
List<Commit> commits = gitLabApi.getCommitsApi().getCommits(1234, "new-feature", since, until);
// Get a list of the registry repositories belonging to the specified project
List<RegistryRepository> registryRepos = gitLabApi.ContainerRegistryApi().getRepositories(projectId);
// Get a list of DeployKeys for the authenticated user
List<DeployKey> deployKeys = gitLabApi.getDeployKeysApi().getDeployKeys();
// Get a list of Discussions for the specified merge request
List<Discussion> discussions = gitLabApi.getDiscussionsApi().getMergeRequestDiscussions(projectId, mergeRequestIid);
// Get a list of Environments for the specified project
List<Environment> environments = gitLabApi.getEnvironmentsApi().getEnvironments(projectId);
// Get a list epics of the requested group and its subgroups.
List<Epic> epics = gitLabApi.getEpicsApi().getEpics(1);
// Get a list of Events for the authenticated user
Date after = new Date(0); // After Epoch
Date before = new Date(); // Before now
List<Event> events = gitLabApi.getEventsApi().getAuthenticatedUserEvents(null, null, before, after, DESC);
// Get a list of groups that you have access to
List<Group> groups = gitLabApi.getGroupApi().getGroups();
// Get the liveness endpoint health check results. Assumes ip_whitelisted per:
// https://docs.gitlab.com/ee/administration/monitoring/ip_whitelist.html
HealthCheckInfo healthCheck = gitLabApi.getHealthCheckApi().getLiveness();
// Schedule a project export for the specified project ID
gitLabApi.getImportExportApi().scheduleExport(projectId);
// Get the project export status for the specified project ID
ExportStatus exportStatus = gitLabApi.getImportExportApi().getExportStatus(projectId);
// Get a list of issues for the specified project ID
List<Issue> issues = gitLabApi.getIssuesApi().getIssues(1234);
// Get a list of jobs for the specified project ID
List<Job> jobs = gitLabApi.getJobApi().getJobs(1234);
// Get a list of labels for the specified project ID
List<Label> labels = gitLabApi.getLabelsApi().getLabels(1234);
// Retrieve information about the current license
License license = gitLabApi.getLicenseApi().getLicense();
// Get a list of open sourcse license templates
List<LicenseTemplate> licenses = gitLabApi.getLicenseTemplatesApi().getLicenseTemplates();
// Get a list of the merge requests for the specified project
List<MergeRequest> mergeRequests = gitLabApi.getMergeRequestApi().getMergeRequests(1234);
// Get a list of the milestones for the specified project
List<Milestone> milestones = gitLabApi.getMilestonesApi().getMilestones(1234);
// Get all namespaces that match "foobar" in their name or path
List<Namespace> namespaces = gitLabApi.getNamespaceApi().findNamespaces("foobar");
// Get a list of the issues's notes for project ID 1234, issue IID 1
List<Note> notes = gitLabApi.getNotesApi().getNotes(1234, 1);
// Get the current global notification settings
NotificationSettings settings = gitLabApi.getNotificationSettingsApi().getGlobalNotificationSettings();
// Get all packages for the specified project ID
List<Package> packages = gitLabApi.getPackagesApi().getPackages(1234);
// Get all pipelines for the specified project ID
List<Pipeline> pipelines = gitLabApi.getPipelineApi().getPipelines(1234);
// Get a list of accessible projects
public List<Project> projects = gitLabApi.getProjectApi().getProjects();
// Create a new project
Project projectSpec = new Project()
.withName("my-project")
.withDescription("My project for demonstration.")
.withIssuesEnabled(true)
.withMergeRequestsEnabled(true)
.withWikiEnabled(true)
.withSnippetsEnabled(true)
.withPublic(true);
Project newProject = gitLabApi.getProjectApi().createProject(projectSpec);
List<ProtectedBranch> branches = gitLabApi.getProtectedBranchesApi().getProtectedBranches(project.getId());
// Get a list of releases for the specified project
List<Release> releases = gitLabApi.getReleasesApi().getReleases(projectId);
// Get a list of repository branches from a project, sorted by name alphabetically
List<Branch> branches = gitLabApi.getRepositoryApi().getBranches(projectId);
// Search repository branches from a project, by name
List<Branch> branches = gitLabApi.getRepositoryApi().getBranches(projectId, searchTerm);
// Get info (name, size, ...) and the content from a file in repository
RepositoryFile file = gitLabApi.getRepositoryFileApi().getFile("file-path", 1234, "ref");
// Get the label events for the specified merge request
List<LabelEvent> labelEvents = gitLabApi.getResourceLabelEventsApi()
.getMergeRequestLabelEvents(projectId, mergeRequestIid);
// Get All Runners.
List<Runner> runners = gitLabApi.getRunnersApi().getAllRunners();
// Do a global search for Projects
List<?> projects = gitLabApi.getSearchApi().globalSearch(SearchScope.PROJECTS, "text-to-search-for");
// Activate/Update the Slack Notifications service
SlackService slackService = new SlackService()
.withMergeRequestsEvents(true)
.withWebhook("https://hooks.slack.com/services/ABCDEFGHI/KJLMNOPQR/wetrewq7897HKLH8998wfjjj")
.withUsername("GitLab4J");
gitLabApi.getServicesApi().updateSlackService("project-path", slackService);
// Log in to the GitLab server and get the session info
gitLabApi.getSessionApi().login("your-username", "your-email", "your-password");
// Get a list of the authenticated user's snippets
List<Snippet> snippets = gitLabApi.getSnippetsApi().getSnippets();
// Get a list of installed system hooks
List<SystemHook> hooks = gitLabApi.getSystemHooksApi().getSystemHooks();
// Get a list of all pending todos for the current user
List<Todo> todos = gitLabApi.getTodosApi().gePendingTodos();
// Get the User info for user_id 1
User user = gitLabApi.getUserApi().getUser(1);
// Create a new user with no password who will recieve a reset password email
User userConfig = new User()
.withEmail("jdoe@example.com")
.withName("Jane Doe")
.withUsername("jdoe");
String password = null;
boolean sendResetPasswordEmail = true;
gitLabApi.getUserApi().createUser(userConfig, password, sendResetPasswordEmail);
// Get a list of pages in project wiki
List<WikiPage> wikiPages = gitLabApi.getWikisApi().getPages();