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.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 MACHINE_MAN_PREVIEW_JSON = "application/vnd.github.machine-man-preview+json";
55 private static final String ANTIOPE_PREVIEW_JSON = "application/vnd.github.antiope-preview+json";
57 private final OkHttpClient client;
59 public GithubApplicationHttpClientImpl(TimeoutConfiguration timeoutConfiguration) {
60 client = new OkHttpClientBuilder()
61 .setConnectTimeoutMs(timeoutConfiguration.getConnectTimeout())
62 .setReadTimeoutMs(timeoutConfiguration.getReadTimeout())
67 public GetResponse get(String appUrl, AccessToken token, String endPoint) throws IOException {
68 validateEndPoint(endPoint);
70 try (okhttp3.Response response = client.newCall(newGetRequest(appUrl, token, endPoint)).execute()) {
71 int responseCode = response.code();
72 if (responseCode != HTTP_OK) {
73 LOG.warn("GET response did not have expected HTTP code (was {}): {}", responseCode, attemptReadContent(response));
74 return new GetResponseImpl(responseCode, null, null);
76 return new GetResponseImpl(responseCode, readContent(response.body()).orElse(null), readNextEndPoint(response));
80 private static void validateEndPoint(String endPoint) {
81 checkArgument(endPoint.startsWith("/") || endPoint.startsWith("http"), "endpoint must start with '/' or 'http'");
84 private static Request newGetRequest(String appUrl, AccessToken token, String endPoint) {
85 return newRequestBuilder(appUrl, token, endPoint).get().build();
89 public Response post(String appUrl, AccessToken token, String endPoint) throws IOException {
90 return doPost(appUrl, token, endPoint, new FormBody.Builder().build());
94 public Response post(String appUrl, AccessToken token, String endPoint, String json) throws IOException {
95 RequestBody body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
96 return doPost(appUrl, token, endPoint, body);
100 public Response patch(String appUrl, AccessToken token, String endPoint, String json) throws IOException {
101 RequestBody body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
102 return doPatch(appUrl, token, endPoint, body);
106 public Response delete(String appUrl, AccessToken token, String endPoint) throws IOException {
107 validateEndPoint(endPoint);
109 try (okhttp3.Response response = client.newCall(newDeleteRequest(appUrl, token, endPoint)).execute()) {
110 int responseCode = response.code();
111 if (responseCode != HTTP_NO_CONTENT) {
112 String content = attemptReadContent(response);
113 LOG.warn("DELETE response did not have expected HTTP code (was {}): {}", responseCode, content);
114 return new ResponseImpl(responseCode, content);
116 return new ResponseImpl(responseCode, null);
120 private static Request newDeleteRequest(String appUrl, AccessToken token, String endPoint) {
121 return newRequestBuilder(appUrl, token, endPoint).delete().build();
124 private Response doPost(String appUrl, @Nullable AccessToken token, String endPoint, RequestBody body) throws IOException {
125 validateEndPoint(endPoint);
127 try (okhttp3.Response response = client.newCall(newPostRequest(appUrl, token, endPoint, body)).execute()) {
128 int responseCode = response.code();
129 if (responseCode == HTTP_OK || responseCode == HTTP_CREATED) {
130 return new ResponseImpl(responseCode, readContent(response.body()).orElse(null));
131 } else if (responseCode == HTTP_NO_CONTENT) {
132 return new ResponseImpl(responseCode, null);
134 String content = attemptReadContent(response);
135 LOG.warn("POST response did not have expected HTTP code (was {}): {}", responseCode, content);
136 return new ResponseImpl(responseCode, content);
140 private Response doPatch(String appUrl, AccessToken token, String endPoint, RequestBody body) throws IOException {
141 validateEndPoint(endPoint);
143 try (okhttp3.Response response = client.newCall(newPatchRequest(token, appUrl, endPoint, body)).execute()) {
144 int responseCode = response.code();
145 if (responseCode == HTTP_OK) {
146 return new ResponseImpl(responseCode, readContent(response.body()).orElse(null));
147 } else if (responseCode == HTTP_NO_CONTENT) {
148 return new ResponseImpl(responseCode, null);
150 String content = attemptReadContent(response);
151 LOG.warn("PATCH response did not have expected HTTP code (was {}): {}", responseCode, content);
152 return new ResponseImpl(responseCode, content);
156 private static Request newPostRequest(String appUrl, @Nullable AccessToken token, String endPoint, RequestBody body) {
157 return newRequestBuilder(appUrl, token, endPoint).post(body).build();
160 private static Request newPatchRequest(AccessToken token, String appUrl, String endPoint, RequestBody body) {
161 return newRequestBuilder(appUrl, token, endPoint).patch(body).build();
164 private static Request.Builder newRequestBuilder(String appUrl, @Nullable AccessToken token, String endPoint) {
165 Request.Builder url = new Request.Builder()
166 .url(toAbsoluteEndPoint(appUrl, endPoint));
169 .addHeader("Authorization", token.getAuthorizationHeaderPrefix() + " " + token)
170 // TODO: Remove when CheckAPI is no longer in beta
171 .addHeader("Accept", ANTIOPE_PREVIEW_JSON + ", " + MACHINE_MAN_PREVIEW_JSON);
176 private static String toAbsoluteEndPoint(String host, String endPoint) {
177 if (endPoint.startsWith("http")) {
181 return new URL(host + endPoint).toExternalForm();
182 } catch (MalformedURLException e) {
183 throw new IllegalArgumentException(String.format("%s is not a valid url", host + endPoint));
187 private static String attemptReadContent(okhttp3.Response response) {
189 return readContent(response.body()).orElse(null);
190 } catch (IOException e) {
195 private static Optional<String> readContent(@Nullable ResponseBody body) throws IOException {
200 return of(body.string());
207 private static String readNextEndPoint(okhttp3.Response response) {
208 String links = response.header("link");
209 if (links == null || links.isEmpty() || !links.contains("rel=\"next\"")) {
213 Matcher nextLinkMatcher = NEXT_LINK_PATTERN.matcher(links);
214 if (!nextLinkMatcher.find()) {
218 return nextLinkMatcher.group(1);
221 private static class ResponseImpl implements Response {
222 private final int code;
223 private final String content;
225 private ResponseImpl(int code, @Nullable String content) {
227 this.content = content;
231 public int getCode() {
236 public Optional<String> getContent() {
237 return ofNullable(content);
241 private static final class GetResponseImpl extends ResponseImpl implements GetResponse {
242 private final String nextEndPoint;
244 private GetResponseImpl(int code, @Nullable String content, @Nullable String nextEndPoint) {
245 super(code, content);
246 this.nextEndPoint = nextEndPoint;
250 public Optional<String> getNextEndPoint() {
251 return ofNullable(nextEndPoint);