JGit and Gitlab API

Define a composite service that propose high-level services : served by gitlab api or JGit according to the case

We set the git property sslVerify to false to bypass ssl checks of the gitlab server.
Here how the gitlabToken and gitlab.server.url fields are valued (spring boot way):
gitlab.server.url=https://gitlab.foo.com/foo-ns/foo-project.git
gitlab.token=tokenFooBar

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
 
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.storage.file.FileBasedConfig;
import org.eclipse.jgit.util.FS;
import org.eclipse.jgit.util.SystemReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
 
@Service
public class GitlabCompositeService {
 
 
    private GitlabApiRequestService gitlabApiRequestService ;
    private String gitlabServerUrl;
    private String gitlabToken;
    private ObjectMapper objectMapper;
 
    public GitlabCompositeService(GitlabApiRequestService gitlabApiRequestService, 
                         @Value("${gitlab.server.url}") String gitlabServerUrl, @Value("${gitlab.token}") String gitlabToken,
                         ObjectMapper objectMapper) {       
        this.GitlabApiRequestService = GitlabApiRequestService;
        this.gitlabServerUrl = gitlabServerUrl;
        this.gitlabToken = gitlabToken;
        this.objectMapper = objectMapper;
    }
 
    // JGIT Example
    public List<String> getBranchList() throws GitAPIException, IOException, ConfigInvalidException {
 
        FileBasedConfig config = SystemReader.getInstance().openUserConfig(null, FS.DETECTED);
 
            config.load();
            config.setBoolean(
                    "http",
                    null,
                    "sslVerify", false);
            config.save();
 
 
        Collection<Ref> refs = Git.lsRemoteRepository()
                                  .setHeads(true)
                                  .setTags(true)
                                  .setRemote("https://oauth2:" + gitlabToken + "@" + gitlabServerUrl)
                                  .call();
 
        List<String> branchesAndTags = refs.stream()
                                           .map(r -> {
                                               String nameWithUserFriendlyPrefix = r.getName()
                                                                                    .replaceFirst("refs/heads/", "branches/")
                                                                                    .replaceFirst("refs/tags/", "tags/");
                                               return nameWithUserFriendlyPrefix;
 
                                           })
                                           .sorted()
                                           .collect(Collectors.toList());
 
 
        return branchesAndTags;
    }
 
     // Gitlab API Example
     public GitCommitsAndDiffs compareCommits(String fromCommitHash, String toCommitHash) throws Exception {        
 
        String body = gitlabApiRequestService.invokeGitlabApiWithGet("/repository/compare?from=" + fromCommitHash + "&to=" + toCommitHash +"&straight=true");
 
        JsonNode root = objectMapper.readTree(body);
        List<GitCommit> gitCommits = new ArrayList<>();
        if (root.has("commits")) {
            gitCommits = objectMapper.readValue(root.at("/commits")
                                                    .toString(), new TypeReference<>() {
            });
        }
 
        gitCommits.sort(Comparator.comparing(GitCommit::getDate).reversed());
 
        List<GitDiff> gitDiffs = new ArrayList<>();
        if (root.has("diffs")) {
            gitDiffs = objectMapper.readValue(root.at("/diffs")
                                                  .toString(), new TypeReference<>() {
            });
 
        }
        return new GitCommitsAndDiffs(gitCommits, gitDiffs);
 
    }
 
    // Gitlab API Example
    public String findLastCommitOfBranchOrTag(String ref) throws Exception {
        String body = gitlabApiRequestService.invokeGitlabApiWithGet("/repository/commits/" + ref);
        JsonNode root = objectMapper.readTree(body);
        if (root.isObject() && !root.isArray()) {
            String hash = objectMapper.readValue(root.at("/id")
                                                     .toString(), String.class);
            return hash;
        } else {
            throw new IllegalArgumentException("LastCommit not found");
        }
    }
 
 
    private String invokeGitlabApiWithGet(String queryString) throws Exception {
        return gitlabApiRequestService.invokeGitlabApiWithGet(queryString);
    }
 
 
}

Define a generic service that performs gitlab api requests with ssl checks disabled

Here how the gitlabToken and gitlabApiBaseUrl fields are valued (spring boot way):
gitlab.api.base-url=https://gitlab.foo.com/api/v4/projects/4581
gitlab.token=tokenFooBar
Here 4581 is the project id in gitlab.

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
 
@Service
public class GitlabApiRequestService {
 
    private static TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
 
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
 
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    }};
 
 
    private String gitlabToken;
    private String gitlabApiBaseUrl;
 
 
    public GitlabApiRequestService(@Value("${gitlab.token}") String gitlabToken, @Value("${gitlab.api.base-url}") String gitlabApiBaseUrl) {
        this.gitlabToken = gitlabToken;
        this.gitlabApiBaseUrl = gitlabApiBaseUrl;
    }
 
    public String invokeGitlabApiWithGet(String queryString) throws Exception {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, new SecureRandom());
 
        HttpClient httpClient = HttpClient.newBuilder()
                                          .sslContext(sslContext)
                                          .build();
 
        HttpRequest httpRequest = HttpRequest.newBuilder()
                                             .uri(URI.create(gitlabApiBaseUrl + queryString))
                                             .GET()
                                             .header("PRIVATE-TOKEN", gitlabToken)
                                             .build();
 
        HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
        return httpResponse.body();
    }
}
Ce contenu a été publié dans Non classé. Vous pouvez le mettre en favoris avec ce permalien.

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *