forked from spotify/github-java-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGitHubClient.java
More file actions
1264 lines (1162 loc) · 43 KB
/
GitHubClient.java
File metadata and controls
1264 lines (1162 loc) · 43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-
* -\-\-
* github-api
* --
* Copyright (C) 2016 - 2020 Spotify AB
* --
* 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.
* See the License for the specific language governing permissions and
* limitations under the License.
* -/-/-
*/
package com.spotify.github.v3.clients;
import static java.util.concurrent.CompletableFuture.completedFuture;
import com.fasterxml.jackson.core.type.TypeReference;
import com.spotify.github.async.Async;
import com.spotify.github.http.HttpClient;
import com.spotify.github.http.HttpRequest;
import com.spotify.github.http.HttpResponse;
import com.spotify.github.http.ImmutableHttpRequest;
import com.spotify.github.http.okhttp.OkHttpHttpClient;
import com.spotify.github.jackson.Json;
import com.spotify.github.tracing.NoopTracer;
import com.spotify.github.tracing.Tracer;
import com.spotify.github.v3.Team;
import com.spotify.github.v3.User;
import com.spotify.github.v3.checks.AccessToken;
import com.spotify.github.v3.checks.Installation;
import com.spotify.github.v3.comment.Comment;
import com.spotify.github.v3.comment.CommentReaction;
import com.spotify.github.v3.exceptions.ReadOnlyRepositoryException;
import com.spotify.github.v3.exceptions.RequestNotOkException;
import com.spotify.github.v3.git.FileItem;
import com.spotify.github.v3.git.Reference;
import com.spotify.github.v3.orgs.TeamInvitation;
import com.spotify.github.v3.prs.PullRequestItem;
import com.spotify.github.v3.prs.Review;
import com.spotify.github.v3.prs.ReviewRequests;
import com.spotify.github.v3.repos.*;
import java.io.File;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.net.URI;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import okhttp3.*;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* GitHub client is a main communication entry point. Provides lower level communication
* functionality as well as acts as a factory for the higher level API clients.
*/
public class GitHubClient {
private static final int EXPIRY_MARGIN_IN_MINUTES = 5;
private static final int HTTP_NOT_FOUND = 404;
private Tracer tracer = NoopTracer.INSTANCE;
static final Consumer<HttpResponse> IGNORE_RESPONSE_CONSUMER =
(response) -> {
if (response != null) {
response.close();
}
};
static final TypeReference<List<Comment>> LIST_COMMENT_TYPE_REFERENCE = new TypeReference<>() {};
static final TypeReference<List<CommentReaction>> LIST_COMMENT_REACTION_TYPE_REFERENCE =
new TypeReference<>() {};
static final TypeReference<List<Repository>> LIST_REPOSITORY = new TypeReference<>() {};
static final TypeReference<List<CommitItem>> LIST_COMMIT_TYPE_REFERENCE =
new TypeReference<>() {};
static final TypeReference<List<Review>> LIST_REVIEW_TYPE_REFERENCE = new TypeReference<>() {};
static final TypeReference<ReviewRequests> LIST_REVIEW_REQUEST_TYPE_REFERENCE =
new TypeReference<>() {};
static final TypeReference<List<Status>> LIST_STATUS_TYPE_REFERENCE = new TypeReference<>() {};
static final TypeReference<List<FolderContent>> LIST_FOLDERCONTENT_TYPE_REFERENCE =
new TypeReference<>() {};
static final TypeReference<List<PullRequestItem>> LIST_PR_TYPE_REFERENCE =
new TypeReference<>() {};
static final TypeReference<List<com.spotify.github.v3.prs.Comment>>
LIST_PR_COMMENT_TYPE_REFERENCE = new TypeReference<>() {};
static final TypeReference<List<Branch>> LIST_BRANCHES = new TypeReference<>() {};
static final TypeReference<List<Reference>> LIST_REFERENCES = new TypeReference<>() {};
static final TypeReference<List<RepositoryInvitation>> LIST_REPOSITORY_INVITATION =
new TypeReference<>() {};
static final TypeReference<List<Team>> LIST_TEAMS = new TypeReference<>() {};
static final TypeReference<List<User>> LIST_TEAM_MEMBERS = new TypeReference<>() {};
static final TypeReference<List<TeamInvitation>> LIST_PENDING_TEAM_INVITATIONS =
new TypeReference<>() {};
static final TypeReference<List<FileItem>> LIST_FILE_ITEMS = new TypeReference<>() {};
private static final String GET_ACCESS_TOKEN_URL = "app/installations/%s/access_tokens";
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private static final int PERMANENT_REDIRECT = 301;
private static final int TEMPORARY_REDIRECT = 307;
private static final int FORBIDDEN = 403;
private final URI baseUrl;
private final Optional<URI> graphqlUrl;
private final Json json = Json.create();
private final HttpClient client;
private Call.Factory callFactory;
private final String token;
private final byte[] privateKey;
private final Integer appId;
private final Integer installationId;
private final Map<Integer, AccessToken> installationTokens;
private GitHubClient(
final HttpClient client,
final URI baseUrl,
final URI graphqlUrl,
final String accessToken,
final byte[] privateKey,
final Integer appId,
final Integer installationId) {
this.baseUrl = baseUrl;
this.graphqlUrl = Optional.ofNullable(graphqlUrl);
this.token = accessToken;
this.client = client;
this.privateKey = privateKey;
this.appId = appId;
this.installationId = installationId;
this.installationTokens = new ConcurrentHashMap<>();
}
private GitHubClient(
final OkHttpClient client,
final URI baseUrl,
final URI graphqlUrl,
final String accessToken,
final byte[] privateKey,
final Integer appId,
final Integer installationId) {
this.baseUrl = baseUrl;
this.graphqlUrl = Optional.ofNullable(graphqlUrl);
this.token = accessToken;
this.client = new OkHttpHttpClient(client);
this.privateKey = privateKey;
this.appId = appId;
this.installationId = installationId;
this.installationTokens = new ConcurrentHashMap<>();
}
/**
* Create a github api client with a given base URL and authorization token.
*
* @param baseUrl base URL
* @param token authorization token
* @return github api client
*/
public static GitHubClient create(final URI baseUrl, final String token) {
return new GitHubClient(new OkHttpClient(), baseUrl, null, token, null, null, null);
}
public static GitHubClient create(final URI baseUrl, final URI graphqlUri, final String token) {
return new GitHubClient(new OkHttpClient(), baseUrl, graphqlUri, token, null, null, null);
}
/**
* Create a github api client with a given base URL and a path to a key.
*
* @param baseUrl base URL
* @param privateKey the private key PEM file
* @param appId the github app ID
* @return github api client
*/
public static GitHubClient create(final URI baseUrl, final File privateKey, final Integer appId) {
return createOrThrow(new OkHttpClient(), baseUrl, null, privateKey, appId, null);
}
/**
* Create a github api client with a given base URL and a path to a key.
*
* @param baseUrl base URL
* @param privateKey the private key as byte array
* @param appId the github app ID
* @return github api client
*/
public static GitHubClient create(
final URI baseUrl, final byte[] privateKey, final Integer appId) {
return new GitHubClient(new OkHttpClient(), baseUrl, null, null, privateKey, appId, null);
}
/**
* Create a github api client with a given base URL and a path to a key.
*
* @param baseUrl base URL
* @param privateKey the private key PEM file
* @param appId the github app ID
* @param installationId the installationID to be authenticated as
* @return github api client
*/
public static GitHubClient create(
final URI baseUrl, final File privateKey, final Integer appId, final Integer installationId) {
return createOrThrow(new OkHttpClient(), baseUrl, null, privateKey, appId, installationId);
}
/**
* Create a github api client with a given base URL and a path to a key.
*
* @param baseUrl base URL
* @param privateKey the private key as byte array
* @param appId the github app ID
* @param installationId the installationID to be authenticated as
* @return github api client
*/
public static GitHubClient create(
final URI baseUrl,
final byte[] privateKey,
final Integer appId,
final Integer installationId) {
return new GitHubClient(
new OkHttpClient(), baseUrl, null, null, privateKey, appId, installationId);
}
/**
* Create a github api client with a given base URL and a path to a key.
*
* @param httpClient an instance of OkHttpClient
* @param baseUrl base URL
* @param privateKey the private key PEM file
* @param appId the github app ID
* @return github api client
*/
public static GitHubClient create(
final OkHttpClient httpClient,
final URI baseUrl,
final File privateKey,
final Integer appId) {
return createOrThrow(httpClient, baseUrl, null, privateKey, appId, null);
}
/**
* Create a github api client with a given base URL and a path to a key.
*
* @param httpClient an instance of OkHttpClient
* @param baseUrl base URL
* @param privateKey the private key PEM file
* @param appId the github app ID
* @return github api client
*/
public static GitHubClient create(
final OkHttpClient httpClient,
final URI baseUrl,
final URI graphqlUrl,
final File privateKey,
final Integer appId) {
return createOrThrow(httpClient, baseUrl, graphqlUrl, privateKey, appId, null);
}
/**
* Create a github api client with a given base URL and a path to a key.
*
* @param httpClient an instance of OkHttpClient
* @param baseUrl base URL
* @param privateKey the private key as byte array
* @param appId the github app ID
* @return github api client
*/
public static GitHubClient create(
final OkHttpClient httpClient,
final URI baseUrl,
final byte[] privateKey,
final Integer appId) {
return new GitHubClient(httpClient, baseUrl, null, null, privateKey, appId, null);
}
/**
* Create a github api client with a given base URL and a path to a key.
*
* @param httpClient an instance of OkHttpClient
* @param baseUrl base URL
* @param privateKey the private key PEM file
* @param appId the github app ID
* @return github api client
*/
public static GitHubClient create(
final OkHttpClient httpClient,
final URI baseUrl,
final File privateKey,
final Integer appId,
final Integer installationId) {
return createOrThrow(httpClient, baseUrl, null, privateKey, appId, installationId);
}
/**
* Create a github api client with a given base URL and a path to a key.
*
* @param httpClient an instance of OkHttpClient
* @param baseUrl base URL
* @param privateKey the private key as byte array
* @param appId the github app ID
* @return github api client
*/
public static GitHubClient create(
final OkHttpClient httpClient,
final URI baseUrl,
final byte[] privateKey,
final Integer appId,
final Integer installationId) {
return new GitHubClient(httpClient, baseUrl, null, null, privateKey, appId, installationId);
}
/**
* Create a github api client with a given base URL and authorization token.
*
* @param httpClient an instance of OkHttpClient
* @param baseUrl base URL
* @param token authorization token
* @return github api client
*/
public static GitHubClient create(
final OkHttpClient httpClient, final URI baseUrl, final String token) {
return new GitHubClient(httpClient, baseUrl, null, token, null, null, null);
}
public static GitHubClient create(
final OkHttpClient httpClient, final URI baseUrl, final URI graphqlUrl, final String token) {
return new GitHubClient(httpClient, baseUrl, graphqlUrl, token, null, null, null);
}
/**
* Create a github api client with a given base URL and a path to a key.
*
* @param httpClient an instance of OkHttpClient
* @param baseUrl base URL
* @param privateKey the private key PEM file
* @param appId the github app ID
* @return github api client
*/
public static GitHubClient create(
final HttpClient httpClient, final URI baseUrl, final File privateKey, final Integer appId) {
return createOrThrow(httpClient, baseUrl, null, privateKey, appId, null);
}
/**
* Create a github api client with a given base URL and a path to a key.
*
* @param httpClient an instance of OkHttpClient
* @param baseUrl base URL
* @param privateKey the private key PEM file
* @param appId the github app ID
* @return github api client
*/
public static GitHubClient create(
final HttpClient httpClient,
final URI baseUrl,
final URI graphqlUrl,
final File privateKey,
final Integer appId) {
return createOrThrow(httpClient, baseUrl, graphqlUrl, privateKey, appId, null);
}
/**
* Create a github api client with a given base URL and a path to a key.
*
* @param httpClient an instance of OkHttpClient
* @param baseUrl base URL
* @param privateKey the private key as byte array
* @param appId the github app ID
* @return github api client
*/
public static GitHubClient create(
final HttpClient httpClient,
final URI baseUrl,
final byte[] privateKey,
final Integer appId) {
return new GitHubClient(httpClient, baseUrl, null, null, privateKey, appId, null);
}
/**
* Create a github api client with a given base URL and a path to a key.
*
* @param httpClient an instance of OkHttpClient
* @param baseUrl base URL
* @param privateKey the private key PEM file
* @param appId the github app ID
* @return github api client
*/
public static GitHubClient create(
final HttpClient httpClient,
final URI baseUrl,
final File privateKey,
final Integer appId,
final Integer installationId) {
return createOrThrow(httpClient, baseUrl, null, privateKey, appId, installationId);
}
/**
* Create a github api client with a given base URL and a path to a key.
*
* @param httpClient an instance of OkHttpClient
* @param baseUrl base URL
* @param privateKey the private key as byte array
* @param appId the github app ID
* @return github api client
*/
public static GitHubClient create(
final HttpClient httpClient,
final URI baseUrl,
final byte[] privateKey,
final Integer appId,
final Integer installationId) {
return new GitHubClient(httpClient, baseUrl, null, null, privateKey, appId, installationId);
}
/**
* Create a github api client with a given base URL and authorization token.
*
* @param httpClient an instance of OkHttpClient
* @param baseUrl base URL
* @param token authorization token
* @return github api client
*/
public static GitHubClient create(
final HttpClient httpClient, final URI baseUrl, final String token) {
return new GitHubClient(httpClient, baseUrl, null, token, null, null, null);
}
public static GitHubClient create(
final HttpClient httpClient, final URI baseUrl, final URI graphqlUrl, final String token) {
return new GitHubClient(httpClient, baseUrl, graphqlUrl, token, null, null, null);
}
/**
* Receives a github client and scopes it to a certain installation ID.
*
* @param client the github client with a valid private key
* @param installationId the installation ID to be scoped
* @return github api client
*/
public static GitHubClient scopeForInstallationId(
final GitHubClient client, final int installationId) {
if (client.getPrivateKey().isEmpty()) {
throw new RuntimeException("Installation ID scoped client needs a private key");
}
return new GitHubClient(
client.client,
client.baseUrl,
null,
null,
client.getPrivateKey().get(),
client.appId,
installationId);
}
public GitHubClient withScopeForInstallationId(final int installationId) {
if (Optional.ofNullable(privateKey).isEmpty()) {
throw new RuntimeException("Installation ID scoped client needs a private key");
}
return new GitHubClient(
client, baseUrl, graphqlUrl.orElse(null), null, privateKey, appId, installationId);
}
/**
* This is for clients authenticated as a GitHub App: when performing operations, the
* "installation" of the App must be specified. This returns a {@code GitHubClient} that has been
* scoped to the user's/organization's installation of the app, if any.
*/
public CompletionStage<Optional<GitHubClient>> asAppScopedClient(final String owner) {
return Async.exceptionallyCompose(
this.createOrganisationClient(owner)
.createGithubAppClient()
.getInstallation()
.thenApply(Installation::id),
e -> {
if (e.getCause() instanceof RequestNotOkException
&& ((RequestNotOkException) e.getCause()).statusCode() == HTTP_NOT_FOUND) {
return this.createUserClient(owner)
.createGithubAppClient()
.getUserInstallation()
.thenApply(Installation::id);
}
return CompletableFuture.failedFuture(e);
})
.thenApply(id -> Optional.of(this.withScopeForInstallationId(id)))
.exceptionally(
e -> {
if (e.getCause() instanceof RequestNotOkException
&& ((RequestNotOkException) e.getCause()).statusCode() == HTTP_NOT_FOUND) {
return Optional.empty();
}
throw new RuntimeException(e);
});
}
public GitHubClient withTracer(final Tracer tracer) {
this.tracer = tracer;
this.client.setTracer(tracer);
return this;
}
public Optional<byte[]> getPrivateKey() {
return Optional.ofNullable(privateKey);
}
public Optional<String> 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);
}
/**
* Create GitHub App API client
*
* @return GitHub App API client
*/
public GithubAppClient createGithubAppClient() {
return new GithubAppClient(this);
}
Json json() {
return json;
}
/**
* Make a 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<HttpResponse> request(final String path) {
return call("GET", path);
}
/**
* Make a 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<HttpResponse> request(
final String path, final Map<String, String> extraHeaders) {
return call("GET", path, extraHeaders);
}
/**
* Make a http GET request for the given path on the server
*
* @param path relative to the GitHub base url
* @return body deserialized as provided type
*/
<T> CompletableFuture<T> request(final String path, final Class<T> clazz) {
return call(path)
.thenApply(response -> json().fromJsonUncheckedNotNull(response.bodyString(), clazz));
}
/**
* Make a 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
*/
<T> CompletableFuture<T> request(
final String path, final Class<T> clazz, final Map<String, String> extraHeaders) {
return call("GET", path, null, extraHeaders)
.thenApply(response -> json().fromJsonUncheckedNotNull(response.bodyString(), clazz));
}
/**
* Make a 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
*/
<T> CompletableFuture<T> request(
final String path,
final TypeReference<T> typeReference,
final Map<String, String> extraHeaders) {
return call("GET", path, null, extraHeaders)
.thenApply(
response -> json().fromJsonUncheckedNotNull(response.bodyString(), typeReference));
}
/**
* Make a http request for the given path on the GitHub server.
*
* @param path relative to the GitHub base url
* @return body deserialized as provided type
*/
<T> CompletableFuture<T> request(final String path, final TypeReference<T> typeReference) {
return call(path)
.thenApply(
response -> json().fromJsonUncheckedNotNull(response.bodyString(), typeReference));
}
/**
* Make a 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<HttpResponse> post(final String path, final String data) {
return call("POST", path, data);
}
/**
* Make a 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<HttpResponse> post(
final String path, final String data, final Map<String, String> extraHeaders) {
return call("POST", path, data, extraHeaders);
}
/**
* Make a 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
*/
<T> CompletableFuture<T> post(
final String path,
final String data,
final Class<T> clazz,
final Map<String, String> extraHeaders) {
return post(path, data, extraHeaders)
.thenApply(response -> json().fromJsonUncheckedNotNull(response.bodyString(), clazz));
}
/**
* Make a 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
*/
<T> CompletableFuture<T> post(final String path, final String data, final Class<T> clazz) {
return post(path, data)
.thenApply(response -> json().fromJsonUncheckedNotNull(response.bodyString(), 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<HttpResponse> postGraphql(final String data) {
return graphqlRequestBuilder()
.thenCompose(
requestBuilder -> {
final HttpRequest request = requestBuilder.method("POST").body(data).build();
log.info("Making POST request to {}", request.url());
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
* @return response body as String
*/
CompletableFuture<HttpResponse> put(final String path, final String data) {
return call("PUT", path, data);
}
/**
* 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
*/
<T> CompletableFuture<T> put(final String path, final String data, final Class<T> clazz) {
return put(path, data)
.thenApply(response -> json().fromJsonUncheckedNotNull(response.bodyString(), clazz));
}
/**
* Make a 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<HttpResponse> patch(final String path, final String data) {
return call("PATCH", path, data);
}
/**
* Make a 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
*/
<T> CompletableFuture<T> patch(final String path, final String data, final Class<T> clazz) {
return patch(path, data)
.thenApply(response -> json().fromJsonUncheckedNotNull(response.bodyString(), clazz));
}
/**
* Make a 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
*/
<T> CompletableFuture<T> patch(
final String path,
final String data,
final Class<T> clazz,
final Map<String, String> extraHeaders) {
return call("PATCH", path, data, extraHeaders)
.thenApply(response -> json().fromJsonUncheckedNotNull(response.bodyString(), clazz));
}
/**
* Make a http DELETE request for the given path.
*
* @param path relative to the GitHub base url
* @return response body as String
*/
CompletableFuture<HttpResponse> delete(final String path) {
return call("DELETE", path);
}
/**
* Make a 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<HttpResponse> delete(final String path, final String data) {
return call("DELETE", path, data);
}
/**
* Make a http DELETE request for the given path.
*
* @param path relative to the GitHub base url
* @return response body as String
*/
private CompletableFuture<HttpResponse> call(final String path) {
return call("GET", path, null, null);
}
/**
* Make a http request for the given path on the GitHub server.
*
* @param method HTTP method
* @param path relative to the GitHub base url
* @return response body as String
*/
private CompletableFuture<HttpResponse> call(final String method, final String path) {
return call(method, path, null, null);
}
/**
* Make a http request for the given path on the GitHub server.
*
* @param method HTTP method
* @param path relative to the GitHub base url
* @param extraHeaders extra github headers to be added to the call
* @return response body as String
*/
private CompletableFuture<HttpResponse> call(
final String method, final String path, final Map<String, String> extraHeaders) {
return call(method, path, null, extraHeaders);
}
/*
* Make a http request for the given path on the GitHub server.
*
* @param method HTTP method
* @param path relative to the GitHub base url
* @param data request body as stringified JSON
* @return response body as String
*/
private CompletableFuture<HttpResponse> call(
final String method, final String path, final String data) {
return call(method, path, data, null);
}
/**
* Make a http request for the given path on the GitHub server.
*
* @param method HTTP method
* @param path relative to the GitHub base url
* @param data request body as stringified JSON
* @param extraHeaders extra github headers to be added to the call
* @return response body as String
*/
private CompletableFuture<HttpResponse> call(
final String method,
final String path,
@Nullable final String data,
@Nullable final Map<String, String> extraHeaders) {
return requestBuilder(path)
.thenCompose(
requestBuilder -> {
final ImmutableHttpRequest.Builder builder = requestBuilder.method(method);
if (data != null) {
builder.body(data);
}
final HttpRequest request =
extraHeaders == null || extraHeaders.isEmpty()
? builder.build()
: toHttpRequestHeaders(builder, extraHeaders).build();
log.debug("Making {} request to {}", method, 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("^/+", "");
}
/**
* Adds extra headers to the Request Builder
*
* @param builder the request builder
* @param extraHeaders the extra headers to be added
* @return the request builder with the extra headers
*/
private ImmutableHttpRequest.Builder toHttpRequestHeaders(
final ImmutableHttpRequest.Builder builder, final Map<String, String> extraHeaders) {
HttpRequest request = builder.build();
extraHeaders.forEach(
(headerKey, headerValue) -> {
if (request.headers().containsKey(headerKey)) {
List<String> headers = new ArrayList<>(request.headers().get(headerKey));
headers.add(headerValue);
builder.putHeaders(headerKey, headers);
} else {
builder.putHeaders(headerKey, List.of(headerValue));
}
});
return builder;
}
/*
* Create a Request Builder for this GitHub GraphQL server.
*
* @return GraphQL Request Builder
*/
private CompletableFuture<ImmutableHttpRequest.Builder> graphqlRequestBuilder() {
URI url = graphqlUrl.orElseThrow(() -> new IllegalStateException("No graphql url set"));
return requestBuilder("/graphql")
.thenApply(requestBuilder -> requestBuilder.url(url.toString()));
}
/*
* Create a Request Builder for this GitHub server.
*
* @param path relative URI
* @return Request Builder
*/
private CompletableFuture<ImmutableHttpRequest.Builder> requestBuilder(final String path) {
return getAuthorizationHeader(path)
.thenApply(
authHeader ->
ImmutableHttpRequest.builder()
.url(urlFor(path))
.method("GET")
.body("")
.putHeaders(HttpHeaders.ACCEPT, List.of(MediaType.APPLICATION_JSON))
.putHeaders(HttpHeaders.CONTENT_TYPE, List.of(MediaType.APPLICATION_JSON))
.putHeaders(HttpHeaders.AUTHORIZATION, List.of(authHeader)));
}
/*
* Check if the GraphQL API is enabled for this client.
*
* @return true if the GraphQL API is enabled, false otherwise
*/
public boolean isGraphqlEnabled() {
return graphqlUrl.isPresent();
}
/*
Generates the Authentication header, given the API endpoint and the credentials provided.
<p>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 CompletableFuture<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 completedFuture(String.format("token %s", token));