-
Notifications
You must be signed in to change notification settings - Fork 4
/
Uri.java
1990 lines (1823 loc) · 73.4 KB
/
Uri.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
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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.river.api.net;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import org.apache.river.impl.Messages;
/**
* This class represents an immutable instance of a URI as defined by RFC 3986.
* <p>
* This class replaces java.net.URI functionality.
* <p>
* Unlike java.net.URI this class is not Serializable and hashCode and
* equality is governed by strict RFC3986 normalisation. In addition "other"
* characters allowed in java.net.URI as specified by javadoc, not specifically
* allowed by RFC3986 are illegal and must be escaped. This strict adherence
* is essential to eliminate false negative or positive matches.
* <p>
* In addition to RFC3896 normalisation, on OS platforms with a \ file separator
* the path is converted to UPPER CASE for comparison for file: schema, during
* equals and hashCode calls.
* <p>
* IPv6 and IPvFuture host addresses must be enclosed in square brackets as per
* RFC3986. A zone delimiter %, if present, must be represented in escaped %25
* form as per RFC6874.
* <p>
* In addition to RFC3896 normalization, IPv6 host addresses will be normalized
* to comply with RFC 5952 A Recommendation for IPv6 Address Text Representation.
* This is to ensure consistent equality between identical IPv6 addresses.
*
* @since 3.0.0
*/
public final class Uri implements Comparable<Uri> {
/* Class Implementation */
/* Legacy java.net.URI RFC 2396 syntax*/
static final String unreserved = "_-!.~\'()*"; //$NON-NLS-1$
static final String punct = ",;:$&+="; //$NON-NLS-1$
static final String reserved = punct + "?/[]@"; //$NON-NLS-1$
// String someLegal = unreserved + punct;
// String queryLegal = unreserved + reserved + "\\\""; //$NON-NLS-1$
// String allLegal = unreserved + reserved;
static final String someLegal = unreserved + punct;
static final String queryLegal = unreserved + reserved + "\\\""; //$NON-NLS-1$
// static final String allLegal = unreserved + reserved;
/* RFC 3986 */
// private static final char [] latin = new char[256];
// private static final String [] latinEsc = new String[256];
/* 2.1. Percent-Encoding
*
* A percent-encoding mechanism is used to represent a data octet in a
* component when that octet's corresponding character is outside the
* allowed set or is being used as a delimiter of, or within, the
* component. A percent-encoded octet is encoded as a character
* triplet, consisting of the percent character "%" followed by the two
* hexadecimal digits representing that octet's numeric value. For
* example, "%20" is the percent-encoding for the binary octet
* "00100000" (ABNF: %x20), which in US-ASCII corresponds to the space
* character (SP). Section 2.4 describes when percent-encoding and
* decoding is applied.
*
* pct-encoded = "%" HEXDIG HEXDIG
*
* The uppercase hexadecimal digits 'A' through 'F' are equivalent to
* the lowercase digits 'a' through 'f', respectively. If two URIs
* differ only in the case of hexadecimal digits used in percent-encoded
* octets, they are equivalent. For consistency, URI producers and
* normalizers should use uppercase hexadecimal digits for all percent-
* encodings.
*/
// Any character that is not part of the reserved and unreserved sets must
// be encoded.
// Section 2.1 Percent encoding must be converted to upper case during normalisation.
private static final char escape = '%';
/* RFC3986 obsoletes RFC2396 and RFC2732
*
* reserved = gen-delims / sub-delims
*
* gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
*
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
// Section 2.2 Reserved set is protected from normalisation.
// private static final char [] gen_delims = {':', '/', '?', '#', '[', ']', '@'};
// private static final char [] sub_delims = {'!', '$', '&', '\'', '(', ')', '*',
// '+', ',', ';', '='};
/*
* For consistency, percent-encoded octets in the ranges of ALPHA
* (%41-%5A and %61-%7A), DIGIT (%30-%39), hyphen (%2D), period (%2E),
* underscore (%5F), or tilde (%7E) should not be created by URI
* producers and, when found in a URI, should be decoded to their
* corresponding unreserved characters by URI normalizers.
*/
// Section 2.3 Unreserved characters (Allowed) must be decoded during normalisation if % encoded.
// private static final char [] lowalpha = "abcdefghijklmnopqrstuvwxyz".toCharArray();
// private static final char [] upalpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
// private static final char [] numeric = "0123456789".toCharArray();
// private static final char [] unres_punct = {'-' , '.' , '_' , '~'};
// Section 3.1 Scheme
// private static final char [] schemeEx = "+-.".toCharArray(); // + ALPHA and numeric.
// To be unescaped during normalisation, unmodifiable and safely published.
// final static Map<String, Character> unReserved;
// final static Map<String, Character> schemeUnreserved;
/* Explicit legal String fields follow, ALPHA and DIGIT are implicitly legal */
/* All characters that are legal URI syntax */
static final String allLegalUnescaped = ":/?#[]@!$&'()*+,;=-._~";
static final String allLegal = "%:/?#[]@!$&'()*+,;=-._~";
/*
* Syntax Summary
*
* URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
*
* hier-part = "//" authority path-abempty
* / path-absolute
* / path-rootless
* / path-empty
*
* scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
*/
static final String schemeLegal = "+-.";
/*
* authority = [ userinfo "@" ] host [ ":" port ]
* userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
*/
static final String userinfoLegal = "-._~!$&'()*+,;=:";
static final String authorityLegal = userinfoLegal + "@[]";
/* host = IP-literal / IPv4address / reg-name
* IP-literal = "[" ( IPv6address / IPvFuture ) "]"
* IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )
*/
static final String iPvFuture = "-._~!$&'()*+,;=:";
/* IPv6address = 6( h16 ":" ) ls32
* / "::" 5( h16 ":" ) ls32
* / [ h16 ] "::" 4( h16 ":" ) ls32
* / [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32
* / [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32
* / [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32
* / [ *4( h16 ":" ) h16 ] "::" ls32
* / [ *5( h16 ":" ) h16 ] "::" h16
* / [ *6( h16 ":" ) h16 ] "::"
*
* ls32 = ( h16 ":" h16 ) / IPv4address
* ; least-significant 32 bits of address
*
* h16 = 1*4HEXDIG
* ; 16 bits of address represented in hexadecimal
*
* IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet
*
* dec-octet = DIGIT ; 0-9
* / %x31-39 DIGIT ; 10-99
* / "1" 2DIGIT ; 100-199
* / "2" %x30-34 DIGIT ; 200-249
* / "25" %x30-35 ; 250-255
* reg-name = *( unreserved / pct-encoded / sub-delims )
*/
static final String hostRegNameLegal = "-._~!$&'()*+,;=";
/* port = *DIGIT
*
* path = path-abempty ; begins with "/" or is empty
* / path-absolute ; begins with "/" but not "//"
* / path-noscheme ; begins with a non-colon segment
* / path-rootless ; begins with a segment
* / path-empty ; zero characters
*
* path-abempty = *( "/" segment )
* path-absolute = "/" [ segment-nz *( "/" segment ) ]
* path-noscheme = segment-nz-nc *( "/" segment )
* path-rootless = segment-nz *( "/" segment )
* path-empty = 0<pchar>
*
* segment = *pchar
* segment-nz = 1*pchar
* segment-nz-nc = 1*( unreserved / pct-encoded / sub-delims / "@" ) ; non-zero-length segment without any colon ":"
*
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
*/
static final String pcharLegal = "-._~!$&'()*+,;=:@";
static final String segmentNzNcLegal = "-._~!$&'()*+,;=@";
static final String segmentLegal = pcharLegal;
static final String pathLegal = segmentLegal + "/";
/* query = *( pchar / "/" / "?" )
*
* fragment = *( pchar / "/" / "?" )
*/
static final String queryFragLegal = pcharLegal + "/?";
private final static char a = 'a';
private final static char z = 'z';
private final static char A = 'A';
private final static char Z = 'Z';
private final static char upperCaseBitwiseMask = 0xdf;
private final static char lowerCaseBitwiseMask = 0x20;
static String toAsciiUpperCase(String s){
return new String(toAsciiUpperCase(s.toCharArray()));
}
static char [] toAsciiUpperCase(char [] array){
int length = array.length;
for (int i = 0; i < length ; i++){
if (array[i] >= a && array[i] <= z) {
array[i] = toAsciiUpperCase(array[i]);
}
}
return array;
}
static char toAsciiUpperCase(char c){
return (char) (c & upperCaseBitwiseMask);
}
static String toAsciiLowerCase(String s){
return new String(toAsciiLowerCase(s.toCharArray()));
}
static char[] toAsciiLowerCase(char [] array){
int length = array.length;
for (int i = 0; i < length ; i++){
if (array[i] >= A && array[i] <= Z) {
array[i] = toAsciiLowerCase(array[i]);
}
}
return array;
}
static char toAsciiLowerCase(char c){
return (char) (c | lowerCaseBitwiseMask);
}
static boolean charArraysEqual( char [] a , char [] b){
int alen = a.length;
int blen = b.length;
if (alen != blen) return false;
for (int i = 0; i < alen; i++){
if (a[i] != b[i]) return false;
}
return true;
}
static boolean asciiStringsUpperCaseEqual(String a, String b){
char [] ac = a.toCharArray();
toAsciiUpperCase(ac);
char [] bc = b.toCharArray();
toAsciiUpperCase(bc);
return charArraysEqual(ac, bc);
}
static boolean asciiStringsLowerCaseEqual(String a, String b){
char [] ac = a.toCharArray();
toAsciiLowerCase(ac);
char [] bc = b.toCharArray();
toAsciiLowerCase(bc);
return charArraysEqual(ac, bc);
}
/** Fixes windows file URI string by converting back slashes to forward
* slashes and inserting a forward slash before the drive letter if it is
* missing. No normalisation or modification of case is performed.
* @param uri String representation of URI
* @return fixed URI String
*/
public static String fixWindowsURI(String uri) {
if (uri == null) return null;
if (File.separatorChar != '\\') return uri;
if ( uri.startsWith("file:") || uri.startsWith("FILE:")){
char [] u = uri.toCharArray();
int l = u.length;
StringBuilder sb = new StringBuilder(uri.length()+1);
for (int i=0; i<l; i++){
// Ensure we use forward slashes
if (u[i] == File.separatorChar) {
sb.append('/');
continue;
}
if (i == 5 && uri.startsWith(":", 6 )) {
// Windows drive letter without leading slashes doesn't comply
// with URI spec, fix it here
sb.append("/");
}
sb.append(u[i]);
}
return sb.toString();
}
return uri;
}
public static URI uriToURI(Uri uri){
return URI.create(uri.toString());
}
public static Uri urlToUri(URL url) throws URISyntaxException{
return Uri.parseAndCreate(fixWindowsURI(url.toString()));
}
public static File uriToFile(Uri uri){
return new File(uriToURI(uri));
}
public static Uri fileToUri(File file) throws URISyntaxException{
String path = file.getAbsolutePath();
if (File.separatorChar == '\\') {
path = path.replace(File.separatorChar, '/');
}
path = fixWindowsURI("file:" + path);
return Uri.escapeAndCreate(path); //$NON-NLS-1$
}
public static Uri filePathToUri(String path) throws URISyntaxException{
String forwardSlash = "/";
if (path == null || path.length() == 0) {
// codebase is "file:"
path = "*";
}
// Ensure compatibility with URLClassLoader, when directory
// character is dropped by File.
boolean directory = false;
if (path.endsWith(forwardSlash)) directory = true;
path = new File(path).getAbsolutePath();
if (directory) {
if (!(path.endsWith(File.separator))){
path = path + File.separator;
}
}
if (File.separatorChar == '\\') {
path = path.replace(File.separatorChar, '/');
}
path = fixWindowsURI("file:" + path);
return Uri.escapeAndCreate(path); //$NON-NLS-1$
}
/* Begin Object Implementation */
private final String string;
private final String scheme;
private final String schemespecificpart;
private final String authority;
private final String userinfo;
private final String host;
private final int port;
private final String path;
private final String query;
private final String fragment;
private final boolean opaque;
private final boolean absolute;
private final boolean serverAuthority;
private final String hashString;
private final int hash;
private final boolean fileSchemeCaseInsensitiveOS;
/**
*
* @param string
* @param scheme
* @param schemespecificpart
* @param authority
* @param userinfo
* @param host
* @param port
* @param path
* @param query
* @param fragment
* @param opaque
* @param absolute
* @param serverAuthority
* @param hash
*/
private Uri(String string,
String scheme,
String schemespecificpart,
String authority,
String userinfo,
String host,
int port,
String path,
String query,
String fragment,
boolean opaque,
boolean absolute,
boolean serverAuthority,
int hash,
boolean fileSchemeCaseInsensitiveOS)
{
super();
this.scheme = scheme;
this.schemespecificpart = schemespecificpart;
this.authority = authority;
this.userinfo = userinfo;
this.host = host;
this.port = port;
this.path = path;
this.query = query;
this.fragment = fragment;
this.opaque = opaque;
this.absolute = absolute;
this.serverAuthority = serverAuthority;
if (string == null) {
StringBuilder result = new StringBuilder();
if (scheme != null) {
result.append(scheme);
result.append(':');
}
if (opaque) {
result.append(schemespecificpart);
} else {
if (authority != null) {
result.append("//"); //$NON-NLS-1$
result.append(authority);
}
if (path != null) {
result.append(path);
}
if (query != null) {
result.append('?');
result.append(query);
}
}
if (fragment != null) {
result.append('#');
result.append(fragment);
}
this.string = result.toString();
} else {
this.string = string;
}
this.hashString = getHashString();
this.hash = hash == -1 ? hashString.hashCode(): hash;
this.fileSchemeCaseInsensitiveOS = fileSchemeCaseInsensitiveOS;
}
/**
* Private constructor that doesn't throw URISyntaxException, all public
* constructors are designed to avoid finalizer attacks by calling static
* methods that throw URISyntaxException, just in case we
* decide to make this class non final at some point in future.
* @param p
*/
private Uri(UriParser p){
this(p.string,
p.scheme,
p.schemespecificpart,
p.authority,
p.userinfo,
p.host,
p.port,
p.path,
p.query,
p.fragment,
p.opaque,
p.absolute,
p.serverAuthority,
p.hash,
p.fileSchemeCaseInsensitiveOS);
}
/**
* Creates a new URI instance according to the given string {@code uri}.
*
* The URI must strictly conform to RFC3986, it doesn't support extended
* characters sets like java.net.URI, instead all non ASCII characters
* must be escaped.
*
* Any encoded unreserved characters are decoded.
*
* @param uri
* the textual URI representation to be parsed into a URI object.
* @throws URISyntaxException
* if the given string {@code uri} doesn't fit to the
* specification RF3986 or could not be parsed correctly.
*/
public Uri(String uri) throws URISyntaxException {
this(constructor1(uri));
}
private static UriParser constructor1(String uri) throws URISyntaxException {
uri = URIEncoderDecoder.decodeUnreserved(uri);
UriParser p = new UriParser();
p.parseURI(uri, false);
return p;
}
/**
* Creates a new URI instance using the given arguments. This constructor
* first creates a temporary URI string from the given components. This
* string will be parsed later on to create the URI instance.
* <p>
* {@code [scheme:]scheme-specific-part[#fragment]}
*
* @param scheme
* the scheme part of the URI.
* @param ssp
* the scheme-specific-part of the URI.
* @param frag
* the fragment part of the URI.
* @throws URISyntaxException
* if the temporary created string doesn't fit to the
* specification RFC2396 or could not be parsed correctly.
*/
public Uri(String scheme, String ssp, String frag) throws URISyntaxException {
this(constructor2(scheme, ssp, frag));
}
private static UriParser constructor2(String scheme, String ssp, String frag) throws URISyntaxException{
StringBuilder uri = new StringBuilder();
if (scheme != null) {
uri.append(scheme);
uri.append(':');
}
if (ssp != null) {
// QUOTE ILLEGAL CHARACTERS
uri.append(quoteComponent(ssp, allLegalUnescaped));
}
if (frag != null) {
uri.append('#');
// QUOTE ILLEGAL CHARACTERS
uri.append(quoteComponent(frag, Uri.queryFragLegal));
}
UriParser p = new UriParser();
p.parseURI(uri.toString(), false);
return p;
}
/**
* Creates a new URI instance using the given arguments. This constructor
* first creates a temporary URI string from the given components. This
* string will be parsed later on to create the URI instance.
* <p>
* {@code [scheme:][user-info@]host[:port][path][?query][#fragment]}
*
* @param scheme
* the scheme part of the URI.
* @param userinfo
* the user information of the URI for authentication and
* authorization.
* @param host
* the host name of the URI.
* @param port
* the port number of the URI.
* @param path
* the path to the resource on the host.
* @param query
* the query part of the URI to specify parameters for the
* resource.
* @param fragment
* the fragment part of the URI.
* @throws URISyntaxException
* if the temporary created string doesn't fit to the
* specification RFC2396 or could not be parsed correctly.
*/
public Uri(String scheme, String userinfo, String host, int port,
String path, String query, String fragment)
throws URISyntaxException {
this(constructor3(scheme, userinfo, host, port, path, query, fragment));
}
private static UriParser constructor3(String scheme, String userinfo, String host, int port,
String path, String query, String fragment) throws URISyntaxException {
if (scheme == null && userinfo == null && host == null && path == null
&& query == null && fragment == null) {
UriParser p = new UriParser();
p.path = ""; //$NON-NLS-1$
return p;
}
if (scheme != null && path != null && path.length() > 0
&& path.charAt(0) != '/') {
throw new URISyntaxException(path, Messages.getString("luni.82")); //$NON-NLS-1$
}
StringBuilder uri = new StringBuilder();
if (scheme != null) {
uri.append(scheme);
uri.append(':');
}
if (userinfo != null || host != null || port != -1) {
uri.append("//"); //$NON-NLS-1$
}
if (userinfo != null) {
// QUOTE ILLEGAL CHARACTERS in userinfo
uri.append(quoteComponent(userinfo, Uri.userinfoLegal));
uri.append('@');
}
if (host != null) {
// check for ipv6 addresses that hasn't been enclosed
// in square brackets
if (host.indexOf(':') != -1 && host.indexOf(']') == -1
&& host.indexOf('[') == -1) {
host = "[" + host + "]"; //$NON-NLS-1$ //$NON-NLS-2$
}
uri.append(host);
}
if (port != -1) {
uri.append(':');
uri.append(port);
}
if (path != null) {
// QUOTE ILLEGAL CHARS
uri.append(quoteComponent(path, "/@" + Uri.pathLegal)); //$NON-NLS-1$
}
if (query != null) {
uri.append('?');
// QUOTE ILLEGAL CHARS
uri.append(quoteComponent(query, Uri.queryFragLegal));
}
if (fragment != null) {
// QUOTE ILLEGAL CHARS
uri.append('#');
uri.append(quoteComponent(fragment, Uri.queryFragLegal));
}
UriParser p = new UriParser();
p.parseURI(uri.toString(), true);
return p;
}
/**
* Creates a new URI instance using the given arguments. This constructor
* first creates a temporary URI string from the given components. This
* string will be parsed later on to create the URI instance.
* <p>
* {@code [scheme:]host[path][#fragment]}
*
* @param scheme
* the scheme part of the URI.
* @param host
* the host name of the URI.
* @param path
* the path to the resource on the host.
* @param fragment
* the fragment part of the URI.
* @throws URISyntaxException
* if the temporary created string doesn't fit to the
* specification RFC2396 or could not be parsed correctly.
*/
public Uri(String scheme, String host, String path, String fragment)
throws URISyntaxException {
this(scheme, null, host, -1, path, null, fragment);
}
/**
* Creates a new URI instance using the given arguments. This constructor
* first creates a temporary URI string from the given components. This
* string will be parsed later on to create the URI instance.
* <p>
* {@code [scheme:][//authority][path][?query][#fragment]}
*
* @param scheme
* the scheme part of the URI.
* @param authority
* the authority part of the URI.
* @param path
* the path to the resource on the host.
* @param query
* the query part of the URI to specify parameters for the
* resource.
* @param fragment
* the fragment part of the URI.
* @throws URISyntaxException
* if the temporary created string doesn't fit to the
* specification RFC2396 or could not be parsed correctly.
*/
public Uri(String scheme, String authority, String path, String query,
String fragment) throws URISyntaxException {
this(constructor4(scheme, authority, path, query, fragment));
}
private static UriParser constructor4(String scheme, String authority, String path, String query,
String fragment) throws URISyntaxException {
if (scheme != null && path != null && path.length() > 0
&& path.charAt(0) != '/') {
throw new URISyntaxException(path, Messages.getString("luni.82")); //$NON-NLS-1$
}
StringBuilder uri = new StringBuilder();
if (scheme != null) {
uri.append(scheme);
uri.append(':');
}
if (authority != null) {
uri.append("//"); //$NON-NLS-1$
// QUOTE ILLEGAL CHARS
uri.append(quoteComponent(authority, "@[]" + Uri.authorityLegal)); //$NON-NLS-1$
}
if (path != null) {
// QUOTE ILLEGAL CHARS
uri.append(quoteComponent(path, "/@" + Uri.pathLegal)); //$NON-NLS-1$
}
if (query != null) {
// QUOTE ILLEGAL CHARS
uri.append('?');
uri.append(quoteComponent(query, Uri.queryFragLegal));
}
if (fragment != null) {
// QUOTE ILLEGAL CHARS
uri.append('#');
uri.append(quoteComponent(fragment, Uri.queryFragLegal));
}
UriParser p = new UriParser();
p.parseURI(uri.toString(), false);
return p;
}
/*
* Quote illegal chars for each component, but not the others
*
* @param component java.lang.String the component to be converted @param
* legalset java.lang.String the legal character set allowed in the
* component s @return java.lang.String the converted string
*/
private static String quoteComponent(String component, String legalset) {
try {
/*
* Use a different encoder than URLEncoder since: 1. chars like "/",
* "#", "@" etc needs to be preserved instead of being encoded, 2.
* UTF-8 char set needs to be used for encoding instead of default
* platform one
*/
return URIEncoderDecoder.quoteIllegal(component, legalset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.toString());
}
}
/**
* Compares this URI with the given argument {@code uri}. This method will
* return a negative value if this URI instance is less than the given
* argument and a positive value if this URI instance is greater than the
* given argument. The return value {@code 0} indicates that the two
* instances represent the same URI. To define the order the single parts of
* the URI are compared with each other. String components will be orderer
* in the natural case-sensitive way. A hierarchical URI is less than an
* opaque URI and if one part is {@code null} the URI with the undefined
* part is less than the other one.
*
* @param uri
* the URI this instance has to compare with.
* @return the value representing the order of the two instances.
*/
@Override
public int compareTo(Uri uri) {
int ret;
// compare schemes
if (scheme == null && uri.scheme != null) {
return -1;
} else if (scheme != null && uri.scheme == null) {
return 1;
} else if (scheme != null && uri.scheme != null) {
ret = scheme.compareToIgnoreCase(uri.scheme);
if (ret != 0) return ret;
}
// compare opacities
if (!opaque && uri.opaque) {
return -1;
} else if (opaque && !uri.opaque) {
return 1;
} else if (opaque && uri.opaque) {
ret = schemespecificpart.compareTo(uri.schemespecificpart);
if (ret != 0) {
return ret;
}
} else {
// otherwise both must be hierarchical
// compare authorities
if (authority != null && uri.authority == null) {
return 1;
} else if (authority == null && uri.authority != null) {
return -1;
} else if (authority != null && uri.authority != null) {
if (host != null && uri.host != null) {
// both are server based, so compare userinfo, host, port
if (userinfo != null && uri.userinfo == null) {
return 1;
} else if (userinfo == null && uri.userinfo != null) {
return -1;
} else if (userinfo != null && uri.userinfo != null) {
ret = userinfo.compareTo(uri.userinfo);
if (ret != 0) {
return ret;
}
}
// userinfo's are the same, compare hostname
ret = host.compareToIgnoreCase(uri.host);
if (ret != 0) {
return ret;
}
// compare port
if (port != uri.port) {
return port - uri.port;
}
} else { // one or both are registry based, compare the whole
// authority
ret = authority.compareTo(uri.authority);
if (ret != 0) {
return ret;
}
}
}
// authorities are the same
// compare paths
if (fileSchemeCaseInsensitiveOS){
ret = toAsciiUpperCase(path).compareTo(toAsciiUpperCase(uri.path));
// ret = path.toUpperCase(Locale.ENGLISH).compareTo(uri.path.toUpperCase(Locale.ENGLISH));
} else {
ret = path.compareTo(uri.path);
}
if (ret != 0) {
return ret;
}
// compare queries
if (query != null && uri.query == null) {
return 1;
} else if (query == null && uri.query != null) {
return -1;
} else if (query != null && uri.query != null) {
ret = query.compareTo(uri.query);
if (ret != 0) {
return ret;
}
}
}
// everything else is identical, so compare fragments
if (fragment != null && uri.fragment == null) {
return 1;
} else if (fragment == null && uri.fragment != null) {
return -1;
} else if (fragment != null && uri.fragment != null) {
ret = fragment.compareTo(uri.fragment);
if (ret != 0) {
return ret;
}
}
// identical
return 0;
}
/**
* Parses the given argument {@code rfc3986compliantURI} and creates an appropriate URI
* instance.
*
* The parameter string is checked for compliance, an IllegalArgumentException
* is thrown if the string is non compliant.
*
* @param rfc3986compliantURI
* the string which has to be parsed to create the URI instance.
* @return the created instance representing the given URI.
*/
public static Uri create(String rfc3986compliantURI) {
Uri result = null;
try {
result = new Uri(rfc3986compliantURI);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e.getMessage());
}
return result;
}
/**
* The parameter string doesn't contain any existing escape sequences, any
* escape character % found is encoded as %25. Illegal characters are
* escaped if possible.
*
* The Uri is normalised according to RFC3986.
*
* @param unescapedString URI in un-escaped string form
* @return an RFC3986 compliant Uri.
* @throws java.net.URISyntaxException if string cannot be escaped.
*/
public static Uri escapeAndCreate(String unescapedString) throws URISyntaxException{
return new Uri(quoteComponent(unescapedString, allLegalUnescaped));
}
/**
* The parameter string may already contain escaped sequences, any illegal
* characters are escaped and any that shouldn't be escaped are un-escaped.
*
* The escape character % is not re-encoded.
* @param nonCompliantEscapedString URI in string from.
* @return an RFC3986 compliant Uri.
* @throws java.net.URISyntaxException if string cannot be escaped.
*/
public static Uri parseAndCreate(String nonCompliantEscapedString) throws URISyntaxException{
return new Uri(quoteComponent(nonCompliantEscapedString, allLegal));
}
/*
* Takes a string that may contain hex sequences like %F1 or %2b and
* converts the hex values following the '%' to uppercase
*/
private String convertHexToUpperCase(String s) {
StringBuilder result = new StringBuilder(""); //$NON-NLS-1$
if (s.indexOf('%') == -1) {
return s;
}
int index, previndex = 0;
while ((index = s.indexOf('%', previndex)) != -1) {
result.append(s.substring(previndex, index + 1));
// Convert to upper case ascii
result.append(toAsciiUpperCase(s.substring(index + 1, index + 3).toCharArray()));
index += 3;
previndex = index;
}
return result.toString();
}
/*
* Takes two strings that may contain hex sequences like %F1 or %2b and
* compares them, ignoring case for the hex values. Hex values must always
* occur in pairs as above
*/
private boolean equalsHexCaseInsensitive(String first, String second) {
//Hex will always be upper case.
if (first != null) return first.equals(second);
return second == null;
}
/**
* Compares this URI instance with the given argument {@code o} and
* determines if both are equal. Two URI instances are equal if all single
* parts are identical in their meaning.
*
* @param o
* the URI this instance has to be compared with.
* @return {@code true} if both URI instances point to the same resource,
* {@code false} otherwise.
*/
@Override
public boolean equals(Object o) {
if (!(o instanceof Uri)) {
return false;
}
if (hash != o.hashCode()) return false;
Uri uri = (Uri) o;
if (uri.fragment == null && fragment != null || uri.fragment != null
&& fragment == null) {
return false;
} else if (uri.fragment != null && fragment != null) {
if (!equalsHexCaseInsensitive(uri.fragment, fragment)) {
return false;
}