delete(final String path, final String data) {
- final Request request =
- requestBuilder(path)
- .method("DELETE", RequestBody.create(parse(MediaType.APPLICATION_JSON), data))
- .build();
- log.debug("Making DELETE request to {}", request.url().toString());
- return call(request);
- }
-
- /**
- * Create a URL for a given path to this Github server.
- *
- * @param path relative URI
- * @return URL to path on this server
- */
- String urlFor(final String path) {
- return baseUrl.toString().replaceAll("/+$", "") + "/" + path.replaceAll("^/+", "");
- }
-
- private Request.Builder requestBuilder(final String path) {
- final Request.Builder builder =
- new Request.Builder()
- .url(urlFor(path))
- .addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON)
- .addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
- builder.addHeader(HttpHeaders.AUTHORIZATION, getAuthorizationHeader(path));
-
- return builder;
- }
-
- private Request.Builder graphqlRequestBuilder() {
- URI url = graphqlUrl.orElseThrow(() -> new IllegalStateException("No graphql url set"));
- final Request.Builder builder =
- new Request.Builder()
- .url(url.toString())
- .addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON)
- .addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
- builder.addHeader(HttpHeaders.AUTHORIZATION, getAuthorizationHeader("/graphql"));
- return builder;
- }
-
- public boolean isGraphqlEnabled() {
- return graphqlUrl.isPresent();
- }
-
-
- /*
- Generates the Authentication header, given the API endpoint and the credentials provided.
-
- Github Requests can be authenticated in 3 different ways.
- (1) Regular, static access token;
- (2) JWT Token, generated from a private key. Used in Github Apps;
- (3) Installation Token, generated from the JWT token. Also used in Github Apps.
- */
- private String getAuthorizationHeader(final String path) {
- if (isJwtRequest(path) && getPrivateKey().isEmpty()) {
- throw new IllegalStateException("This endpoint needs a client with a private key for an App");
- }
- if (getAccessToken().isPresent()) {
- return String.format("token %s", token);
- } else if (getPrivateKey().isPresent()) {
- final String jwtToken;
- try {
- jwtToken = JwtTokenIssuer.fromPrivateKey(privateKey).getToken(appId);
- } catch (Exception e) {
- throw new RuntimeException("There was an error generating JWT token", e);
- }
- if (isJwtRequest(path)) {
- return String.format("Bearer %s", jwtToken);
- }
- if (installationId == null) {
- throw new RuntimeException("This endpoint needs a client with an installation ID");
- }
- try {
- return String.format("token %s", getInstallationToken(jwtToken, installationId));
- } catch (Exception e) {
- throw new RuntimeException("Could not generate access token for github app", e);
- }
- }
- throw new RuntimeException("Not possible to authenticate. ");
- }
-
- private boolean isJwtRequest(final String path) {
- return path.startsWith("/app/installation") || path.endsWith("installation");
- }
-
- private String getInstallationToken(final String jwtToken, final int installationId)
- throws Exception {
-
- AccessToken installationToken = installationTokens.get(installationId);
-
- if (installationToken == null || isExpired(installationToken)) {
- log.info(
- "Github token for installation {} is either expired or null. Trying to get a new one.",
- installationId);
- installationToken = generateInstallationToken(jwtToken, installationId);
- installationTokens.put(installationId, installationToken);
- }
- return installationToken.token();
- }
-
- private boolean isExpired(final AccessToken token) {
- // Adds a few minutes to avoid making calls with an expired token due to clock differences
- return token.expiresAt().isBefore(ZonedDateTime.now().plusMinutes(EXPIRY_MARGIN_IN_MINUTES));
- }
-
- private AccessToken generateInstallationToken(final String jwtToken, final int installationId)
- throws Exception {
- log.info("Got JWT Token. Now getting Github access_token for installation {}", installationId);
- final String url = String.format(urlFor(GET_ACCESS_TOKEN_URL), installationId);
- final Request request =
- new Request.Builder()
- .addHeader("Accept", "application/vnd.github.machine-man-preview+json")
- .addHeader("Authorization", "Bearer " + jwtToken)
- .url(url)
- .method("POST", RequestBody.create(parse(MediaType.APPLICATION_JSON), ""))
- .build();
-
- final Response response = client.newCall(request).execute();
-
- if (!response.isSuccessful()) {
- throw new Exception(
- String.format(
- "Got non-2xx status %s when getting an access token from GitHub: %s",
- response.code(), response.message()));
- }
-
- if (response.body() == null) {
- throw new Exception(
- String.format(
- "Got empty response body when getting an access token from GitHub, HTTP status was: %s",
- response.message()));
- }
- final String text = response.body().string();
- response.body().close();
- return Json.create().fromJson(text, AccessToken.class);
- }
-
- private CompletableFuture call(final Request request) {
- final Call call = client.newCall(request);
-
- final CompletableFuture future = new CompletableFuture<>();
-
- // avoid multiple redirects
- final AtomicBoolean redirected = new AtomicBoolean(false);
-
- call.enqueue(
- new Callback() {
- @Override
- public void onFailure(final Call call, final IOException e) {
- future.completeExceptionally(e);
- }
-
- @Override
- public void onResponse(final Call call, final Response response) {
- processPossibleRedirects(response, redirected)
- .handle(
- (res, ex) -> {
- if (Objects.nonNull(ex)) {
- future.completeExceptionally(ex);
- } else if (!res.isSuccessful()) {
- try {
- future.completeExceptionally(mapException(res, request));
- } catch (final Throwable e) {
- future.completeExceptionally(e);
- } finally {
- if (res.body() != null) {
- res.body().close();
- }
+ public GitHubClient withTracer(final Tracer tracer) {
+ this.tracer = tracer;
+ return this;
+ }
+
+ public Optional getPrivateKey() {
+ return Optional.ofNullable(privateKey);
+ }
+
+ public Optional getAccessToken() {
+ return Optional.ofNullable(token);
+ }
+
+ /**
+ * Create a repository API client
+ *
+ * @param owner repository owner
+ * @param repo repository name
+ * @return repository API client
+ */
+ public RepositoryClient createRepositoryClient(final String owner, final String repo) {
+ return RepositoryClient.create(this, owner, repo);
+ }
+
+ /**
+ * Create a GitData API client
+ *
+ * @param owner repository owner
+ * @param repo repository name
+ * @return GitData API client
+ */
+ public GitDataClient createGitDataClient(final String owner, final String repo) {
+ return GitDataClient.create(this, owner, repo);
+ }
+
+ /**
+ * Create search API client
+ *
+ * @return search API client
+ */
+ public SearchClient createSearchClient() {
+ return SearchClient.create(this);
+ }
+
+ /**
+ * Create a checks API client
+ *
+ * @param owner repository owner
+ * @param repo repository name
+ * @return checks API client
+ */
+ public ChecksClient createChecksClient(final String owner, final String repo) {
+ return ChecksClient.create(this, owner, repo);
+ }
+
+ /**
+ * Create organisation API client
+ *
+ * @return organisation API client
+ */
+ public OrganisationClient createOrganisationClient(final String org) {
+ return OrganisationClient.create(this, org);
+ }
+
+ /**
+ * Create user API client
+ *
+ * @return user API client
+ */
+ public UserClient createUserClient(final String owner) {
+ return UserClient.create(this, owner);
+ }
+
+ Json json() {
+ return json;
+ }
+
+ /**
+ * Make an http GET request for the given path on the server
+ *
+ * @param path relative to the Github base url
+ * @return response body as a String
+ */
+ CompletableFuture request(final String path) {
+ final Request request = requestBuilder(path).build();
+ log.debug("Making request to {}", request.url().toString());
+ return call(request);
+ }
+
+ /**
+ * Make an http GET request for the given path on the server
+ *
+ * @param path relative to the Github base url
+ * @param extraHeaders extra github headers to be added to the call
+ * @return a reader of response body
+ */
+ CompletableFuture request(final String path, final Map extraHeaders) {
+ final Request.Builder builder = requestBuilder(path);
+ extraHeaders.forEach(builder::addHeader);
+ final Request request = builder.build();
+ log.debug("Making request to {}", request.url().toString());
+ return call(request);
+ }
+
+ /**
+ * Make an http GET request for the given path on the server
+ *
+ * @param path relative to the Github base url
+ * @return body deserialized as provided type
+ */
+ CompletableFuture request(final String path, final Class clazz) {
+ final Request request = requestBuilder(path).build();
+ log.debug("Making request to {}", request.url().toString());
+ return call(request)
+ .thenApply(body -> json().fromJsonUncheckedNotNull(responseBodyUnchecked(body), clazz));
+ }
+
+ /**
+ * Make an http GET request for the given path on the server
+ *
+ * @param path relative to the Github base url
+ * @param extraHeaders extra github headers to be added to the call
+ * @return body deserialized as provided type
+ */
+ CompletableFuture request(
+ final String path, final Class clazz, final Map extraHeaders) {
+ final Request.Builder builder = requestBuilder(path);
+ extraHeaders.forEach(builder::addHeader);
+ final Request request = builder.build();
+ log.debug("Making request to {}", request.url().toString());
+ return call(request)
+ .thenApply(body -> json().fromJsonUncheckedNotNull(responseBodyUnchecked(body), clazz));
+ }
+
+ /**
+ * Make an http request for the given path on the Github server.
+ *
+ * @param path relative to the Github base url
+ * @param extraHeaders extra github headers to be added to the call
+ * @return body deserialized as provided type
+ */
+ CompletableFuture request(
+ final String path,
+ final TypeReference typeReference,
+ final Map extraHeaders) {
+ final Request.Builder builder = requestBuilder(path);
+ extraHeaders.forEach(builder::addHeader);
+ final Request request = builder.build();
+ log.debug("Making request to {}", request.url().toString());
+ return call(request)
+ .thenApply(
+ response ->
+ json().fromJsonUncheckedNotNull(responseBodyUnchecked(response), typeReference));
+ }
+
+ /**
+ * Make an http request for the given path on the Github server.
+ *
+ * @param path relative to the Github base url
+ * @return body deserialized as provided type
+ */
+ CompletableFuture request(final String path, final TypeReference typeReference) {
+ final Request request = requestBuilder(path).build();
+ log.debug("Making request to {}", request.url().toString());
+ return call(request)
+ .thenApply(
+ response ->
+ json().fromJsonUncheckedNotNull(responseBodyUnchecked(response), typeReference));
+ }
+
+ /**
+ * Make an http POST request for the given path with provided JSON body.
+ *
+ * @param path relative to the Github base url
+ * @param data request body as stringified JSON
+ * @return response body as String
+ */
+ CompletableFuture post(final String path, final String data) {
+ final Request request =
+ requestBuilder(path)
+ .method("POST", RequestBody.create(parse(MediaType.APPLICATION_JSON), data))
+ .build();
+ log.debug("Making POST request to {}", request.url().toString());
+ return call(request);
+ }
+
+ /**
+ * Make an http POST request for the given path with provided JSON body.
+ *
+ * @param path relative to the Github base url
+ * @param data request body as stringified JSON
+ * @param extraHeaders
+ * @return response body as String
+ */
+ CompletableFuture post(
+ final String path, final String data, final Map extraHeaders) {
+ final Request.Builder builder =
+ requestBuilder(path)
+ .method("POST", RequestBody.create(parse(MediaType.APPLICATION_JSON), data));
+ extraHeaders.forEach(builder::addHeader);
+ final Request request = builder.build();
+ log.debug("Making POST request to {}", request.url().toString());
+ return call(request);
+ }
+
+ /**
+ * Make an http POST request for the given path with provided JSON body.
+ *
+ * @param path relative to the Github base url
+ * @param data request body as stringified JSON
+ * @param clazz class to cast response as
+ * @param extraHeaders
+ * @return response body deserialized as provided class
+ */
+ CompletableFuture post(
+ final String path,
+ final String data,
+ final Class clazz,
+ final Map extraHeaders) {
+ return post(path, data, extraHeaders)
+ .thenApply(
+ response -> json().fromJsonUncheckedNotNull(responseBodyUnchecked(response), clazz));
+ }
+
+ /**
+ * Make an http POST request for the given path with provided JSON body.
+ *
+ * @param path relative to the Github base url
+ * @param data request body as stringified JSON
+ * @param clazz class to cast response as
+ * @return response body deserialized as provided class
+ */
+ CompletableFuture post(final String path, final String data, final Class clazz) {
+ return post(path, data)
+ .thenApply(
+ response -> json().fromJsonUncheckedNotNull(responseBodyUnchecked(response), clazz));
+ }
+
+ /**
+ * Make a POST request to the graphql endpoint of Github
+ *
+ * @param data request body as stringified JSON
+ * @return response
+ * @see "https://docs.github.com/en/enterprise-server@3.9/graphql/guides/forming-calls-with-graphql#communicating-with-graphql"
+ */
+ public CompletableFuture postGraphql(final String data) {
+ final Request request =
+ graphqlRequestBuilder()
+ .method("POST", RequestBody.create(parse(MediaType.APPLICATION_JSON), data))
+ .build();
+ log.info("Making POST request to {}", request.url());
+ return call(request);
+ }
+
+ /**
+ * Make an http PUT request for the given path with provided JSON body.
+ *
+ * @param path relative to the Github base url
+ * @param data request body as stringified JSON
+ * @return response body as String
+ */
+ CompletableFuture put(final String path, final String data) {
+ final Request request =
+ requestBuilder(path)
+ .method("PUT", RequestBody.create(parse(MediaType.APPLICATION_JSON), data))
+ .build();
+ log.debug("Making POST request to {}", request.url().toString());
+ return call(request);
+ }
+
+ /**
+ * Make a HTTP PUT request for the given path with provided JSON body.
+ *
+ * @param path relative to the Github base url
+ * @param data request body as stringified JSON
+ * @param clazz class to cast response as
+ * @return response body deserialized as provided class
+ */
+ CompletableFuture put(final String path, final String data, final Class clazz) {
+ return put(path, data)
+ .thenApply(
+ response -> json().fromJsonUncheckedNotNull(responseBodyUnchecked(response), clazz));
+ }
+
+ /**
+ * Make an http PATCH request for the given path with provided JSON body.
+ *
+ * @param path relative to the Github base url
+ * @param data request body as stringified JSON
+ * @return response body as String
+ */
+ CompletableFuture patch(final String path, final String data) {
+ final Request request =
+ requestBuilder(path)
+ .method("PATCH", RequestBody.create(parse(MediaType.APPLICATION_JSON), data))
+ .build();
+ log.debug("Making PATCH request to {}", request.url().toString());
+ return call(request);
+ }
+
+ /**
+ * Make an http PATCH request for the given path with provided JSON body.
+ *
+ * @param path relative to the Github base url
+ * @param data request body as stringified JSON
+ * @param clazz class to cast response as
+ * @return response body deserialized as provided class
+ */
+ CompletableFuture patch(final String path, final String data, final Class clazz) {
+ return patch(path, data)
+ .thenApply(
+ response -> json().fromJsonUncheckedNotNull(responseBodyUnchecked(response), clazz));
+ }
+
+ /**
+ * Make an http PATCH request for the given path with provided JSON body
+ *
+ * @param path relative to the Github base url
+ * @param data request body as stringified JSON
+ * @param clazz class to cast response as
+ * @return response body deserialized as provided class
+ */
+ CompletableFuture patch(
+ final String path,
+ final String data,
+ final Class clazz,
+ final Map extraHeaders) {
+ final Request.Builder builder =
+ requestBuilder(path)
+ .method("PATCH", RequestBody.create(parse(MediaType.APPLICATION_JSON), data));
+ extraHeaders.forEach(builder::addHeader);
+ final Request request = builder.build();
+ log.debug("Making PATCH request to {}", request.url().toString());
+ return call(request)
+ .thenApply(
+ response -> json().fromJsonUncheckedNotNull(responseBodyUnchecked(response), clazz));
+ }
+
+ /**
+ * Make an http DELETE request for the given path.
+ *
+ * @param path relative to the Github base url
+ * @return response body as String
+ */
+ CompletableFuture delete(final String path) {
+ final Request request = requestBuilder(path).delete().build();
+ log.debug("Making DELETE request to {}", request.url().toString());
+ return call(request);
+ }
+
+ /**
+ * Make an http DELETE request for the given path.
+ *
+ * @param path relative to the Github base url
+ * @param data request body as stringified JSON
+ * @return response body as String
+ */
+ CompletableFuture delete(final String path, final String data) {
+ final Request request =
+ requestBuilder(path)
+ .method("DELETE", RequestBody.create(parse(MediaType.APPLICATION_JSON), data))
+ .build();
+ log.debug("Making DELETE request to {}", request.url().toString());
+ return call(request);
+ }
+
+ /**
+ * Create a URL for a given path to this Github server.
+ *
+ * @param path relative URI
+ * @return URL to path on this server
+ */
+ String urlFor(final String path) {
+ return baseUrl.toString().replaceAll("/+$", "") + "/" + path.replaceAll("^/+", "");
+ }
+
+ private Request.Builder requestBuilder(final String path) {
+ final Request.Builder builder =
+ new Request.Builder()
+ .url(urlFor(path))
+ .addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON)
+ .addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
+ builder.addHeader(HttpHeaders.AUTHORIZATION, getAuthorizationHeader(path));
+
+ return builder;
+ }
+
+ private Request.Builder graphqlRequestBuilder() {
+ URI url = graphqlUrl.orElseThrow(() -> new IllegalStateException("No graphql url set"));
+ final Request.Builder builder =
+ new Request.Builder()
+ .url(url.toString())
+ .addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON)
+ .addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
+ builder.addHeader(HttpHeaders.AUTHORIZATION, getAuthorizationHeader("/graphql"));
+ return builder;
+ }
+
+ public boolean isGraphqlEnabled() {
+ return graphqlUrl.isPresent();
+ }
+
+
+ /*
+ Generates the Authentication header, given the API endpoint and the credentials provided.
+
+ Github Requests can be authenticated in 3 different ways.
+ (1) Regular, static access token;
+ (2) JWT Token, generated from a private key. Used in Github Apps;
+ (3) Installation Token, generated from the JWT token. Also used in Github Apps.
+ */
+ private String getAuthorizationHeader(final String path) {
+ if (isJwtRequest(path) && getPrivateKey().isEmpty()) {
+ throw new IllegalStateException("This endpoint needs a client with a private key for an App");
+ }
+ if (getAccessToken().isPresent()) {
+ return String.format("token %s", token);
+ } else if (getPrivateKey().isPresent()) {
+ final String jwtToken;
+ try {
+ jwtToken = JwtTokenIssuer.fromPrivateKey(privateKey).getToken(appId);
+ } catch (Exception e) {
+ throw new RuntimeException("There was an error generating JWT token", e);
+ }
+ if (isJwtRequest(path)) {
+ return String.format("Bearer %s", jwtToken);
+ }
+ if (installationId == null) {
+ throw new RuntimeException("This endpoint needs a client with an installation ID");
+ }
+ try {
+ return String.format("token %s", getInstallationToken(jwtToken, installationId));
+ } catch (Exception e) {
+ throw new RuntimeException("Could not generate access token for github app", e);
+ }
+ }
+ throw new RuntimeException("Not possible to authenticate. ");
+ }
+
+ private boolean isJwtRequest(final String path) {
+ return path.startsWith("/app/installation") || path.endsWith("installation");
+ }
+
+ private String getInstallationToken(final String jwtToken, final int installationId)
+ throws Exception {
+
+ AccessToken installationToken = installationTokens.get(installationId);
+
+ if (installationToken == null || isExpired(installationToken)) {
+ log.info(
+ "Github token for installation {} is either expired or null. Trying to get a new one.",
+ installationId);
+ installationToken = generateInstallationToken(jwtToken, installationId);
+ installationTokens.put(installationId, installationToken);
+ }
+ return installationToken.token();
+ }
+
+ private boolean isExpired(final AccessToken token) {
+ // Adds a few minutes to avoid making calls with an expired token due to clock differences
+ return token.expiresAt().isBefore(ZonedDateTime.now().plusMinutes(EXPIRY_MARGIN_IN_MINUTES));
+ }
+
+ private AccessToken generateInstallationToken(final String jwtToken, final int installationId)
+ throws Exception {
+ log.info("Got JWT Token. Now getting Github access_token for installation {}", installationId);
+ final String url = String.format(urlFor(GET_ACCESS_TOKEN_URL), installationId);
+ final Request request =
+ new Request.Builder()
+ .addHeader("Accept", "application/vnd.github.machine-man-preview+json")
+ .addHeader("Authorization", "Bearer " + jwtToken)
+ .url(url)
+ .method("POST", RequestBody.create(parse(MediaType.APPLICATION_JSON), ""))
+ .build();
+
+ final Response response = client.newCall(request).execute();
+
+ if (!response.isSuccessful()) {
+ throw new Exception(
+ String.format(
+ "Got non-2xx status %s when getting an access token from GitHub: %s",
+ response.code(), response.message()));
+ }
+
+ if (response.body() == null) {
+ throw new Exception(
+ String.format(
+ "Got empty response body when getting an access token from GitHub, HTTP status was: %s",
+ response.message()));
+ }
+ final String text = response.body().string();
+ response.body().close();
+ return Json.create().fromJson(text, AccessToken.class);
+ }
+
+ private CompletableFuture call(final Request request) {
+ try (Span span = tracer.span(request)) {
+ Request tracedRequest = span.decorateRequest(request);
+ final Call call = client.newCall(tracedRequest);
+
+ final CompletableFuture future = new CompletableFuture<>();
+
+ // avoid multiple redirects
+ final AtomicBoolean redirected = new AtomicBoolean(false);
+
+ call.enqueue(
+ new Callback() {
+ @Override
+ public void onFailure(final Call call, final IOException e) {
+ future.completeExceptionally(e);
+ }
+
+ @Override
+ public void onResponse(final Call call, final Response response) {
+ processPossibleRedirects(response, redirected)
+ .handle(
+ (res, ex) -> {
+ if (Objects.nonNull(ex)) {
+ future.completeExceptionally(ex);
+ } else if (!res.isSuccessful()) {
+ try {
+ future.completeExceptionally(mapException(res, request));
+ } catch (final Throwable e) {
+ future.completeExceptionally(e);
+ } finally {
+ if (res.body() != null) {
+ res.body().close();
+ }
+ }
+ } else {
+ future.complete(res);
+ }
+ return res;
+ });
}
- } else {
- future.complete(res);
- }
- return res;
});
- }
- });
- tracer.span(request.url().toString(), request.method(), future);
- return future;
- }
-
- private RequestNotOkException mapException(final Response res, final Request request)
- throws IOException {
- String bodyString = res.body() != null ? res.body().string() : "";
- Map> headersMap = res.headers().toMultimap();
-
- if (res.code() == FORBIDDEN) {
- if (bodyString.contains("Repository was archived so is read-only")) {
- return new ReadOnlyRepositoryException(request.method(), request.url().encodedPath(), res.code(), bodyString, headersMap);
- }
- }
-
- return new RequestNotOkException(request.method(), request.url().encodedPath(), res.code(), bodyString, headersMap);
- }
-
- CompletableFuture processPossibleRedirects(
- final Response response, final AtomicBoolean redirected) {
- if (response.code() >= PERMANENT_REDIRECT
- && response.code() <= TEMPORARY_REDIRECT
- && !redirected.get()) {
- redirected.set(true);
- // redo the same request with a new URL
- final String newLocation = response.header("Location");
- final Request request =
- requestBuilder(newLocation)
- .url(newLocation)
- .method(response.request().method(), response.request().body())
- .build();
- // Do the new call and complete the original future when the new call completes
- return call(request);
- }
-
- return completedFuture(response);
- }
-
- /**
- * Wrapper to Constructors that expose File object for the privateKey argument
- * */
- private static GitHubClient createOrThrow(final OkHttpClient httpClient, final URI baseUrl, final URI graphqlUrl, final File privateKey, final Integer appId, final Integer installationId) {
- try {
- return new GitHubClient(httpClient, baseUrl, graphqlUrl, null, FileUtils.readFileToByteArray(privateKey), appId, installationId);
- } catch (IOException e) {
- throw new RuntimeException("There was an error generating JWT token", e);
- }
- }
+ tracer.attachSpanToFuture(span, future);
+ return future;
+ }
+ }
+
+ private RequestNotOkException mapException(final Response res, final Request request)
+ throws IOException {
+ String bodyString = res.body() != null ? res.body().string() : "";
+ Map> headersMap = res.headers().toMultimap();
+
+ if (res.code() == FORBIDDEN) {
+ if (bodyString.contains("Repository was archived so is read-only")) {
+ return new ReadOnlyRepositoryException(request.method(), request.url().encodedPath(), res.code(), bodyString, headersMap);
+ }
+ }
+
+ return new RequestNotOkException(request.method(), request.url().encodedPath(), res.code(), bodyString, headersMap);
+ }
+
+ CompletableFuture processPossibleRedirects(
+ final Response response, final AtomicBoolean redirected) {
+ if (response.code() >= PERMANENT_REDIRECT
+ && response.code() <= TEMPORARY_REDIRECT
+ && !redirected.get()) {
+ redirected.set(true);
+ // redo the same request with a new URL
+ final String newLocation = response.header("Location");
+ final Request request =
+ requestBuilder(newLocation)
+ .url(newLocation)
+ .method(response.request().method(), response.request().body())
+ .build();
+ // Do the new call and complete the original future when the new call completes
+ return call(request);
+ }
+
+ return completedFuture(response);
+ }
+
+ /**
+ * Wrapper to Constructors that expose File object for the privateKey argument
+ */
+ private static GitHubClient createOrThrow(final OkHttpClient httpClient, final URI baseUrl, final URI graphqlUrl, final File privateKey, final Integer appId, final Integer installationId) {
+ try {
+ return new GitHubClient(httpClient, baseUrl, graphqlUrl, null, FileUtils.readFileToByteArray(privateKey), appId, installationId);
+ } catch (IOException e) {
+ throw new RuntimeException("There was an error generating JWT token", e);
+ }
+ }
}
diff --git a/src/main/java/com/spotify/github/v3/clients/NoopTracer.java b/src/main/java/com/spotify/github/v3/clients/NoopTracer.java
index 5b3c769e..d46baab9 100644
--- a/src/main/java/com/spotify/github/v3/clients/NoopTracer.java
+++ b/src/main/java/com/spotify/github/v3/clients/NoopTracer.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,11 +19,15 @@
*/
package com.spotify.github.v3.clients;
-import com.spotify.github.Span;
-import com.spotify.github.Tracer;
+
+import com.spotify.github.tracing.Span;
+import com.spotify.github.tracing.Tracer;
+import okhttp3.Request;
import java.util.concurrent.CompletionStage;
+import static java.util.Objects.requireNonNull;
+
public class NoopTracer implements Tracer {
public static final NoopTracer INSTANCE = new NoopTracer();
@@ -40,10 +44,17 @@ public Span failure(final Throwable t) {
}
@Override
- public void close() {}
+ public void close() {
+ }
+
+ @Override
+ public Request decorateRequest(final Request request) {
+ return request;
+ }
};
- private NoopTracer() {}
+ private NoopTracer() {
+ }
@Override
public Span span(
@@ -53,5 +64,30 @@ public Span span(
return SPAN;
}
+ @Override
+ public Span span(final String path, final String method) {
+ return SPAN;
+ }
+
+ @Override
+ public Span span(final Request request) {
+ return SPAN;
+ }
+
+ @Override
+ public void attachSpanToFuture(final Span span, final CompletionStage> future) {
+ requireNonNull(span);
+ requireNonNull(future);
+ future.whenComplete(
+ (result, t) -> {
+ if (t == null) {
+ span.success();
+ } else {
+ span.failure(t);
+ }
+ span.close();
+ });
+ }
+
}
diff --git a/src/test/java/com/spotify/github/opencensus/OpenCensusSpanTest.java b/src/test/java/com/spotify/github/tracing/opencensus/OpenCensusSpanTest.java
similarity index 93%
rename from src/test/java/com/spotify/github/opencensus/OpenCensusSpanTest.java
rename to src/test/java/com/spotify/github/tracing/opencensus/OpenCensusSpanTest.java
index c6b5d94d..0f529f37 100644
--- a/src/test/java/com/spotify/github/opencensus/OpenCensusSpanTest.java
+++ b/src/test/java/com/spotify/github/tracing/opencensus/OpenCensusSpanTest.java
@@ -18,9 +18,10 @@
* -/-/-
*/
-package com.spotify.github.opencensus;
+package com.spotify.github.tracing.opencensus;
-import com.spotify.github.Span;
+import com.spotify.github.tracing.Span;
+import com.spotify.github.tracing.opencensus.OpenCensusSpan;
import com.spotify.github.v3.exceptions.RequestNotOkException;
import io.opencensus.trace.AttributeValue;
import io.opencensus.trace.Status;
diff --git a/src/test/java/com/spotify/github/opencensus/OpenCensusTracerTest.java b/src/test/java/com/spotify/github/tracing/opencensus/OpenCensusTracerTest.java
similarity index 99%
rename from src/test/java/com/spotify/github/opencensus/OpenCensusTracerTest.java
rename to src/test/java/com/spotify/github/tracing/opencensus/OpenCensusTracerTest.java
index 27b5c52b..c5a34184 100644
--- a/src/test/java/com/spotify/github/opencensus/OpenCensusTracerTest.java
+++ b/src/test/java/com/spotify/github/tracing/opencensus/OpenCensusTracerTest.java
@@ -18,7 +18,7 @@
* -/-/-
*/
-package com.spotify.github.opencensus;
+package com.spotify.github.tracing.opencensus;
import io.grpc.Context;
diff --git a/src/test/java/com/spotify/github/opencensus/TestExportHandler.java b/src/test/java/com/spotify/github/tracing/opencensus/TestExportHandler.java
similarity index 98%
rename from src/test/java/com/spotify/github/opencensus/TestExportHandler.java
rename to src/test/java/com/spotify/github/tracing/opencensus/TestExportHandler.java
index c1519572..8d812182 100644
--- a/src/test/java/com/spotify/github/opencensus/TestExportHandler.java
+++ b/src/test/java/com/spotify/github/tracing/opencensus/TestExportHandler.java
@@ -18,7 +18,7 @@
* -/-/-
*/
-package com.spotify.github.opencensus;
+package com.spotify.github.tracing.opencensus;
import io.opencensus.trace.export.SpanData;
import io.opencensus.trace.export.SpanExporter;
diff --git a/src/test/java/com/spotify/github/v3/clients/GitHubClientTest.java b/src/test/java/com/spotify/github/v3/clients/GitHubClientTest.java
index 53541217..b6df2a99 100644
--- a/src/test/java/com/spotify/github/v3/clients/GitHubClientTest.java
+++ b/src/test/java/com/spotify/github/v3/clients/GitHubClientTest.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -33,7 +33,8 @@
import static org.mockito.Mockito.*;
import com.google.common.io.Resources;
-import com.spotify.github.Tracer;
+import com.spotify.github.tracing.Span;
+import com.spotify.github.tracing.Tracer;
import com.spotify.github.v3.checks.CheckSuiteResponseList;
import com.spotify.github.v3.checks.Installation;
import com.spotify.github.v3.exceptions.ReadOnlyRepositoryException;
@@ -41,7 +42,6 @@
import com.spotify.github.v3.repos.CommitItem;
import com.spotify.github.v3.repos.RepositoryInvitation;
-import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
@@ -50,6 +50,7 @@
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
+
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
@@ -66,225 +67,228 @@
public class GitHubClientTest {
- private GitHubClient github;
- private OkHttpClient client;
- private Tracer tracer = mock(Tracer.class);
-
- private static String getFixture(String resource) throws IOException {
- return Resources.toString(getResource(GitHubClientTest.class, resource), defaultCharset());
- }
-
- @BeforeEach
- public void setUp() {
- client = mock(OkHttpClient.class);
- github = GitHubClient.create(client, URI.create("http://bogus"), "token");
- }
-
- @Test
- public void withScopedInstallationIdShouldFailWhenMissingPrivateKey() {
- assertThrows(RuntimeException.class, () -> github.withScopeForInstallationId(1));
- }
-
- @Test
- public void testWithScopedInstallationId() throws URISyntaxException {
- GitHubClient org = GitHubClient.create(new URI("http://apa.bepa.cepa"), "some_key_content".getBytes(), null, null);
- GitHubClient scoped = org.withScopeForInstallationId(1);
- Assertions.assertTrue(scoped.getPrivateKey().isPresent());
- Assertions.assertEquals(org.getPrivateKey().get(), scoped.getPrivateKey().get());
- }
-
- @Test
- public void testSearchIssue() throws Throwable {
-
- final Call call = mock(Call.class);
- final ArgumentCaptor capture = ArgumentCaptor.forClass(Callback.class);
- doNothing().when(call).enqueue(capture.capture());
-
- final Response response =
- new okhttp3.Response.Builder()
- .code(403)
- .body(
- ResponseBody.create(
- MediaType.get("application/json"),
- "{\"message\":\"Repository "
- + "was archived so is "
- + "read-only.\","
- + "\"documentation_url"
- + "\":\"https://developer"
- + ".github.com/enterprise/2"
- + ".12/v3/repos/comments"
- + "/#update-a-commit-comment"
- + "\"}"))
- .message("foo")
- .protocol(Protocol.HTTP_1_1)
- .request(new Request.Builder().url("http://localhost/").build())
- .build();
-
- when(client.newCall(any())).thenReturn(call);
- IssueClient issueClient =
- github.withTracer(tracer).createRepositoryClient("testorg", "testrepo").createIssueClient();
-
- CompletableFuture maybeSucceeded = issueClient.editComment(1, "some comment");
- capture.getValue().onResponse(call, response);
- verify(tracer,times(1)).span(anyString(), anyString(),any());
-
- Exception exception = assertThrows(ExecutionException.class,
- maybeSucceeded::get);
- Assertions.assertEquals(ReadOnlyRepositoryException.class, exception.getCause().getClass());
- }
-
- @Test
- public void testRequestNotOkException() throws Throwable {
- final Call call = mock(Call.class);
- final ArgumentCaptor capture = ArgumentCaptor.forClass(Callback.class);
- doNothing().when(call).enqueue(capture.capture());
-
- final Response response = new okhttp3.Response.Builder()
- .code(409) // Conflict
- .headers(Headers.of("x-ratelimit-remaining", "0"))
- .body(
- ResponseBody.create(
- MediaType.get("application/json"),
- "{\n \"message\": \"Merge Conflict\"\n}"
- ))
- .message("")
- .protocol(Protocol.HTTP_1_1)
- .request(new Request.Builder().url("http://localhost/").build())
- .build();
-
- when(client.newCall(any())).thenReturn(call);
- RepositoryClient repoApi = github.createRepositoryClient("testorg", "testrepo");
-
- CompletableFuture> future = repoApi.merge("basebranch", "headbranch");
- capture.getValue().onResponse(call, response);
- try {
- future.get();
- Assertions.fail("Did not throw");
- } catch (ExecutionException e) {
- assertThat(e.getCause() instanceof RequestNotOkException, is(true));
- RequestNotOkException e1 = (RequestNotOkException) e.getCause();
- assertThat(e1.statusCode(), is(409));
- assertThat(e1.method(), is("POST"));
- assertThat(e1.path(), is("/repos/testorg/testrepo/merges"));
- assertThat(e1.headers(), hasEntry("x-ratelimit-remaining", List.of("0")));
- assertThat(e1.getMessage(), containsString("POST"));
- assertThat(e1.getMessage(), containsString("/repos/testorg/testrepo/merges"));
- assertThat(e1.getMessage(), containsString("Merge Conflict"));
- assertThat(e1.getRawMessage(), containsString("Merge Conflict"));
+ private GitHubClient github;
+ private OkHttpClient client;
+ private final Tracer tracer = mock(Tracer.class);
+ private final Span mockSpan = mock(Span.class);
+
+ private static String getFixture(String resource) throws IOException {
+ return Resources.toString(getResource(GitHubClientTest.class, resource), defaultCharset());
+ }
+
+ @BeforeEach
+ public void setUp() {
+ client = mock(OkHttpClient.class);
+ github = GitHubClient.create(client, URI.create("http://bogus"), "token");
+ when(tracer.span(any())).thenReturn(mockSpan);
+ when(mockSpan.decorateRequest(any())).thenAnswer(invocation -> invocation.getArgument(0));
+ }
+
+ @Test
+ public void withScopedInstallationIdShouldFailWhenMissingPrivateKey() {
+ assertThrows(RuntimeException.class, () -> github.withScopeForInstallationId(1));
+ }
+
+ @Test
+ public void testWithScopedInstallationId() throws URISyntaxException {
+ GitHubClient org = GitHubClient.create(new URI("http://apa.bepa.cepa"), "some_key_content".getBytes(), null, null);
+ GitHubClient scoped = org.withScopeForInstallationId(1);
+ Assertions.assertTrue(scoped.getPrivateKey().isPresent());
+ Assertions.assertEquals(org.getPrivateKey().get(), scoped.getPrivateKey().get());
+ }
+
+ @Test
+ public void testSearchIssue() throws Throwable {
+
+ final Call call = mock(Call.class);
+ final ArgumentCaptor capture = ArgumentCaptor.forClass(Callback.class);
+ doNothing().when(call).enqueue(capture.capture());
+
+ final Response response =
+ new okhttp3.Response.Builder()
+ .code(403)
+ .body(
+ ResponseBody.create(
+ MediaType.get("application/json"),
+ "{\"message\":\"Repository "
+ + "was archived so is "
+ + "read-only.\","
+ + "\"documentation_url"
+ + "\":\"https://developer"
+ + ".github.com/enterprise/2"
+ + ".12/v3/repos/comments"
+ + "/#update-a-commit-comment"
+ + "\"}"))
+ .message("foo")
+ .protocol(Protocol.HTTP_1_1)
+ .request(new Request.Builder().url("http://localhost/").build())
+ .build();
+
+ when(client.newCall(any())).thenReturn(call);
+ IssueClient issueClient =
+ github.withTracer(tracer).createRepositoryClient("testorg", "testrepo").createIssueClient();
+
+ CompletableFuture maybeSucceeded = issueClient.editComment(1, "some comment");
+ capture.getValue().onResponse(call, response);
+ verify(tracer, times(1)).span(any(Request.class));
+
+ Exception exception = assertThrows(ExecutionException.class,
+ maybeSucceeded::get);
+ Assertions.assertEquals(ReadOnlyRepositoryException.class, exception.getCause().getClass());
+ }
+
+ @Test
+ public void testRequestNotOkException() throws Throwable {
+ final Call call = mock(Call.class);
+ final ArgumentCaptor capture = ArgumentCaptor.forClass(Callback.class);
+ doNothing().when(call).enqueue(capture.capture());
+
+ final Response response = new okhttp3.Response.Builder()
+ .code(409) // Conflict
+ .headers(Headers.of("x-ratelimit-remaining", "0"))
+ .body(
+ ResponseBody.create(
+ MediaType.get("application/json"),
+ "{\n \"message\": \"Merge Conflict\"\n}"
+ ))
+ .message("")
+ .protocol(Protocol.HTTP_1_1)
+ .request(new Request.Builder().url("http://localhost/").build())
+ .build();
+
+ when(client.newCall(any())).thenReturn(call);
+ RepositoryClient repoApi = github.createRepositoryClient("testorg", "testrepo");
+
+ CompletableFuture> future = repoApi.merge("basebranch", "headbranch");
+ capture.getValue().onResponse(call, response);
+ try {
+ future.get();
+ Assertions.fail("Did not throw");
+ } catch (ExecutionException e) {
+ assertThat(e.getCause() instanceof RequestNotOkException, is(true));
+ RequestNotOkException e1 = (RequestNotOkException) e.getCause();
+ assertThat(e1.statusCode(), is(409));
+ assertThat(e1.method(), is("POST"));
+ assertThat(e1.path(), is("/repos/testorg/testrepo/merges"));
+ assertThat(e1.headers(), hasEntry("x-ratelimit-remaining", List.of("0")));
+ assertThat(e1.getMessage(), containsString("POST"));
+ assertThat(e1.getMessage(), containsString("/repos/testorg/testrepo/merges"));
+ assertThat(e1.getMessage(), containsString("Merge Conflict"));
+ assertThat(e1.getRawMessage(), containsString("Merge Conflict"));
+ }
+ }
+
+ @Test
+ public void testPutConvertsToClass() throws Throwable {
+ final Call call = mock(Call.class);
+ final ArgumentCaptor callbackCapture = ArgumentCaptor.forClass(Callback.class);
+ doNothing().when(call).enqueue(callbackCapture.capture());
+
+ final ArgumentCaptor requestCapture = ArgumentCaptor.forClass(Request.class);
+ when(client.newCall(requestCapture.capture())).thenReturn(call);
+
+ final Response response =
+ new okhttp3.Response.Builder()
+ .code(200)
+ .body(
+ ResponseBody.create(
+ MediaType.get("application/json"), getFixture("repository_invitation.json")))
+ .message("")
+ .protocol(Protocol.HTTP_1_1)
+ .request(new Request.Builder().url("http://localhost/").build())
+ .build();
+
+ CompletableFuture future = github.put("collaborators/", "",
+ RepositoryInvitation.class);
+ callbackCapture.getValue().onResponse(call, response);
+
+ RepositoryInvitation invitation = future.get();
+ assertThat(requestCapture.getValue().method(), is("PUT"));
+ assertThat(requestCapture.getValue().url().toString(), is("http://bogus/collaborators/"));
+ assertThat(invitation.id(), is(1));
+ }
+
+ @Test
+ public void testGetCheckSuites() throws Throwable {
+
+ final Call call = mock(Call.class);
+ final ArgumentCaptor callbackCapture = ArgumentCaptor.forClass(Callback.class);
+ doNothing().when(call).enqueue(callbackCapture.capture());
+
+ final Response response = new okhttp3.Response.Builder()
+ .code(200)
+ .body(
+ ResponseBody.create(
+ MediaType.get("application/json"), getFixture("../checks/check-suites-response.json")))
+ .message("")
+ .protocol(Protocol.HTTP_1_1)
+ .request(new Request.Builder().url("http://localhost/").build())
+ .build();
+
+ when(client.newCall(any())).thenReturn(call);
+ ChecksClient client = github.createChecksClient("testorg", "testrepo");
+
+ CompletableFuture future = client.getCheckSuites("sha");
+ callbackCapture.getValue().onResponse(call, response);
+ var result = future.get();
+
+ assertThat(result.totalCount(), is(1));
+ assertThat(result.checkSuites().get(0).app().get().slug().get(), is("octoapp"));
+
+ }
+
+ @Test
+ void asAppScopedClientGetsUserClientIfOrgClientNotFound() {
+ var appGithub = GitHubClient.create(client, URI.create("http://bogus"), new byte[]{}, 1);
+ var githubSpy = spy(appGithub);
+
+ var orgClientMock = mock(OrganisationClient.class);
+ when(githubSpy.createOrganisationClient("owner")).thenReturn(orgClientMock);
+
+ var appClientMock = mock(GithubAppClient.class);
+ when(orgClientMock.createGithubAppClient()).thenReturn(appClientMock);
+ when(appClientMock.getInstallation()).thenReturn(failedFuture(new RequestNotOkException("", "", 404, "", new HashMap<>())));
+
+ var userClientMock = mock(UserClient.class);
+ when(githubSpy.createUserClient("owner")).thenReturn(userClientMock);
+
+ var appClientMock2 = mock(GithubAppClient.class);
+ when(userClientMock.createGithubAppClient()).thenReturn(appClientMock2);
+
+ var installationMock = mock(Installation.class);
+ when(appClientMock2.getUserInstallation()).thenReturn(completedFuture(installationMock));
+ when(installationMock.id()).thenReturn(1);
+
+ var maybeScopedClient = githubSpy.asAppScopedClient("owner").toCompletableFuture().join();
+
+ Assertions.assertTrue(maybeScopedClient.isPresent());
+ verify(githubSpy, times(1)).createOrganisationClient("owner");
+ verify(githubSpy, times(1)).createUserClient("owner");
+ }
+
+ @Test
+ void asAppScopedClientReturnsEmptyIfNoInstallation() {
+ var appGithub = GitHubClient.create(client, URI.create("http://bogus"), new byte[]{}, 1);
+ var githubSpy = spy(appGithub);
+
+ var orgClientMock = mock(OrganisationClient.class);
+ when(githubSpy.createOrganisationClient("owner")).thenReturn(orgClientMock);
+
+ var appClientMock = mock(GithubAppClient.class);
+ when(orgClientMock.createGithubAppClient()).thenReturn(appClientMock);
+ when(appClientMock.getInstallation()).thenReturn(failedFuture(new RequestNotOkException("", "", 404, "", new HashMap<>())));
+
+ var userClientMock = mock(UserClient.class);
+ when(githubSpy.createUserClient("owner")).thenReturn(userClientMock);
+
+ var appClientMock2 = mock(GithubAppClient.class);
+ when(userClientMock.createGithubAppClient()).thenReturn(appClientMock2);
+
+ var installationMock = mock(Installation.class);
+ when(appClientMock2.getUserInstallation()).thenReturn(failedFuture(new RequestNotOkException("", "", 404, "", new HashMap<>())));
+ when(installationMock.id()).thenReturn(1);
+
+ var maybeScopedClient = githubSpy.asAppScopedClient("owner").toCompletableFuture().join();
+ Assertions.assertTrue(maybeScopedClient.isEmpty());
}
- }
-
- @Test
- public void testPutConvertsToClass() throws Throwable {
- final Call call = mock(Call.class);
- final ArgumentCaptor callbackCapture = ArgumentCaptor.forClass(Callback.class);
- doNothing().when(call).enqueue(callbackCapture.capture());
-
- final ArgumentCaptor requestCapture = ArgumentCaptor.forClass(Request.class);
- when(client.newCall(requestCapture.capture())).thenReturn(call);
-
- final Response response =
- new okhttp3.Response.Builder()
- .code(200)
- .body(
- ResponseBody.create(
- MediaType.get("application/json"), getFixture("repository_invitation.json")))
- .message("")
- .protocol(Protocol.HTTP_1_1)
- .request(new Request.Builder().url("http://localhost/").build())
- .build();
-
- CompletableFuture future = github.put("collaborators/", "",
- RepositoryInvitation.class);
- callbackCapture.getValue().onResponse(call, response);
-
- RepositoryInvitation invitation = future.get();
- assertThat(requestCapture.getValue().method(), is("PUT"));
- assertThat(requestCapture.getValue().url().toString(), is("http://bogus/collaborators/"));
- assertThat(invitation.id(), is(1));
- }
-
- @Test
- public void testGetCheckSuites() throws Throwable {
-
- final Call call = mock(Call.class);
- final ArgumentCaptor callbackCapture = ArgumentCaptor.forClass(Callback.class);
- doNothing().when(call).enqueue(callbackCapture.capture());
-
- final Response response = new okhttp3.Response.Builder()
- .code(200)
- .body(
- ResponseBody.create(
- MediaType.get("application/json"), getFixture("../checks/check-suites-response.json")))
- .message("")
- .protocol(Protocol.HTTP_1_1)
- .request(new Request.Builder().url("http://localhost/").build())
- .build();
-
- when(client.newCall(any())).thenReturn(call);
- ChecksClient client = github.createChecksClient("testorg", "testrepo");
-
- CompletableFuture future = client.getCheckSuites("sha");
- callbackCapture.getValue().onResponse(call, response);
- var result = future.get();
-
- assertThat(result.totalCount(), is(1));
- assertThat(result.checkSuites().get(0).app().get().slug().get(), is("octoapp"));
-
- }
-
- @Test
- void asAppScopedClientGetsUserClientIfOrgClientNotFound() {
- var appGithub = GitHubClient.create(client, URI.create("http://bogus"), new byte[] {}, 1);
- var githubSpy = spy(appGithub);
-
- var orgClientMock = mock(OrganisationClient.class);
- when(githubSpy.createOrganisationClient("owner")).thenReturn(orgClientMock);
-
- var appClientMock = mock(GithubAppClient.class);
- when(orgClientMock.createGithubAppClient()).thenReturn(appClientMock);
- when(appClientMock.getInstallation()).thenReturn(failedFuture(new RequestNotOkException("", "", 404, "", new HashMap<>())));
-
- var userClientMock = mock(UserClient.class);
- when(githubSpy.createUserClient("owner")).thenReturn(userClientMock);
-
- var appClientMock2 = mock(GithubAppClient.class);
- when(userClientMock.createGithubAppClient()).thenReturn(appClientMock2);
-
- var installationMock = mock(Installation.class);
- when(appClientMock2.getUserInstallation()).thenReturn(completedFuture(installationMock));
- when(installationMock.id()).thenReturn(1);
-
- var maybeScopedClient = githubSpy.asAppScopedClient("owner").toCompletableFuture().join();
-
- Assertions.assertTrue(maybeScopedClient.isPresent());
- verify(githubSpy, times(1)).createOrganisationClient("owner");
- verify(githubSpy, times(1)).createUserClient("owner");
- }
-
- @Test
- void asAppScopedClientReturnsEmptyIfNoInstallation() {
- var appGithub = GitHubClient.create(client, URI.create("http://bogus"), new byte[] {}, 1);
- var githubSpy = spy(appGithub);
-
- var orgClientMock = mock(OrganisationClient.class);
- when(githubSpy.createOrganisationClient("owner")).thenReturn(orgClientMock);
-
- var appClientMock = mock(GithubAppClient.class);
- when(orgClientMock.createGithubAppClient()).thenReturn(appClientMock);
- when(appClientMock.getInstallation()).thenReturn(failedFuture(new RequestNotOkException("", "", 404, "", new HashMap<>())));
-
- var userClientMock = mock(UserClient.class);
- when(githubSpy.createUserClient("owner")).thenReturn(userClientMock);
-
- var appClientMock2 = mock(GithubAppClient.class);
- when(userClientMock.createGithubAppClient()).thenReturn(appClientMock2);
-
- var installationMock = mock(Installation.class);
- when(appClientMock2.getUserInstallation()).thenReturn(failedFuture(new RequestNotOkException("", "", 404, "", new HashMap<>())));
- when(installationMock.id()).thenReturn(1);
-
- var maybeScopedClient = githubSpy.asAppScopedClient("owner").toCompletableFuture().join();
- Assertions.assertTrue(maybeScopedClient.isEmpty());
- }
}