package io.gitlab.jfronny.inceptum.util.api; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; 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; 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 { 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>() {}.getType(); private static final Type jobListType = new TypeToken>() {}.getType(); private static final Type packageFileInfoListType = new TypeToken>() {}.getType(); public static GitlabProject getProject(Long projectId) throws IOException { return downloadObject("projects/" + projectId, GitlabProject.class); } public static List getPackages(GitlabProject project) throws IOException { List list = downloadObject("projects/" + project.id + "/packages", packageInfoListType); list.sort((left, right) -> right.created_at.compareTo(left.created_at)); return list; } public static List 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 isValid) throws IOException { int page = 0; while (true) { List 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 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); } } }