-
Notifications
You must be signed in to change notification settings - Fork 775
Expand file tree
/
Copy pathGitHubRequest.java
More file actions
882 lines (801 loc) · 26.5 KB
/
GitHubRequest.java
File metadata and controls
882 lines (801 loc) · 26.5 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
package org.kohsuke.github;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.kohsuke.github.connector.GitHubConnectorRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.WillClose;
import static java.util.Arrays.asList;
// TODO: Auto-generated Javadoc
/**
* Class {@link GitHubRequest} represents an immutable instance used by the client to determine what information to
* retrieve from a GitHub server. Use the {@link Builder} to construct a {@link GitHubRequest}.
* <p>
* NOTE: {@link GitHubRequest} should include the data type to be returned. Any use cases where the same request should
* be used to return different types of data could be handled in some other way. However, the return type is currently
* not specified until late in the building process, so this is still untyped.
* </p>
*
* @author Liam Newman
*/
public class GitHubRequest implements GitHubConnectorRequest {
/**
* The Class Entry.
*/
protected static class Entry {
/** The key. */
final String key;
/** The value. */
final Object value;
/**
* Instantiates a new entry.
*
* @param key
* the key
* @param value
* the value
*/
protected Entry(String key, Object value) {
this.key = key;
this.value = value;
}
}
/**
* Class {@link Builder} follows the builder pattern for {@link GitHubRequest}.
*
* @param <B>
* The type of {@link Builder} to return from the various "with*" methods.
*/
static class Builder<B extends Builder<B>> {
/**
* The base GitHub API for this request.
*/
@Nonnull
private String apiUrl;
@Nonnull
private final List<Entry> args;
private byte[] body;
private boolean forceBody;
/**
* The header values for this request.
*/
@Nonnull
private final Map<String, List<String>> headers;
/**
* Injected local data map
*/
@Nonnull
private final Map<String, Object> injectedMappingValues;
/**
* Request method.
*/
@Nonnull
private String method;
@Nonnull
private RateLimitTarget rateLimitTarget;
@Nonnull
private String urlPath;
private Builder(@Nonnull List<Entry> args,
@Nonnull Map<String, List<String>> headers,
@Nonnull Map<String, Object> injectedMappingValues,
@Nonnull String apiUrl,
@Nonnull String urlPath,
@Nonnull String method,
@Nonnull RateLimitTarget rateLimitTarget,
@CheckForNull byte[] body,
boolean forceBody) {
this.args = new ArrayList<>(args);
TreeMap<String, List<String>> caseInsensitiveMap = new TreeMap<>(nullableCaseInsensitiveComparator);
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
caseInsensitiveMap.put(entry.getKey(), new ArrayList<>(entry.getValue()));
}
this.headers = caseInsensitiveMap;
this.injectedMappingValues = new LinkedHashMap<>(injectedMappingValues);
this.apiUrl = apiUrl;
this.urlPath = urlPath;
this.method = method;
this.rateLimitTarget = rateLimitTarget;
this.body = body;
this.forceBody = forceBody;
}
/**
* Create a new {@link GitHubRequest.Builder}
*/
protected Builder() {
this(new ArrayList<>(),
new TreeMap<>(nullableCaseInsensitiveComparator),
new LinkedHashMap<>(),
GitHubClient.GITHUB_URL,
"/",
"GET",
RateLimitTarget.CORE,
null,
false);
}
/**
* Builds a {@link GitHubRequest} from this builder.
*
* @return a {@link GitHubRequest}
* @throws GHException
* wrapping a {@link MalformedURLException} if the GitHub API URL cannot be constructed
*/
public GitHubRequest build() {
return new GitHubRequest(args,
headers,
injectedMappingValues,
apiUrl,
urlPath,
method,
rateLimitTarget,
body,
forceBody);
}
/**
* Content type requester.
*
* @param contentType
* the content type
* @return the request builder
*/
public B contentType(String contentType) {
this.setHeader("Content-type", contentType);
return (B) this;
}
/**
* Small number of GitHub APIs use HTTP methods somewhat inconsistently, and use a body where it's not expected.
* Normally whether parameters go as query parameters or a body depends on the HTTP verb in use, but this method
* forces the parameters to be sent as a body.
*
* @return the request builder
*/
public B inBody() {
forceBody = true;
return (B) this;
}
/**
* Object to inject into binding.
*
* @param value
* the value
* @return the request builder
*/
public B injectMappingValue(@NonNull Object value) {
return injectMappingValue(value.getClass().getName(), value);
}
/**
* Object to inject into binding.
*
* @param name
* the name
* @param value
* the value
* @return the request builder
*/
public B injectMappingValue(@NonNull String name, Object value) {
this.injectedMappingValues.put(name, value);
return (B) this;
}
/**
* Method requester.
*
* @param method
* the method
* @return the request builder
*/
public B method(@Nonnull String method) {
this.method = method;
return (B) this;
}
/**
* Method requester.
*
* @param rateLimitTarget
* the rate limit target for this request. Default is {@link RateLimitTarget#CORE}.
* @return the request builder
*/
public B rateLimit(@Nonnull RateLimitTarget rateLimitTarget) {
this.rateLimitTarget = rateLimitTarget;
return (B) this;
}
/**
* Removes all arg entries for a specific key.
*
* @param key
* the key
* @return the request builder
*/
public B remove(String key) {
for (int index = 0; index < args.size();) {
if (args.get(index).key.equals(key)) {
args.remove(index);
} else {
index++;
}
}
return (B) this;
}
/**
* Removes the named request HTTP header.
*
* @param name
* the name
* @return the request builder
*/
public B removeHeader(String name) {
headers.remove(name);
return (B) this;
}
/**
* Unlike {@link #with(String, String)}, overrides the existing value.
*
* @param key
* the key
* @param value
* the value
* @return the request builder
*/
public B set(String key, Object value) {
remove(key);
return with(key, value);
}
/**
* Sets the request HTTP header.
* <p>
* If a header of the same name is already set, this method overrides it.
*
* @param name
* the name
* @param value
* the value
* @return the request builder
*/
public B setHeader(String name, String value) {
List<String> field = new ArrayList<>();
field.add(value);
headers.put(name, field);
return (B) this;
}
/**
* With requester.
*
* @param body
* the body
* @return the request builder
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public B with(@WillClose InputStream body) throws IOException {
this.body = IOUtils.toByteArray(body);
IOUtils.closeQuietly(body);
return (B) this;
}
/**
* With requester.
*
* @param map
* map of key value pairs to add
* @return the request builder
*/
public B with(Map<String, Object> map) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
with(entry.getKey(), entry.getValue());
}
return (B) this;
}
/**
* With requester.
*
* @param key
* the key
* @param value
* the value
* @return the request builder
*/
public B with(String key, Collection<?> value) {
return with(key, (Object) value);
}
/**
* With requester.
*
* @param key
* the key
* @param e
* the e
* @return the request builder
*/
public B with(String key, Enum<?> e) {
if (e == null)
return with(key, (Object) null);
return with(key, transformEnum(e));
}
/**
* With requester.
*
* @param key
* the key
* @param value
* the value
* @return the request builder
*/
public B with(String key, Map<?, ?> value) {
return with(key, (Object) value);
}
/**
* With requester.
*
* @param key
* the key
* @param value
* the value
* @return the request builder
*/
public B with(String key, Object value) {
if (value != null) {
args.add(new Entry(key, value));
}
return (B) this;
}
/**
* With requester.
*
* @param key
* the key
* @param value
* the value
* @return the request builder
*/
public B with(String key, String value) {
return with(key, (Object) value);
}
/**
* With requester.
*
* @param key
* the key
* @param value
* the value
* @return the request builder
*/
public B with(String key, boolean value) {
return with(key, (Object) value);
}
/**
* With requester.
*
* @param key
* the key
* @param value
* the value
* @return the request builder
*/
public B with(String key, int value) {
return with(key, (Object) value);
}
/**
* With requester.
*
* @param key
* the key
* @param value
* the value
* @return the request builder
*/
public B with(String key, long value) {
return with(key, (Object) value);
}
/**
* With preview.
*
* @param name
* the name
* @return the b
*/
public B withAccept(String name) {
return withHeader("Accept", name);
}
/**
* With header requester.
*
* @param url
* the url
* @return the request builder
*/
public B withApiUrl(String url) {
this.apiUrl = url;
return (B) this;
}
/**
* With header requester.
*
* @param name
* the name
* @param value
* the value
* @return the request builder
*/
public B withHeader(String name, String value) {
List<String> field = headers.get(name);
if (field == null) {
setHeader(name, value);
} else {
field.add(value);
}
return (B) this;
}
/**
* With nullable requester.
*
* @param key
* the key
* @param value
* the value
* @return the request builder
*/
public B withNullable(String key, Object value) {
args.add(new Entry(key, value));
return (B) this;
}
/**
* Path component of api URL. Appended to api url.
* <p>
* If urlPath starts with a slash, it will be URI encoded as a path. If it starts with anything else, it will be
* used as is.
*
* @param urlPath
* the url path
* @param urlPathItems
* the content type
* @return the request builder
*/
public B withUrlPath(@Nonnull String urlPath, @Nonnull String... urlPathItems) {
// full url may be set and reset as needed
if (urlPathItems.length == 0 && !urlPath.startsWith("/")) {
return setRawUrlPath(urlPath);
}
// Once full url is set, do not allow path setting
if (!this.urlPath.startsWith("/")) {
throw new GHException("Cannot append to url path after setting a full url");
}
String tailUrlPath = urlPath;
if (urlPathItems.length != 0) {
tailUrlPath += "/" + String.join("/", urlPathItems);
}
tailUrlPath = StringUtils.prependIfMissing(tailUrlPath, "/");
this.urlPath = urlPathEncode(tailUrlPath);
return (B) this;
}
/**
* NOT FOR PUBLIC USE. Do not make this method public.
* <p>
* Sets the path component of api URL without URI encoding.
* <p>
* Should only be used when passing a literal URL field from a GHObject, such as {@link GHContent#refresh()} or
* when needing to set query parameters on requests methods that don't usually have them, such as
* {@link GHRelease#uploadAsset(String, InputStream, String)}.
*
* @param rawUrlPath
* the content type
* @return the request builder
*/
B setRawUrlPath(@Nonnull String rawUrlPath) {
Objects.requireNonNull(rawUrlPath);
// This method should only work for full urls, which must start with "http"
if (!rawUrlPath.startsWith("http")) {
throw new GHException("Raw URL must start with 'http'");
}
this.urlPath = rawUrlPath;
return (B) this;
}
}
private static final List<String> METHODS_WITHOUT_BODY = asList("GET", "DELETE");
private static final Comparator<String> nullableCaseInsensitiveComparator = Comparator
.nullsFirst(String.CASE_INSENSITIVE_ORDER);
/**
* Encode the path to url safe string.
*
* @param value
* string to be path encoded.
* @return The encoded string.
*/
private static String urlPathEncode(String value) {
try {
return new URI(null, null, value, null, null).toASCIIString();
} catch (URISyntaxException ex) {
throw new AssertionError(ex);
}
}
/**
* Gets the final GitHub API URL.
*
* @param apiUrl
* the api url
* @param tailApiUrl
* the tail api url
* @return the api URL
* @throws GHException
* wrapping a {@link MalformedURLException} if the GitHub API URL cannot be constructed
*/
@Nonnull
static URL getApiURL(String apiUrl, String tailApiUrl) {
try {
if (!tailApiUrl.startsWith("/")) {
apiUrl = "";
} else if ("github.com".equals(apiUrl)) {
// backward compatibility
apiUrl = GitHubClient.GITHUB_URL;
}
String fullApiUrl = apiUrl + tailApiUrl;
try {
return new URI(fullApiUrl).toURL();
} catch (URISyntaxException e) {
// Some API URL fields include unescaped square brackets in path segments.
// Keep existing escaping as-is while making the URL URI-safe for connectors.
return new URI(encodeSquareBrackets(fullApiUrl)).toURL();
}
} catch (Exception e) {
// The data going into constructing this URL should be controlled by the GitHub API framework,
// so a malformed URL here is a framework runtime error.
// All callers of this method ended up wrapping and throwing GHException,
// indicating the functionality should be moved to the common code path.
throw new GHException("Unable to build GitHub API URL", e);
}
}
@Nonnull
private static String encodeSquareBrackets(@Nonnull String url) {
URL parsedUrl;
try {
parsedUrl = new URL(url);
} catch (MalformedURLException e) {
// Preserve the original input when URL parsing fails so existing error behavior is unchanged.
return url;
}
String path = parsedUrl.getPath();
String query = parsedUrl.getQuery();
String ref = parsedUrl.getRef();
StringBuilder encodedUrl = new StringBuilder();
encodedUrl.append(parsedUrl.getProtocol()).append("://").append(parsedUrl.getAuthority());
if (path != null) {
encodedUrl.append(path.replace("[", "%5B").replace("]", "%5D"));
}
if (query != null) {
encodedUrl.append('?').append(query.replace("[", "%5B").replace("]", "%5D"));
}
if (ref != null) {
encodedUrl.append('#').append(ref.replace("[", "%5B").replace("]", "%5D"));
}
return encodedUrl.toString();
}
/**
* Create a new {@link Builder}.
*
* @return a new {@link Builder}.
*/
static Builder<?> newBuilder() {
return new Builder<>();
}
/**
* Transform Java Enum into Github constants given its conventions.
*
* @param en
* Enum to be transformed
* @return a String containing the value of a Github constant
*/
static String transformEnum(Enum<?> en) {
// by convention Java constant names are upper cases, but github uses
// lower-case constants. GitHub also uses '-', which in Java we always
// replace with '_'
return en.toString().toLowerCase(Locale.ENGLISH).replace('_', '-');
}
private final String apiUrl;
private final List<Entry> args;
private final byte[] body;
private final boolean forceBody;
private final Map<String, List<String>> headers;
private final Map<String, Object> injectedMappingValues;
private final String method;
private final RateLimitTarget rateLimitTarget;
private final URL url;
private final String urlPath;
@SuppressFBWarnings(value = { "CT_CONSTRUCTOR_THROW" }, justification = "Basic argument validation")
private GitHubRequest(@Nonnull List<Entry> args,
@Nonnull Map<String, List<String>> headers,
@Nonnull Map<String, Object> injectedMappingValues,
@Nonnull String apiUrl,
@Nonnull String urlPath,
@Nonnull String method,
@Nonnull RateLimitTarget rateLimitTarget,
@CheckForNull byte[] body,
boolean forceBody) {
this.args = Collections.unmodifiableList(new ArrayList<>(args));
TreeMap<String, List<String>> caseInsensitiveMap = new TreeMap<>(nullableCaseInsensitiveComparator);
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
caseInsensitiveMap.put(entry.getKey(), Collections.unmodifiableList(new ArrayList<>(entry.getValue())));
}
this.headers = Collections.unmodifiableMap(caseInsensitiveMap);
this.injectedMappingValues = Collections.unmodifiableMap(new LinkedHashMap<>(injectedMappingValues));
this.apiUrl = apiUrl;
this.urlPath = urlPath;
this.method = method;
this.rateLimitTarget = rateLimitTarget;
this.body = body;
this.forceBody = forceBody;
String tailApiUrl = buildTailApiUrl();
url = getApiURL(apiUrl, tailApiUrl);
}
/**
* The headers for this request.
*
* @return the {@link Map} of headers
*/
@Override
@SuppressFBWarnings(value = { "EI_EXPOSE_REP" }, justification = "Unmodifiable Map of unmodifiable lists")
@Nonnull
public Map<String, List<String>> allHeaders() {
return headers;
}
/**
* The base GitHub API URL for this request represented as a {@link String}.
*
* @return the url string
*/
@Nonnull
public String apiUrl() {
return apiUrl;
}
/**
* The arguments for this request. Depending on the {@link #method()} and {@code #inBody()} these maybe added to the
* url or to the request body.
*
* @return the list of arguments
*/
@SuppressFBWarnings(value = { "EI_EXPOSE_REP" }, justification = "Already unmodifiable")
@Nonnull
public List<Entry> args() {
return args;
}
/**
* The {@link InputStream} to be sent as the body of this request.
*
* @return the {@link InputStream}.
*/
@Override
@CheckForNull
public InputStream body() {
return body != null ? new ByteArrayInputStream(body) : null;
}
/**
* The content type to be sent by this request.
*
* @return the content type.
*/
@Override
public String contentType() {
return header("Content-type");
}
/**
* Whether arguments for this request should be included in the URL or in the body of the request.
*
* @return true if the arguments should be sent in the body of the request.
*/
@Override
public boolean hasBody() {
return forceBody || !METHODS_WITHOUT_BODY.contains(method);
}
/**
* Gets the first value of a header field for this request.
*
* @param name
* the name of the header field.
* @return the value of the header field, or {@code null} if the header isn't set.
*/
@CheckForNull
public String header(String name) {
List<String> values = headers.get(name);
if (values != null) {
return values.get(0);
}
return null;
}
/**
* The headers for this request.
*
* @return the {@link Map} of headers
*/
@SuppressFBWarnings(value = { "EI_EXPOSE_REP" }, justification = "Already unmodifiable")
@Nonnull
public Map<String, Object> injectedMappingValues() {
return injectedMappingValues;
}
/**
* The method for this request, such as "GET", "PATCH", or "DELETE".
*
* @return the request method.
*/
@Override
@Nonnull
public String method() {
return method;
}
/**
* The rate limit target for this request.
*
* @return the rate limit to use for this request.
*/
@Nonnull
public RateLimitTarget rateLimitTarget() {
return rateLimitTarget;
}
/**
* The {@link URL} for this request. This is the actual URL the {@link GitHubClient} will send this request to.
*
* @return the request {@link URL}
*/
@Override
@Nonnull
public URL url() {
return url;
}
/**
* The url path to be added to the {@link #apiUrl()} for this request. If this does not start with a "/", it instead
* represents the full url string for this request.
*
* @return a url path or full url string
*/
@Nonnull
public String urlPath() {
return urlPath;
}
private String buildTailApiUrl() {
String tailApiUrl = urlPath;
if (!hasBody() && !args.isEmpty() && tailApiUrl.startsWith("/")) {
try {
StringBuilder argString = new StringBuilder();
boolean questionMarkFound = tailApiUrl.indexOf('?') != -1;
argString.append(questionMarkFound ? '&' : '?');
for (Iterator<Entry> it = args.listIterator(); it.hasNext();) {
Entry arg = it.next();
argString.append(URLEncoder.encode(arg.key, StandardCharsets.UTF_8.name()));
argString.append('=');
argString.append(URLEncoder.encode(arg.value.toString(), StandardCharsets.UTF_8.name()));
if (it.hasNext()) {
argString.append('&');
}
}
tailApiUrl += argString;
} catch (UnsupportedEncodingException e) {
throw new GHException("UTF-8 encoding required", e);
}
}
return tailApiUrl;
}
/**
* Create a {@link Builder} from this request. Initial values of the builder will be the same as this
* {@link GitHubRequest}.
*
* @return a {@link Builder} based on this request.
*/
Builder<?> toBuilder() {
return new Builder<>(args,
headers,
injectedMappingValues,
apiUrl,
urlPath,
method,
rateLimitTarget,
body,
forceBody);
}
}