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.apache.commons.lang.StringUtils;
37 import org.sonar.alm.client.TimeoutConfiguration;
38 import org.sonar.alm.client.github.security.AccessToken;
39 import org.sonar.api.utils.log.Logger;
40 import org.sonar.api.utils.log.Loggers;
41 import org.sonarqube.ws.client.OkHttpClientBuilder;
43 import static com.google.common.base.Preconditions.checkArgument;
44 import static java.net.HttpURLConnection.HTTP_ACCEPTED;
45 import static java.net.HttpURLConnection.HTTP_CREATED;
46 import static java.net.HttpURLConnection.HTTP_NO_CONTENT;
47 import static java.net.HttpURLConnection.HTTP_OK;
48 import static java.util.Optional.empty;
49 import static java.util.Optional.of;
50 import static java.util.Optional.ofNullable;
52 public class GithubApplicationHttpClientImpl implements GithubApplicationHttpClient {
54 private static final Logger LOG = Loggers.get(GithubApplicationHttpClientImpl.class);
55 private static final Pattern NEXT_LINK_PATTERN = Pattern.compile("<([^<]+)>; rel=\"next\"");
56 private static final String GITHUB_API_VERSION_JSON = "application/vnd.github.v3+json";
57 private static final String ANTIOPE_PREVIEW_JSON = "application/vnd.github.antiope-preview+json";
58 private static final String MACHINE_MAN_PREVIEW_JSON = "application/vnd.github.machine-man-preview+json";
60 private final OkHttpClient client;
62 public GithubApplicationHttpClientImpl(TimeoutConfiguration timeoutConfiguration) {
63 client = new OkHttpClientBuilder()
64 .setConnectTimeoutMs(timeoutConfiguration.getConnectTimeout())
65 .setReadTimeoutMs(timeoutConfiguration.getReadTimeout())
66 .setFollowRedirects(false)
71 public GetResponse get(String appUrl, AccessToken token, String endPoint) throws IOException {
72 return get(appUrl, token, endPoint, true);
76 public GetResponse getSilent(String appUrl, AccessToken token, String endPoint) throws IOException {
77 return get(appUrl, token, endPoint, false);
80 private GetResponse get(String appUrl, AccessToken token, String endPoint, boolean withLog) throws IOException {
81 validateEndPoint(endPoint);
83 try (okhttp3.Response response = client.newCall(newGetRequest(appUrl, token, endPoint)).execute()) {
84 int responseCode = response.code();
85 if (responseCode != HTTP_OK) {
86 String content = StringUtils.trimToNull(attemptReadContent(response));
88 LOG.warn("GET response did not have expected HTTP code (was {}): {}", responseCode, content);
90 return new GetResponseImpl(responseCode, content, null);
92 return new GetResponseImpl(responseCode, readContent(response.body()).orElse(null), readNextEndPoint(response));
97 private static void validateEndPoint(String endPoint) {
98 checkArgument(endPoint.startsWith("/") || endPoint.startsWith("http"), "endpoint must start with '/' or 'http'");
101 private static Request newGetRequest(String appUrl, AccessToken token, String endPoint) {
102 return newRequestBuilder(appUrl, token, endPoint).get().build();
106 public Response post(String appUrl, AccessToken token, String endPoint) throws IOException {
107 return doPost(appUrl, token, endPoint, new FormBody.Builder().build());
111 public Response post(String appUrl, AccessToken token, String endPoint, String json) throws IOException {
112 RequestBody body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
113 return doPost(appUrl, token, endPoint, body);
117 public Response patch(String appUrl, AccessToken token, String endPoint, String json) throws IOException {
118 RequestBody body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
119 return doPatch(appUrl, token, endPoint, body);
123 public Response delete(String appUrl, AccessToken token, String endPoint) throws IOException {
124 validateEndPoint(endPoint);
126 try (okhttp3.Response response = client.newCall(newDeleteRequest(appUrl, token, endPoint)).execute()) {
127 int responseCode = response.code();
128 if (responseCode != HTTP_NO_CONTENT) {
129 String content = attemptReadContent(response);
130 LOG.warn("DELETE response did not have expected HTTP code (was {}): {}", responseCode, content);
131 return new ResponseImpl(responseCode, content);
133 return new ResponseImpl(responseCode, null);
137 private static Request newDeleteRequest(String appUrl, AccessToken token, String endPoint) {
138 return newRequestBuilder(appUrl, token, endPoint).delete().build();
141 private Response doPost(String appUrl, @Nullable AccessToken token, String endPoint, RequestBody body) throws IOException {
142 validateEndPoint(endPoint);
144 try (okhttp3.Response response = client.newCall(newPostRequest(appUrl, token, endPoint, body)).execute()) {
145 int responseCode = response.code();
146 if (responseCode == HTTP_OK || responseCode == HTTP_CREATED || responseCode == HTTP_ACCEPTED) {
147 return new ResponseImpl(responseCode, readContent(response.body()).orElse(null));
148 } else if (responseCode == HTTP_NO_CONTENT) {
149 return new ResponseImpl(responseCode, null);
151 String content = attemptReadContent(response);
152 LOG.warn("POST response did not have expected HTTP code (was {}): {}", responseCode, content);
153 return new ResponseImpl(responseCode, content);
157 private Response doPatch(String appUrl, AccessToken token, String endPoint, RequestBody body) throws IOException {
158 validateEndPoint(endPoint);
160 try (okhttp3.Response response = client.newCall(newPatchRequest(token, appUrl, endPoint, body)).execute()) {
161 int responseCode = response.code();
162 if (responseCode == HTTP_OK) {
163 return new ResponseImpl(responseCode, readContent(response.body()).orElse(null));
164 } else if (responseCode == HTTP_NO_CONTENT) {
165 return new ResponseImpl(responseCode, null);
167 String content = attemptReadContent(response);
168 LOG.warn("PATCH response did not have expected HTTP code (was {}): {}", responseCode, content);
169 return new ResponseImpl(responseCode, content);
173 private static Request newPostRequest(String appUrl, @Nullable AccessToken token, String endPoint, RequestBody body) {
174 return newRequestBuilder(appUrl, token, endPoint).post(body).build();
177 private static Request newPatchRequest(AccessToken token, String appUrl, String endPoint, RequestBody body) {
178 return newRequestBuilder(appUrl, token, endPoint).patch(body).build();
181 private static Request.Builder newRequestBuilder(String appUrl, @Nullable AccessToken token, String endPoint) {
182 Request.Builder url = new Request.Builder().url(toAbsoluteEndPoint(appUrl, endPoint));
184 url.addHeader("Authorization", token.getAuthorizationHeaderPrefix() + " " + token);
185 url.addHeader("Accept", String.format("%s, %s, %s", ANTIOPE_PREVIEW_JSON, MACHINE_MAN_PREVIEW_JSON, GITHUB_API_VERSION_JSON));
190 private static String toAbsoluteEndPoint(String host, String endPoint) {
191 if (endPoint.startsWith("http")) {
195 return new URL(host + endPoint).toExternalForm();
196 } catch (MalformedURLException e) {
197 throw new IllegalArgumentException(String.format("%s is not a valid url", host + endPoint));
201 private static String attemptReadContent(okhttp3.Response response) {
203 return readContent(response.body()).orElse(null);
204 } catch (IOException e) {
209 private static Optional<String> readContent(@Nullable ResponseBody body) throws IOException {
214 return of(body.string());
221 private static String readNextEndPoint(okhttp3.Response response) {
222 String links = response.headers().get("link");
223 if (links == null || links.isEmpty() || !links.contains("rel=\"next\"")) {
227 Matcher nextLinkMatcher = NEXT_LINK_PATTERN.matcher(links);
228 if (!nextLinkMatcher.find()) {
232 return nextLinkMatcher.group(1);
235 private static class ResponseImpl implements Response {
236 private final int code;
237 private final String content;
239 private ResponseImpl(int code, @Nullable String content) {
241 this.content = content;
245 public int getCode() {
250 public Optional<String> getContent() {
251 return ofNullable(content);
255 private static final class GetResponseImpl extends ResponseImpl implements GetResponse {
256 private final String nextEndPoint;
258 private GetResponseImpl(int code, @Nullable String content, @Nullable String nextEndPoint) {
259 super(code, content);
260 this.nextEndPoint = nextEndPoint;
264 public Optional<String> getNextEndPoint() {
265 return ofNullable(nextEndPoint);