3 * Copyright (C) 2009-2022 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.github;
22 import java.io.IOException;
23 import java.net.MalformedURLException;
25 import java.util.Optional;
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28 import javax.annotation.CheckForNull;
29 import javax.annotation.Nullable;
30 import okhttp3.FormBody;
31 import okhttp3.MediaType;
32 import okhttp3.OkHttpClient;
33 import okhttp3.Request;
34 import okhttp3.RequestBody;
35 import okhttp3.ResponseBody;
36 import org.sonar.alm.client.TimeoutConfiguration;
37 import org.sonar.alm.client.github.security.AccessToken;
38 import org.sonar.api.utils.log.Logger;
39 import org.sonar.api.utils.log.Loggers;
40 import org.sonarqube.ws.client.OkHttpClientBuilder;
42 import static com.google.common.base.Preconditions.checkArgument;
43 import static java.net.HttpURLConnection.HTTP_CREATED;
44 import static java.net.HttpURLConnection.HTTP_NO_CONTENT;
45 import static java.net.HttpURLConnection.HTTP_OK;
46 import static java.util.Optional.empty;
47 import static java.util.Optional.of;
48 import static java.util.Optional.ofNullable;
50 public class GithubApplicationHttpClientImpl implements GithubApplicationHttpClient {
52 private static final Logger LOG = Loggers.get(GithubApplicationHttpClientImpl.class);
53 private static final Pattern NEXT_LINK_PATTERN = Pattern.compile("<([^<]+)>; rel=\"next\"");
54 private static final String GITHUB_API_VERSION_JSON = "application/vnd.github.v3+json";
55 private static final String ANTIOPE_PREVIEW_JSON = "application/vnd.github.antiope-preview+json";
56 private static final String MACHINE_MAN_PREVIEW_JSON = "application/vnd.github.machine-man-preview+json";
58 private final OkHttpClient client;
60 public GithubApplicationHttpClientImpl(TimeoutConfiguration timeoutConfiguration) {
61 client = new OkHttpClientBuilder()
62 .setConnectTimeoutMs(timeoutConfiguration.getConnectTimeout())
63 .setReadTimeoutMs(timeoutConfiguration.getReadTimeout())
64 .setFollowRedirects(false)
69 public GetResponse get(String appUrl, AccessToken token, String endPoint) throws IOException {
70 validateEndPoint(endPoint);
72 try (okhttp3.Response response = client.newCall(newGetRequest(appUrl, token, endPoint)).execute()) {
73 int responseCode = response.code();
74 if (responseCode != HTTP_OK) {
75 LOG.warn("GET response did not have expected HTTP code (was {}): {}", responseCode, attemptReadContent(response));
76 return new GetResponseImpl(responseCode, null, null);
78 return new GetResponseImpl(responseCode, readContent(response.body()).orElse(null), readNextEndPoint(response));
82 private static void validateEndPoint(String endPoint) {
83 checkArgument(endPoint.startsWith("/") || endPoint.startsWith("http"), "endpoint must start with '/' or 'http'");
86 private static Request newGetRequest(String appUrl, AccessToken token, String endPoint) {
87 return newRequestBuilder(appUrl, token, endPoint).get().build();
91 public Response post(String appUrl, AccessToken token, String endPoint) throws IOException {
92 return doPost(appUrl, token, endPoint, new FormBody.Builder().build());
96 public Response post(String appUrl, AccessToken token, String endPoint, String json) throws IOException {
97 RequestBody body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
98 return doPost(appUrl, token, endPoint, body);
102 public Response patch(String appUrl, AccessToken token, String endPoint, String json) throws IOException {
103 RequestBody body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
104 return doPatch(appUrl, token, endPoint, body);
108 public Response delete(String appUrl, AccessToken token, String endPoint) throws IOException {
109 validateEndPoint(endPoint);
111 try (okhttp3.Response response = client.newCall(newDeleteRequest(appUrl, token, endPoint)).execute()) {
112 int responseCode = response.code();
113 if (responseCode != HTTP_NO_CONTENT) {
114 String content = attemptReadContent(response);
115 LOG.warn("DELETE response did not have expected HTTP code (was {}): {}", responseCode, content);
116 return new ResponseImpl(responseCode, content);
118 return new ResponseImpl(responseCode, null);
122 private static Request newDeleteRequest(String appUrl, AccessToken token, String endPoint) {
123 return newRequestBuilder(appUrl, token, endPoint).delete().build();
126 private Response doPost(String appUrl, @Nullable AccessToken token, String endPoint, RequestBody body) throws IOException {
127 validateEndPoint(endPoint);
129 try (okhttp3.Response response = client.newCall(newPostRequest(appUrl, token, endPoint, body)).execute()) {
130 int responseCode = response.code();
131 if (responseCode == HTTP_OK || responseCode == HTTP_CREATED) {
132 return new ResponseImpl(responseCode, readContent(response.body()).orElse(null));
133 } else if (responseCode == HTTP_NO_CONTENT) {
134 return new ResponseImpl(responseCode, null);
136 String content = attemptReadContent(response);
137 LOG.warn("POST response did not have expected HTTP code (was {}): {}", responseCode, content);
138 return new ResponseImpl(responseCode, content);
142 private Response doPatch(String appUrl, AccessToken token, String endPoint, RequestBody body) throws IOException {
143 validateEndPoint(endPoint);
145 try (okhttp3.Response response = client.newCall(newPatchRequest(token, appUrl, endPoint, body)).execute()) {
146 int responseCode = response.code();
147 if (responseCode == HTTP_OK) {
148 return new ResponseImpl(responseCode, readContent(response.body()).orElse(null));
149 } else if (responseCode == HTTP_NO_CONTENT) {
150 return new ResponseImpl(responseCode, null);
152 String content = attemptReadContent(response);
153 LOG.warn("PATCH response did not have expected HTTP code (was {}): {}", responseCode, content);
154 return new ResponseImpl(responseCode, content);
158 private static Request newPostRequest(String appUrl, @Nullable AccessToken token, String endPoint, RequestBody body) {
159 return newRequestBuilder(appUrl, token, endPoint).post(body).build();
162 private static Request newPatchRequest(AccessToken token, String appUrl, String endPoint, RequestBody body) {
163 return newRequestBuilder(appUrl, token, endPoint).patch(body).build();
166 private static Request.Builder newRequestBuilder(String appUrl, @Nullable AccessToken token, String endPoint) {
167 Request.Builder url = new Request.Builder().url(toAbsoluteEndPoint(appUrl, endPoint));
169 url.addHeader("Authorization", token.getAuthorizationHeaderPrefix() + " " + token);
170 url.addHeader("Accept", String.format("%s, %s, %s", ANTIOPE_PREVIEW_JSON, MACHINE_MAN_PREVIEW_JSON, GITHUB_API_VERSION_JSON));
175 private static String toAbsoluteEndPoint(String host, String endPoint) {
176 if (endPoint.startsWith("http")) {
180 return new URL(host + endPoint).toExternalForm();
181 } catch (MalformedURLException e) {
182 throw new IllegalArgumentException(String.format("%s is not a valid url", host + endPoint));
186 private static String attemptReadContent(okhttp3.Response response) {
188 return readContent(response.body()).orElse(null);
189 } catch (IOException e) {
194 private static Optional<String> readContent(@Nullable ResponseBody body) throws IOException {
199 return of(body.string());
206 private static String readNextEndPoint(okhttp3.Response response) {
207 String links = response.headers().get("link");
208 if (links == null || links.isEmpty() || !links.contains("rel=\"next\"")) {
212 Matcher nextLinkMatcher = NEXT_LINK_PATTERN.matcher(links);
213 if (!nextLinkMatcher.find()) {
217 return nextLinkMatcher.group(1);
220 private static class ResponseImpl implements Response {
221 private final int code;
222 private final String content;
224 private ResponseImpl(int code, @Nullable String content) {
226 this.content = content;
230 public int getCode() {
235 public Optional<String> getContent() {
236 return ofNullable(content);
240 private static final class GetResponseImpl extends ResponseImpl implements GetResponse {
241 private final String nextEndPoint;
243 private GetResponseImpl(int code, @Nullable String content, @Nullable String nextEndPoint) {
244 super(code, content);
245 this.nextEndPoint = nextEndPoint;
249 public Optional<String> getNextEndPoint() {
250 return ofNullable(nextEndPoint);