/
GenericUrl.java
641 lines (590 loc) · 17.5 KB
/
GenericUrl.java
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
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.http;
import com.google.api.client.util.GenericData;
import com.google.api.client.util.Key;
import com.google.api.client.util.Preconditions;
import com.google.api.client.util.escape.CharEscapers;
import com.google.api.client.util.escape.Escaper;
import com.google.api.client.util.escape.PercentEscaper;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* URL builder in which the query parameters are specified as generic data key/value pairs, based on
* the specification <a href="http://tools.ietf.org/html/rfc3986">RFC 3986: Uniform Resource
* Identifier (URI)</a>.
*
* <p>
* The query parameters are specified with the data key name as the parameter name, and the data
* value as the parameter value. Subclasses can declare fields for known query parameters using the
* {@link Key} annotation. {@code null} parameter names are not allowed, but {@code null} query
* values are allowed.
* </p>
*
* <p>
* Query parameter values are parsed using {@link UrlEncodedParser#parse(String, Object)}.
* </p>
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.0
* @author Yaniv Inbar
*/
public class GenericUrl extends GenericData {
private static final Escaper URI_FRAGMENT_ESCAPER =
new PercentEscaper("=&-_.!~*'()@:$,;/?:", false);
/** Scheme (lowercase), for example {@code "https"}. */
private String scheme;
/** Host, for example {@code "www.google.com"}. */
private String host;
/** User info or {@code null} for none, for example {@code "username:password"}. */
private String userInfo;
/** Port number or {@code -1} if undefined, for example {@code 443}. */
private int port = -1;
/**
* Decoded path component by parts with each part separated by a {@code '/'} or {@code null} for
* none, for example {@code "/m8/feeds/contacts/default/full"} is represented by {@code "", "m8",
*"feeds", "contacts", "default", "full"}.
* <p>
* Use {@link #appendRawPath(String)} to append to the path, which ensures that no extra slash is
* added.
* </p>
*/
private List<String> pathParts;
/** Fragment component or {@code null} for none. */
private String fragment;
public GenericUrl() {
}
/**
* Constructs from an encoded URL.
*
* <p>
* Any known query parameters with pre-defined fields as data keys will be parsed based on their
* data type. Any unrecognized query parameter will always be parsed as a string.
* </p>
*
* <p>
* Any {@link MalformedURLException} is wrapped in an {@link IllegalArgumentException}.
* </p>
*
* <p>Upgrade warning: starting in version 1.18 this parses the encodedUrl using
* new URL(encodedUrl). In previous versions it used new URI(encodedUrl).
* In particular, this means that only a limited set of schemes are allowed such as "http" and
* "https", but that parsing is compliant with, at least, RFC 3986.</p>
*
* @param encodedUrl encoded URL, including any existing query parameters that should be parsed
* @throws IllegalArgumentException if URL has a syntax error
*/
public GenericUrl(String encodedUrl) {
this(parseURL(encodedUrl));
}
/**
* Constructs from a URI.
*
* @param uri URI
*
* @since 1.14
*/
public GenericUrl(URI uri) {
this(uri.getScheme(),
uri.getHost(),
uri.getPort(),
uri.getRawPath(),
uri.getRawFragment(),
uri.getRawQuery(),
uri.getRawUserInfo());
}
/**
* Constructs from a URL.
*
* @param url URL
*
* @since 1.14
*/
public GenericUrl(URL url) {
this(url.getProtocol(),
url.getHost(),
url.getPort(),
url.getPath(),
url.getRef(),
url.getQuery(),
url.getUserInfo());
}
private GenericUrl(String scheme,
String host,
int port,
String path,
String fragment,
String query,
String userInfo) {
this.scheme = scheme.toLowerCase();
this.host = host;
this.port = port;
this.pathParts = toPathParts(path);
this.fragment = fragment != null ? CharEscapers.decodeUri(fragment) : null;
if (query != null) {
UrlEncodedParser.parse(query, this);
}
this.userInfo = userInfo != null ? CharEscapers.decodeUri(userInfo) : null;
}
@Override
public int hashCode() {
// TODO(yanivi): optimize?
return build().hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj) || !(obj instanceof GenericUrl)) {
return false;
}
GenericUrl other = (GenericUrl) obj;
// TODO(yanivi): optimize?
return build().equals(other.toString());
}
@Override
public String toString() {
return build();
}
@Override
public GenericUrl clone() {
GenericUrl result = (GenericUrl) super.clone();
if (pathParts != null) {
result.pathParts = new ArrayList<String>(pathParts);
}
return result;
}
@Override
public GenericUrl set(String fieldName, Object value) {
return (GenericUrl) super.set(fieldName, value);
}
/**
* Returns the scheme (lowercase), for example {@code "https"}.
*
* @since 1.5
*/
public final String getScheme() {
return scheme;
}
/**
* Sets the scheme (lowercase), for example {@code "https"}.
*
* @since 1.5
*/
public final void setScheme(String scheme) {
this.scheme = Preconditions.checkNotNull(scheme);
}
/**
* Returns the host, for example {@code "www.google.com"}.
*
* @since 1.5
*/
public String getHost() {
return host;
}
/**
* Sets the host, for example {@code "www.google.com"}.
*
* @since 1.5
*/
public final void setHost(String host) {
this.host = Preconditions.checkNotNull(host);
}
/**
* Returns the user info or {@code null} for none, for example {@code "username:password"}.
*
* @since 1.15
*/
public final String getUserInfo() {
return userInfo;
}
/**
* Sets the user info or {@code null} for none, for example {@code "username:password"}.
*
* @since 1.15
*/
public final void setUserInfo(String userInfo) {
this.userInfo = userInfo;
}
/**
* Returns the port number or {@code -1} if undefined, for example {@code 443}.
*
* @since 1.5
*/
public int getPort() {
return port;
}
/**
* Sets the port number, for example {@code 443}.
*
* @since 1.5
*/
public final void setPort(int port) {
Preconditions.checkArgument(port >= -1, "expected port >= -1");
this.port = port;
}
/**
* Returns the decoded path component by parts with each part separated by a {@code '/'} or
* {@code null} for none.
*
* @since 1.5
*/
public List<String> getPathParts() {
return pathParts;
}
/**
* Sets the decoded path component by parts with each part separated by a {@code '/'} or
* {@code null} for none.
*
* <p>
* For example {@code "/m8/feeds/contacts/default/full"} is represented by {@code "", "m8",
*"feeds", "contacts", "default", "full"}.
* </p>
*
* <p>
* Use {@link #appendRawPath(String)} to append to the path, which ensures that no extra slash is
* added.
* </p>
*
* @since 1.5
*/
public void setPathParts(List<String> pathParts) {
this.pathParts = pathParts;
}
/**
* Returns the fragment component or {@code null} for none.
*
* @since 1.5
*/
public String getFragment() {
return fragment;
}
/**
* Sets the fragment component or {@code null} for none.
*
* @since 1.5
*/
public final void setFragment(String fragment) {
this.fragment = fragment;
}
/**
* Constructs the string representation of the URL, including the path specified by
* {@link #pathParts} and the query parameters specified by this generic URL.
*/
public final String build() {
return buildAuthority() + buildRelativeUrl();
}
/**
* Constructs the portion of the URL containing the scheme, host and port.
*
* <p>
* For the URL {@code "http://example.com/something?action=add"} this method would return
* {@code "http://example.com"}.
* </p>
*
* @return scheme://[user-info@]host[:port]
* @since 1.9
*/
public final String buildAuthority() {
// scheme, [user info], host, [port]
StringBuilder buf = new StringBuilder();
buf.append(Preconditions.checkNotNull(scheme));
buf.append("://");
if (userInfo != null) {
buf.append(CharEscapers.escapeUriUserInfo(userInfo)).append('@');
}
buf.append(Preconditions.checkNotNull(host));
int port = this.port;
if (port != -1) {
buf.append(':').append(port);
}
return buf.toString();
}
/**
* Constructs the portion of the URL beginning at the rooted path.
*
* <p>
* For the URL {@code "http://example.com/something?action=add"} this method would return
* {@code "/something?action=add"}.
* </p>
*
* @return path with with leading '/' if the path is non-empty, query parameters and fragment
* @since 1.9
*/
public final String buildRelativeUrl() {
StringBuilder buf = new StringBuilder();
if (pathParts != null) {
appendRawPathFromParts(buf);
}
addQueryParams(entrySet(), buf);
// URL fragment
String fragment = this.fragment;
if (fragment != null) {
buf.append('#').append(URI_FRAGMENT_ESCAPER.escape(fragment));
}
return buf.toString();
}
/**
* Constructs the URI based on the string representation of the URL from {@link #build()}.
*
* <p>
* Any {@link URISyntaxException} is wrapped in an {@link IllegalArgumentException}.
* </p>
*
* @return new URI instance
*
* @since 1.14
*/
public final URI toURI() {
return toURI(build());
}
/**
* Constructs the URL based on the string representation of the URL from {@link #build()}.
*
* <p>
* Any {@link MalformedURLException} is wrapped in an {@link IllegalArgumentException}.
* </p>
*
* @return new URL instance
*
* @since 1.14
*/
public final URL toURL() {
return parseURL(build());
}
/**
* Constructs the URL based on {@link URL#URL(URL, String)} with this URL representation from
* {@link #toURL()} and a relative url.
*
* <p>
* Any {@link MalformedURLException} is wrapped in an {@link IllegalArgumentException}.
* </p>
*
* @return new URL instance
*
* @since 1.14
*/
public final URL toURL(String relativeUrl) {
try {
URL url = toURL();
return new URL(url, relativeUrl);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
}
/**
* Returns the first query parameter value for the given query parameter name.
*
* @param name query parameter name
* @return first query parameter value
*/
public Object getFirst(String name) {
Object value = get(name);
if (value instanceof Collection<?>) {
@SuppressWarnings("unchecked")
Collection<Object> collectionValue = (Collection<Object>) value;
Iterator<Object> iterator = collectionValue.iterator();
return iterator.hasNext() ? iterator.next() : null;
}
return value;
}
/**
* Returns all query parameter values for the given query parameter name.
*
* @param name query parameter name
* @return unmodifiable collection of query parameter values (possibly empty)
*/
public Collection<Object> getAll(String name) {
Object value = get(name);
if (value == null) {
return Collections.emptySet();
}
if (value instanceof Collection<?>) {
@SuppressWarnings("unchecked")
Collection<Object> collectionValue = (Collection<Object>) value;
return Collections.unmodifiableCollection(collectionValue);
}
return Collections.singleton(value);
}
/**
* Returns the raw encoded path computed from the {@link #pathParts}.
*
* @return raw encoded path computed from the {@link #pathParts} or {@code null} if
* {@link #pathParts} is {@code null}
*/
public String getRawPath() {
List<String> pathParts = this.pathParts;
if (pathParts == null) {
return null;
}
StringBuilder buf = new StringBuilder();
appendRawPathFromParts(buf);
return buf.toString();
}
/**
* Sets the {@link #pathParts} from the given raw encoded path.
*
* @param encodedPath raw encoded path or {@code null} to set {@link #pathParts} to {@code null}
*/
public void setRawPath(String encodedPath) {
pathParts = toPathParts(encodedPath);
}
/**
* Appends the given raw encoded path to the current {@link #pathParts}, setting field only if it
* is {@code null} or empty.
* <p>
* The last part of the {@link #pathParts} is merged with the first part of the path parts
* computed from the given encoded path. Thus, if the current raw encoded path is {@code "a"}, and
* the given encoded path is {@code "b"}, then the resulting raw encoded path is {@code "ab"}.
* </p>
*
* @param encodedPath raw encoded path or {@code null} to ignore
*/
public void appendRawPath(String encodedPath) {
if (encodedPath != null && encodedPath.length() != 0) {
List<String> appendedPathParts = toPathParts(encodedPath);
if (pathParts == null || pathParts.isEmpty()) {
this.pathParts = appendedPathParts;
} else {
int size = pathParts.size();
pathParts.set(size - 1, pathParts.get(size - 1) + appendedPathParts.get(0));
pathParts.addAll(appendedPathParts.subList(1, appendedPathParts.size()));
}
}
}
/**
* Returns the decoded path parts for the given encoded path.
*
* @param encodedPath slash-prefixed encoded path, for example
* {@code "/m8/feeds/contacts/default/full"}
* @return decoded path parts, with each part assumed to be preceded by a {@code '/'}, for example
* {@code "", "m8", "feeds", "contacts", "default", "full"}, or {@code null} for
* {@code null} or {@code ""} input
*/
public static List<String> toPathParts(String encodedPath) {
if (encodedPath == null || encodedPath.length() == 0) {
return null;
}
List<String> result = new ArrayList<String>();
int cur = 0;
boolean notDone = true;
while (notDone) {
int slash = encodedPath.indexOf('/', cur);
notDone = slash != -1;
String sub;
if (notDone) {
sub = encodedPath.substring(cur, slash);
} else {
sub = encodedPath.substring(cur);
}
result.add(CharEscapers.decodeUri(sub));
cur = slash + 1;
}
return result;
}
private void appendRawPathFromParts(StringBuilder buf) {
int size = pathParts.size();
for (int i = 0; i < size; i++) {
String pathPart = pathParts.get(i);
if (i != 0) {
buf.append('/');
}
if (pathPart.length() != 0) {
buf.append(CharEscapers.escapeUriPath(pathPart));
}
}
}
/**
* Adds query parameters from the provided entrySet into the buffer.
*/
static void addQueryParams(Set<Entry<String, Object>> entrySet, StringBuilder buf) {
// (similar to UrlEncodedContent)
boolean first = true;
for (Map.Entry<String, Object> nameValueEntry : entrySet) {
Object value = nameValueEntry.getValue();
if (value != null) {
String name = CharEscapers.escapeUriQuery(nameValueEntry.getKey());
if (value instanceof Collection<?>) {
Collection<?> collectionValue = (Collection<?>) value;
for (Object repeatedValue : collectionValue) {
first = appendParam(first, buf, name, repeatedValue);
}
} else {
first = appendParam(first, buf, name, value);
}
}
}
}
private static boolean appendParam(boolean first, StringBuilder buf, String name, Object value) {
if (first) {
first = false;
buf.append('?');
} else {
buf.append('&');
}
buf.append(name);
String stringValue = CharEscapers.escapeUriQuery(value.toString());
if (stringValue.length() != 0) {
buf.append('=').append(stringValue);
}
return first;
}
/**
* Returns the URI for the given encoded URL.
*
* <p>
* Any {@link URISyntaxException} is wrapped in an {@link IllegalArgumentException}.
* </p>
*
* @param encodedUrl encoded URL
* @return URI
*/
private static URI toURI(String encodedUrl) {
try {
return new URI(encodedUrl);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
}
/**
* Returns the URI for the given encoded URL.
*
* <p>
* Any {@link MalformedURLException} is wrapped in an {@link IllegalArgumentException}.
* </p>
*
* @param encodedUrl encoded URL
* @return URL
*/
private static URL parseURL(String encodedUrl) {
try {
return new URL(encodedUrl);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
}
}