Inceptum/wrapper/src/main/java/io/gitlab/jfronny/inceptum/util/api/GitlabApi.java

62 lines
2.7 KiB
Java
Raw Normal View History

package io.gitlab.jfronny.inceptum.util.api;
import com.google.gson.Gson;
2021-12-11 14:21:58 +01:00
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
2021-12-11 14:21:58 +01:00
import io.gitlab.jfronny.inceptum.gson.ComparableVersionAdapter;
import io.gitlab.jfronny.inceptum.model.ComparableVersion;
import io.gitlab.jfronny.inceptum.model.gitlab.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
2021-12-11 14:21:58 +01:00
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.net.URL;
import java.util.List;
import java.util.function.Predicate;
public class GitlabApi {
2021-12-11 14:21:58 +01:00
private static final Gson GSON = new GsonBuilder()
.registerTypeAdapter(ComparableVersion.class, new ComparableVersionAdapter())
.excludeFieldsWithModifiers(Modifier.TRANSIENT)
.excludeFieldsWithModifiers(Modifier.PRIVATE)
.setPrettyPrinting()
.create();
private static final Type packageInfoListType = new TypeToken<List<GitlabPackage>>() {}.getType();
private static final Type jobListType = new TypeToken<List<GitlabJob>>() {}.getType();
private static final Type packageFileInfoListType = new TypeToken<List<GitlabPackageFile>>() {}.getType();
public static GitlabProject getProject(Long projectId) throws IOException {
return downloadObject("projects/" + projectId, GitlabProject.class);
}
public static List<GitlabPackage> getPackages(GitlabProject project) throws IOException {
2021-12-11 14:21:58 +01:00
List<GitlabPackage> list = downloadObject("projects/" + project.id + "/packages", packageInfoListType);
list.sort((left, right) -> right.created_at.compareTo(left.created_at));
return list;
}
public static List<GitlabJob> getJobs(GitlabProject project, Long pipelineId) throws IOException {
return downloadObject("projects/" + project.id + "/pipelines/" + pipelineId + "/jobs", jobListType);
}
public static GitlabPackageFile getFile(GitlabProject project, GitlabPackage packageInfo, Predicate<GitlabPackageFile> isValid) throws IOException {
int page = 0;
while (true) {
List<GitlabPackageFile> files = downloadObject("projects/" + project.id + "/packages/" + packageInfo.id + "/package_files?per_page=100&page=" + ++page, packageFileInfoListType);
if (files.isEmpty()) return null;
for (GitlabPackageFile file : files) {
if (isValid.test(file))
return file;
}
}
}
public static <T> T downloadObject(String source, Type type) throws IOException {
try (InputStream is = new URL("https://gitlab.com/api/v4/" + source).openStream(); InputStreamReader isr = new InputStreamReader(is)) {
return GSON.fromJson(isr, type);
}
}
}