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_ACCEPTED;
44 import static java.net.HttpURLConnection.HTTP_CREATED;
45 import static java.net.HttpURLConnection.HTTP_NO_CONTENT;
46 import static java.net.HttpURLConnection.HTTP_OK;
47 import static java.util.Optional.empty;
48 import static java.util.Optional.of;
49 import static java.util.Optional.ofNullable;
51 public class GithubApplicationHttpClientImpl implements GithubApplicationHttpClient {
53 private static final Logger LOG = Loggers.get(GithubApplicationHttpClientImpl.class);
54 private static final Pattern NEXT_LINK_PATTERN = Pattern.compile("<([^<]+)>; rel=\"next\"");
55 private static final String GITHUB_API_VERSION_JSON = "application/vnd.github.v3+json";
56 private static final String ANTIOPE_PREVIEW_JSON = "application/vnd.github.antiope-preview+json";
57 private static final String MACHINE_MAN_PREVIEW_JSON = "application/vnd.github.machine-man-preview+json";
59 private final OkHttpClient client;
61 public GithubApplicationHttpClientImpl(TimeoutConfiguration timeoutConfiguration) {
62 client = new OkHttpClientBuilder()
63 .setConnectTimeoutMs(timeoutConfiguration.getConnectTimeout())
64 .setReadTimeoutMs(timeoutConfiguration.getReadTimeout())
65 .setFollowRedirects(false)
70 public GetResponse get(String appUrl, AccessToken token, String endPoint) throws IOException {
71 return get(appUrl, token, endPoint, true);
75 public GetResponse getSilent(String appUrl, AccessToken token, String endPoint) throws IOException {
76 return get(appUrl, token, endPoint, false);
79 private GetResponse get(String appUrl, AccessToken token, String endPoint, boolean withLog) throws IOException {
80 validateEndPoint(endPoint);
82 try (okhttp3.Response response = client.newCall(newGetRequest(appUrl, token, endPoint)).execute()) {
83 int responseCode = response.code();
84 if (responseCode != HTTP_OK) {
86 LOG.warn("GET response did not have expected HTTP code (was {}): {}", responseCode, attemptReadContent(response));
88 return new GetResponseImpl(responseCode, null, null);
90 return new GetResponseImpl(responseCode, readContent(response.body()).orElse(null), readNextEndPoint(response));
95 private static void validateEndPoint(String endPoint) {
96 checkArgument(endPoint.startsWith("/") || endPoint.startsWith("http"), "endpoint must start with '/' or 'http'");
99 private static Request newGetRequest(String appUrl, AccessToken token, String endPoint) {
100 return newRequestBuilder(appUrl, token, endPoint).get().build();
104 public Response post(String appUrl, AccessToken token, String endPoint) throws IOException {
105 return doPost(appUrl, token, endPoint, new FormBody.Builder().build());
109 public Response post(String appUrl, AccessToken token, String endPoint, String json) throws IOException {
110 RequestBody body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
111 return doPost(appUrl, token, endPoint, body);
115 public Response patch(String appUrl, AccessToken token, String endPoint, String json) throws IOException {
116 RequestBody body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
117 return doPatch(appUrl, token, endPoint, body);
121 public Response delete(String appUrl, AccessToken token, String endPoint) throws IOException {
122 validateEndPoint(endPoint);
124 try (okhttp3.Response response = client.newCall(newDeleteRequest(appUrl, token, endPoint)).execute()) {
125 int responseCode = response.code();
126 if (responseCode != HTTP_NO_CONTENT) {
127 String content = attemptReadContent(response);
128 LOG.warn("DELETE response did not have expected HTTP code (was {}): {}", responseCode, content);
129 return new ResponseImpl(responseCode, content);
131 return new ResponseImpl(responseCode, null);
135 private static Request newDeleteRequest(String appUrl, AccessToken token, String endPoint) {
136 return newRequestBuilder(appUrl, token, endPoint).delete().build();
139 private Response doPost(String appUrl, @Nullable AccessToken token, String endPoint, RequestBody body) throws IOException {
140 validateEndPoint(endPoint);
142 try (okhttp3.Response response = client.newCall(newPostRequest(appUrl, token, endPoint, body)).execute()) {
143 int responseCode = response.code();
144 if (responseCode == HTTP_OK || responseCode == HTTP_CREATED || responseCode == HTTP_ACCEPTED) {
145 return new ResponseImpl(responseCode, readContent(response.body()).orElse(null));
146 } else if (responseCode == HTTP_NO_CONTENT) {
147 return new ResponseImpl(responseCode, null);
149 String content = attemptReadContent(response);
150 LOG.warn("POST response did not have expected HTTP code (was {}): {}", responseCode, content);
151 return new ResponseImpl(responseCode, content);
155 private Response doPatch(String appUrl, AccessToken token, String endPoint, RequestBody body) throws IOException {
156 validateEndPoint(endPoint);
158 try (okhttp3.Response response = client.newCall(newPatchRequest(token, appUrl, endPoint, body)).execute()) {
159 int responseCode = response.code();
160 if (responseCode == HTTP_OK) {
161 return new ResponseImpl(responseCode, readContent(response.body()).orElse(null));
162 } else if (responseCode == HTTP_NO_CONTENT) {
163 return new ResponseImpl(responseCode, null);
165 String content = attemptReadContent(response);
166 LOG.warn("PATCH response did not have expected HTTP code (was {}): {}", responseCode, content);
167 return new ResponseImpl(responseCode, content);
171 private static Request newPostRequest(String appUrl, @Nullable AccessToken token, String endPoint, RequestBody body) {
172 return newRequestBuilder(appUrl, token, endPoint).post(body).build();
175 private static Request newPatchRequest(AccessToken token, String appUrl, String endPoint, RequestBody body) {
176 return newRequestBuilder(appUrl, token, endPoint).patch(body).build();
179 private static Request.Builder newRequestBuilder(String appUrl, @Nullable AccessToken token, String endPoint) {
180 Request.Builder url = new Request.Builder().url(toAbsoluteEndPoint(appUrl, endPoint));
182 url.addHeader("Authorization", token.getAuthorizationHeaderPrefix() + " " + token);
183 url.addHeader("Accept", String.format("%s, %s, %s", ANTIOPE_PREVIEW_JSON, MACHINE_MAN_PREVIEW_JSON, GITHUB_API_VERSION_JSON));
188 private static String toAbsoluteEndPoint(String host, String endPoint) {
189 if (endPoint.startsWith("http")) {
193 return new URL(host + endPoint).toExternalForm();
194 } catch (MalformedURLException e) {
195 throw new IllegalArgumentException(String.format("%s is not a valid url", host + endPoint));
199 private static String attemptReadContent(okhttp3.Response response) {
201 return readContent(response.body()).orElse(null);
202 } catch (IOException e) {
207 private static Optional<String> readContent(@Nullable ResponseBody body) throws IOException {
212 return of(body.string());
219 private static String readNextEndPoint(okhttp3.Response response) {
220 String links = response.headers().get("link");
221 if (links == null || links.isEmpty() || !links.contains("rel=\"next\"")) {
225 Matcher nextLinkMatcher = NEXT_LINK_PATTERN.matcher(links);
226 if (!nextLinkMatcher.find()) {
230 return nextLinkMatcher.group(1);
233 private static class ResponseImpl implements Response {
234 private final int code;
235 private final String content;
237 private ResponseImpl(int code, @Nullable String content) {
239 this.content = content;
243 public int getCode() {
248 public Optional<String> getContent() {
249 return ofNullable(content);
253 private static final class GetResponseImpl extends ResponseImpl implements GetResponse {
254 private final String nextEndPoint;
256 private GetResponseImpl(int code, @Nullable String content, @Nullable String nextEndPoint) {
257 super(code, content);
258 this.nextEndPoint = nextEndPoint;
262 public Optional<String> getNextEndPoint() {
263 return ofNullable(nextEndPoint);