3 * Copyright (C) 2009-2021 SonarSource SA
4 * mailto:info AT sonarsource DOT com
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 3 of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 package org.sonar.alm.client.bitbucketserver;
22 import com.google.gson.Gson;
23 import com.google.gson.GsonBuilder;
24 import com.google.gson.JsonParseException;
25 import com.google.gson.JsonSyntaxException;
26 import com.google.gson.annotations.SerializedName;
27 import java.io.IOException;
28 import java.net.HttpURLConnection;
29 import java.util.Optional;
30 import java.util.function.Function;
31 import java.util.stream.Collectors;
32 import java.util.stream.Stream;
33 import javax.annotation.Nullable;
34 import okhttp3.HttpUrl;
35 import okhttp3.MediaType;
36 import okhttp3.OkHttpClient;
37 import okhttp3.Request;
38 import okhttp3.RequestBody;
39 import okhttp3.Response;
40 import okhttp3.ResponseBody;
41 import org.sonar.alm.client.TimeoutConfiguration;
42 import org.sonar.api.server.ServerSide;
43 import org.sonar.api.utils.log.Logger;
44 import org.sonar.api.utils.log.Loggers;
45 import org.sonarqube.ws.client.OkHttpClientBuilder;
47 import static java.lang.String.format;
48 import static java.util.Locale.ENGLISH;
49 import static org.sonar.api.internal.apachecommons.lang.StringUtils.removeEnd;
52 public class BitbucketServerRestClient {
54 private static final Logger LOG = Loggers.get(BitbucketServerRestClient.class);
55 private static final String GET = "GET";
56 protected static final String UNABLE_TO_CONTACT_BITBUCKET_SERVER = "Unable to contact Bitbucket server";
58 protected final OkHttpClient client;
60 public BitbucketServerRestClient(TimeoutConfiguration timeoutConfiguration) {
61 OkHttpClientBuilder okHttpClientBuilder = new OkHttpClientBuilder();
62 client = okHttpClientBuilder
63 .setConnectTimeoutMs(timeoutConfiguration.getConnectTimeout())
64 .setReadTimeoutMs(timeoutConfiguration.getReadTimeout())
68 public RepositoryList getRepos(String serverUrl, String token, @Nullable String project, @Nullable String repo) {
69 String projectOrEmpty = Optional.ofNullable(project).orElse("");
70 String repoOrEmpty = Optional.ofNullable(repo).orElse("");
71 HttpUrl url = buildUrl(serverUrl, format("/rest/api/1.0/repos?projectname=%s&name=%s", projectOrEmpty, repoOrEmpty));
72 return doGet(token, url, r -> buildGson().fromJson(r.body().charStream(), RepositoryList.class));
75 public Repository getRepo(String serverUrl, String token, String project, String repoSlug) {
76 HttpUrl url = buildUrl(serverUrl, format("/rest/api/1.0/projects/%s/repos/%s", project, repoSlug));
77 return doGet(token, url, r -> buildGson().fromJson(r.body().charStream(), Repository.class));
80 public ProjectList getProjects(String serverUrl, String token) {
81 HttpUrl url = buildUrl(serverUrl, "/rest/api/1.0/projects");
82 return doGet(token, url, r -> buildGson().fromJson(r.body().charStream(), ProjectList.class));
85 protected static HttpUrl buildUrl(@Nullable String serverUrl, String relativeUrl) {
86 if (serverUrl == null || !(serverUrl.toLowerCase(ENGLISH).startsWith("http://") || serverUrl.toLowerCase(ENGLISH).startsWith("https://"))) {
87 throw new IllegalArgumentException("url must start with http:// or https://");
89 return HttpUrl.parse(removeEnd(serverUrl, "/") + relativeUrl);
92 protected <G> G doGet(String token, HttpUrl url, Function<Response, G> handler) {
93 Request request = prepareRequestWithBearerToken(token, GET, url, null);
94 return doCall(request, handler);
97 protected static Request prepareRequestWithBearerToken(String token, String method, HttpUrl url, @Nullable RequestBody body) {
98 return new Request.Builder()
101 .addHeader("Authorization", "Bearer " + token)
102 .addHeader("x-atlassian-token", "no-check")
106 protected <G> G doCall(Request request, Function<Response, G> handler) {
107 try (Response response = client.newCall(request).execute()) {
108 handleError(response);
109 return handler.apply(response);
110 } catch (JsonSyntaxException e) {
111 throw new IllegalArgumentException(UNABLE_TO_CONTACT_BITBUCKET_SERVER + ", got an unexpected response", e);
112 } catch (IOException e) {
113 throw new IllegalArgumentException(UNABLE_TO_CONTACT_BITBUCKET_SERVER, e);
117 protected static void handleError(Response response) throws IOException {
118 if (!response.isSuccessful()) {
119 String errorMessage = getErrorMessage(response.body());
120 LOG.debug(UNABLE_TO_CONTACT_BITBUCKET_SERVER + ": {} {}", response.code(), errorMessage);
121 if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) {
122 throw new IllegalArgumentException("Invalid personal access token");
124 throw new IllegalArgumentException(UNABLE_TO_CONTACT_BITBUCKET_SERVER);
128 protected static boolean equals(@Nullable MediaType first, @Nullable MediaType second) {
129 String s1 = first == null ? null : first.toString().toLowerCase(ENGLISH).replace(" ", "");
130 String s2 = second == null ? null : second.toString().toLowerCase(ENGLISH).replace(" ", "");
131 return s1 != null && s2 != null && s1.equals(s2);
134 protected static String getErrorMessage(ResponseBody body) throws IOException {
135 if (equals(MediaType.parse("application/json;charset=utf-8"), body.contentType())) {
137 return Stream.of(buildGson().fromJson(body.charStream(), Errors.class).errorData)
138 .map(e -> e.exceptionName + " " + e.message)
139 .collect(Collectors.joining("\n"));
140 } catch (JsonParseException e) {
141 return body.string();
144 return body.string();
147 protected static Gson buildGson() {
148 return new GsonBuilder()
152 protected static class Errors {
154 @SerializedName("errors")
155 public Error[] errorData;
158 // http://stackoverflow.com/a/18645370/229031
161 public static class Error {
162 @SerializedName("message")
163 public String message;
165 @SerializedName("exceptionName")
166 public String exceptionName;
169 // http://stackoverflow.com/a/18645370/229031