Repository navigation
Expand file tree
/
Copy pathUtil.java
More file actions
607 lines (545 loc) · 21.2 KB
/
Copy pathUtil.java
File metadata and controls
607 lines (545 loc) · 21.2 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
/*
* Copyright © 2012 The Feign Authors (feign@commonhaus.dev)
*
* 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 feign;
import static java.lang.String.format;
import static java.util.Objects.nonNull;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Stream;
/** Utilities, typically copied in from guava, so as to avoid dependency conflicts. */
public class Util {
/** The HTTP Content-Length header field name. */
public static final String CONTENT_LENGTH = "Content-Length";
/** The HTTP Content-Type header field name. */
public static final String CONTENT_TYPE = "Content-Type";
/** The HTTP Content-Encoding header field name. */
public static final String CONTENT_ENCODING = "Content-Encoding";
/** The HTTP Accept-Encoding header field name. */
public static final String ACCEPT_ENCODING = "Accept-Encoding";
/** The HTTP Accept header field name. */
public static final String ACCEPT = "Accept";
/** The HTTP Retry-After header field name. */
public static final String RETRY_AFTER = "Retry-After";
/** Value for the Content-Encoding header that indicates that GZIP encoding is in use. */
public static final String ENCODING_GZIP = "gzip";
/** Value for the Content-Encoding header that indicates that DEFLATE encoding is in use. */
public static final String ENCODING_DEFLATE = "deflate";
/** UTF-8: eight-bit UCS Transformation Format. */
public static final Charset UTF_8 = StandardCharsets.UTF_8;
// com.google.common.base.Charsets
/** ISO-8859-1: ISO Latin Alphabet Number 1 (ISO-LATIN-1). */
public static final Charset ISO_8859_1 = StandardCharsets.ISO_8859_1;
private static final int BUF_SIZE = 0x800; // 2K chars (4K bytes)
// matches application/json, text/json, application/vnd.github+json,
// application/json;charset=utf-8
private static final Pattern JSON_CONTENT_TYPE =
Pattern.compile("(?i)\\w+/(?:[\\w._-]+\\+)?json.*");
// matches application/xml, text/xml, application/soap+xml, application/xml;charset=utf-8
private static final Pattern XML_CONTENT_TYPE =
Pattern.compile("(?i)\\w+/(?:[\\w._-]+\\+)?xml.*");
/** Type literal for {@code Map<String, ?>}. */
public static final Type MAP_STRING_WILDCARD =
new Types.ParameterizedTypeImpl(
null,
Map.class,
String.class,
new Types.WildcardTypeImpl(new Type[] {Object.class}, new Type[0]));
private Util() { // no instances
}
/** Copy of {@code com.google.common.base.Preconditions#checkArgument}. */
public static void checkArgument(
boolean expression, String errorMessageTemplate, Object... errorMessageArgs) {
if (!expression) {
throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs));
}
}
/** Copy of {@code com.google.common.base.Preconditions#checkNotNull}. */
public static <T> T checkNotNull(
T reference, String errorMessageTemplate, Object... errorMessageArgs) {
if (reference == null) {
// If either of these parameters is null, the right thing happens anyway
throw new NullPointerException(format(errorMessageTemplate, errorMessageArgs));
}
return reference;
}
/** Copy of {@code com.google.common.base.Preconditions#checkState}. */
public static void checkState(
boolean expression, String errorMessageTemplate, Object... errorMessageArgs) {
if (!expression) {
throw new IllegalStateException(format(errorMessageTemplate, errorMessageArgs));
}
}
/** Identifies a method as a default instance method. */
public static boolean isDefault(Method method) {
// Default methods are public non-abstract, non-synthetic, and non-static instance methods
// declared in an interface.
// method.isDefault() is not sufficient for our usage as it does not check
// for synthetic methods. As a result, it picks up overridden methods as well as actual default
// methods.
final int SYNTHETIC = 0x00001000;
return ((method.getModifiers()
& (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC | SYNTHETIC))
== Modifier.PUBLIC)
&& method.getDeclaringClass().isInterface();
}
/** Adapted from {@code com.google.common.base.Strings#emptyToNull}. */
public static String emptyToNull(String string) {
return string == null || string.isEmpty() ? null : string;
}
/**
* Removes values from the array that meet the criteria for removal via the supplied {@link
* Predicate} value
*/
@SuppressWarnings("unchecked")
public static <T> T[] removeValues(T[] values, Predicate<T> shouldRemove, Class<T> type) {
Collection<T> collection = new ArrayList<>(values.length);
for (T value : values) {
if (shouldRemove.negate().test(value)) {
collection.add(value);
}
}
T[] array = (T[]) Array.newInstance(type, collection.size());
return collection.toArray(array);
}
/** Adapted from {@code com.google.common.base.Strings#emptyToNull}. */
@SuppressWarnings("unchecked")
public static <T> T[] toArray(Iterable<? extends T> iterable, Class<T> type) {
Collection<T> collection;
if (iterable instanceof Collection) {
collection = (Collection<T>) iterable;
} else {
collection = new ArrayList<>();
for (T element : iterable) {
collection.add(element);
}
}
T[] array = (T[]) Array.newInstance(type, collection.size());
return collection.toArray(array);
}
/** Returns an unmodifiable collection which may be empty, but is never null. */
public static <T> Collection<T> valuesOrEmpty(Map<String, Collection<T>> map, String key) {
Collection<T> values = map.get(key);
return values != null ? values : Collections.emptyList();
}
public static void ensureClosed(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException ignored) { // NOPMD
}
}
}
/** Moved to {@code feign.Types.resolveLastTypeParameter} */
@Deprecated
public static Type resolveLastTypeParameter(Type genericContext, Class<?> supertype)
throws IllegalStateException {
return Types.resolveLastTypeParameter(genericContext, supertype);
}
/**
* This returns well known empty values for well-known java types. This returns null for types not
* in the following list.
*
* <ul>
* <li>{@code [Bb]oolean}
* <li>{@code byte[]}
* <li>{@code Collection}
* <li>{@code Iterator}
* <li>{@code List}
* <li>{@code Map}
* <li>{@code Set}
* </ul>
*
* <p>When {@link Feign.Builder#dismiss404() decoding HTTP 404 status}, you'll need to teach
* decoders a default empty value for a type. This method cheaply supports typical types by only
* looking at the raw type (vs type hierarchy). Decorate for sophistication.
*/
public static Object emptyValueOf(Type type) {
return EMPTIES.getOrDefault(Types.getRawType(type), () -> null).get();
}
private static final Map<Class<?>, Supplier<Object>> EMPTIES;
static {
final Map<Class<?>, Supplier<Object>> empties = new LinkedHashMap<>();
empties.put(boolean.class, () -> false);
empties.put(Boolean.class, () -> false);
empties.put(byte[].class, () -> new byte[0]);
empties.put(Collection.class, Collections::emptyList);
empties.put(Iterator.class, Collections::emptyIterator);
empties.put(List.class, Collections::emptyList);
empties.put(Map.class, Collections::emptyMap);
empties.put(Set.class, Collections::emptySet);
empties.put(Optional.class, Optional::empty);
empties.put(Stream.class, Stream::empty);
EMPTIES = Collections.unmodifiableMap(empties);
}
/** Adapted from {@code com.google.common.io.CharStreams.toString()}. */
public static String toString(Reader reader) throws IOException {
if (reader == null) {
return null;
}
try {
StringBuilder to = new StringBuilder();
CharBuffer charBuf = CharBuffer.allocate(BUF_SIZE);
// must cast to super class Buffer otherwise break when running with java 11
Buffer buf = charBuf;
while (reader.read(charBuf) != -1) {
buf.flip();
to.append(charBuf);
buf.clear();
}
return to.toString();
} finally {
ensureClosed(reader);
}
}
/** Adapted from {@code com.google.common.io.ByteStreams.toByteArray()}. */
public static byte[] toByteArray(InputStream in) throws IOException {
checkNotNull(in, "in");
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
copy(in, out);
return out.toByteArray();
} finally {
ensureClosed(in);
}
}
/** Adapted from {@code com.google.common.io.ByteStreams.copy()}. */
private static long copy(InputStream from, OutputStream to) throws IOException {
checkNotNull(from, "from");
checkNotNull(to, "to");
byte[] buf = new byte[BUF_SIZE];
long total = 0;
while (true) {
int r = from.read(buf);
if (r == -1) {
break;
}
to.write(buf, 0, r);
total += r;
}
return total;
}
public static String decodeOrDefault(byte[] data, Charset charset, String defaultValue) {
if (data == null) {
return defaultValue;
}
checkNotNull(charset, "charset");
try {
return charset.newDecoder().decode(ByteBuffer.wrap(data)).toString();
} catch (CharacterCodingException ex) {
return defaultValue;
}
}
/**
* If the provided String is not null or empty.
*
* @param value to evaluate.
* @return true of the value is not null and not empty.
*/
public static boolean isNotBlank(String value) {
return value != null && !value.isEmpty();
}
/**
* If the provided String is null or empty.
*
* @param value to evaluate.
* @return true if the value is null or empty.
*/
public static boolean isBlank(String value) {
return value == null || value.isEmpty();
}
/**
* Copy entire map of string collection.
*
* <p>The copy is unmodifiable map of unmodifiable collections.
*
* @param map string collection map
* @return copy of the map or an empty map if the map is null.
*/
public static Map<String, Collection<String>> caseInsensitiveCopyOf(
Map<String, Collection<String>> map) {
if (map == null) {
return Collections.emptyMap();
}
Map<String, Collection<String>> result = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
for (Map.Entry<String, Collection<String>> entry : map.entrySet()) {
String key = entry.getKey();
if (!result.containsKey(key)) {
result.put(key.toLowerCase(Locale.ROOT), new LinkedList<>());
}
result.get(key).addAll(entry.getValue());
}
result.replaceAll((key, value) -> Collections.unmodifiableCollection(value));
return Collections.unmodifiableMap(result);
}
public static <T extends Enum<?>> T enumForName(Class<T> enumClass, Object object) {
String name = (nonNull(object)) ? object.toString() : null;
for (T enumItem : enumClass.getEnumConstants()) {
if (enumItem.name().equalsIgnoreCase(name) || enumItem.toString().equalsIgnoreCase(name)) {
return enumItem;
}
}
return null;
}
public static List<Field> allFields(Class<?> clazz) {
if (Objects.equals(clazz, Object.class)) {
return Collections.emptyList();
}
List<Field> fields = new ArrayList<>();
fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
fields.addAll(allFields(clazz.getSuperclass()));
return fields;
}
public static String getThreadIdentifier() {
Thread currentThread = Thread.currentThread();
return currentThread.getThreadGroup()
+ "_"
+ currentThread.getName()
+ "_"
+ currentThread.getId();
}
/**
* Checks whether the {@code Content-Type} header of the given template denotes JSON.
*
* <p>Matches {@code application/json} as well as suffixed types such as {@code
* application/vnd.github+json}. The header name is matched case-insensitively.
*
* @param template the request template to check
* @return {@code true} if the content type is JSON, {@code false} otherwise
*/
@Experimental
public static boolean isJsonContentType(RequestTemplate template) {
return hasContentTypeMatching(template, JSON_CONTENT_TYPE);
}
/**
* Checks whether the {@code Content-Type} header of the given response denotes JSON.
*
* <p>Matches {@code application/json} as well as suffixed types such as {@code
* application/vnd.github+json}. The header name is matched case-insensitively.
*
* @param response the response to check
* @return {@code true} if the content type is JSON, {@code false} otherwise
*/
@Experimental
public static boolean isJsonContentType(Response response) {
return hasContentTypeMatching(response, JSON_CONTENT_TYPE);
}
/**
* Checks whether the {@code Content-Type} header of the given template denotes XML.
*
* <p>Matches {@code application/xml} and {@code text/xml} as well as suffixed types such as
* {@code application/soap+xml}. The header name is matched case-insensitively.
*
* @param template the request template to check
* @return {@code true} if the content type is XML, {@code false} otherwise
*/
@Experimental
public static boolean isXmlContentType(RequestTemplate template) {
return hasContentTypeMatching(template, XML_CONTENT_TYPE);
}
/**
* Checks whether the {@code Content-Type} header of the given response denotes XML.
*
* <p>Matches {@code application/xml} and {@code text/xml} as well as suffixed types such as
* {@code application/soap+xml}. The header name is matched case-insensitively.
*
* @param response the response to check
* @return {@code true} if the content type is XML, {@code false} otherwise
*/
@Experimental
public static boolean isXmlContentType(Response response) {
return hasContentTypeMatching(response, XML_CONTENT_TYPE);
}
/**
* Checks whether the {@code Content-Type} header of the given template starts with the given
* media type, ignoring case and any parameters such as {@code ;charset=utf-8}.
*
* @param template the request template to check
* @param mediaType the media type to look for, for example {@code
* application/x-www-form-urlencoded}
* @return {@code true} if the content type matches, {@code false} otherwise
*/
@Experimental
public static boolean hasContentType(RequestTemplate template, String mediaType) {
return matchesMediaType(contentTypes(template), mediaType);
}
/**
* Checks whether the {@code Content-Type} header of the given response starts with the given
* media type, ignoring case and any parameters such as {@code ;charset=utf-8}.
*
* @param response the response to check
* @param mediaType the media type to look for, for example {@code text/csv}
* @return {@code true} if the content type matches, {@code false} otherwise
*/
@Experimental
public static boolean hasContentType(Response response, String mediaType) {
return matchesMediaType(contentTypes(response), mediaType);
}
/**
* Reads the {@code charset} parameter of a single {@code Content-Type} header value, wherever it
* appears among the parameters.
*
* <p>Parameters are scanned quote-aware: a {@code ;} inside a quoted parameter value is data
* rather than a parameter separator, and an escaped quote does not end the quoted value. Charset
* text inside a quoted parameter value, or inside another parameter's name, is therefore data and
* not the charset parameter. Parameter names are matched ignoring case, and whitespace around the
* name, the {@code =} and the value is ignored.
*
* @param contentType a single {@code Content-Type} header value, may be {@code null}
* @return the declared charset, {@link #UTF_8} if the declared one is illegal or unsupported, or
* {@code null} if the value declares no charset at all
*/
@Experimental
public static Charset charsetOfContentType(String contentType) {
if (contentType == null) {
return null;
}
int length = contentType.length();
int start = 0;
while (start <= length) {
int end = nextUnquoted(contentType, start, length, ';');
Charset charset = charsetParameterOf(contentType, start, end);
if (charset != null) {
return charset;
}
if (end >= length) {
return null;
}
start = end + 1;
}
return null;
}
/** Reads {@code name=value} between the given bounds, or null if the name is not charset. */
private static Charset charsetParameterOf(String contentType, int start, int end) {
int equals = nextUnquoted(contentType, start, end, '=');
if (equals >= end) {
return null;
}
if (!"charset".equalsIgnoreCase(contentType.substring(start, equals).trim())) {
return null;
}
try {
return Charset.forName(unquote(contentType.substring(equals + 1, end).trim()));
} catch (IllegalCharsetNameException | UnsupportedCharsetException e) {
return UTF_8;
}
}
/** Index of the first {@code separator} between the given bounds outside a quoted-string. */
private static int nextUnquoted(String value, int start, int end, char separator) {
boolean quoted = false;
for (int i = start; i < end; i++) {
char c = value.charAt(i);
if (quoted) {
if (c == '\\' && i + 1 < end) {
i++; // a backslash escapes the next character inside a quoted-string, e.g. \" or \\
} else if (c == '"') {
quoted = false;
}
} else if (c == '"') {
quoted = true;
} else if (c == separator) {
return i;
}
}
return end;
}
/** Removes the surrounding quotes of a quoted-string value and resolves its escapes. */
private static String unquote(String value) {
if (value.isEmpty() || value.charAt(0) != '"') {
return value;
}
StringBuilder unquoted = new StringBuilder(value.length());
for (int i = 1; i < value.length(); i++) {
char c = value.charAt(i);
if (c == '"') {
return unquoted.toString(); // anything after the closing quote is not part of the value
}
if (c == '\\' && i + 1 < value.length()) {
c = value.charAt(++i);
}
unquoted.append(c);
}
return unquoted.toString(); // unterminated quoted-string, tolerate it
}
private static boolean matchesMediaType(Stream<String> contentTypes, String mediaType) {
return contentTypes.anyMatch(
contentType -> {
String trimmed = contentType.trim();
return trimmed.regionMatches(true, 0, mediaType, 0, mediaType.length())
&& (trimmed.length() == mediaType.length()
|| trimmed.charAt(mediaType.length()) == ';');
});
}
private static Stream<String> contentTypes(RequestTemplate template) {
return contentTypes(template.headers());
}
private static Stream<String> contentTypes(Response response) {
if (response == null || response.headers() == null) {
return Stream.empty();
}
return contentTypes(response.headers());
}
private static Stream<String> contentTypes(Map<String, Collection<String>> headers) {
return headers.entrySet().stream()
.filter(header -> CONTENT_TYPE.equalsIgnoreCase(header.getKey()))
.map(Map.Entry::getValue)
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.filter(Objects::nonNull);
}
private static boolean hasContentTypeMatching(RequestTemplate template, Pattern pattern) {
return matchesPattern(contentTypes(template), pattern);
}
private static boolean hasContentTypeMatching(Response response, Pattern pattern) {
return matchesPattern(contentTypes(response), pattern);
}
private static boolean matchesPattern(Stream<String> contentTypes, Pattern pattern) {
return contentTypes.anyMatch(contentType -> pattern.matcher(contentType.trim()).matches());
}
}