-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathURI.java
More file actions
1489 lines (1283 loc) · 40.2 KB
/
URI.java
File metadata and controls
1489 lines (1283 loc) · 40.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
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
/*
* @(#)URI.java 0.3-3 06/05/2001
*
* This file is part of the HTTPClient package
* Copyright (C) 1996-2001 Ronald Tschal�r
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307, USA
*
* For questions, suggestions, bug-reports, enhancement-requests etc.
* I may be contacted at:
*
* ronald@innovation.ch
*
* The HTTPClient's home page is located at:
*
* http://www.innovation.ch/java/HTTPClient/
*
*/
package HTTPClient;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.BitSet;
import java.util.Hashtable;
/**
* This class represents a generic URI, as defined in RFC-2396.
* This is similar to java.net.URL, with the following enhancements:
* <UL>
* <LI>it doesn't require a URLStreamhandler to exist for the scheme; this
* allows this class to be used to hold any URI, construct absolute
* URIs from relative ones, etc.
* <LI>it handles escapes correctly
* <LI>equals() works correctly
* <LI>relative URIs are correctly constructed
* <LI>it has methods for accessing various fields such as userinfo,
* fragment, params, etc.
* <LI>it handles less common forms of resources such as the "*" used in
* http URLs.
* </UL>
*
* <P>The elements are always stored in escaped form.
*
* <P>While RFC-2396 distinguishes between just two forms of URI's, those that
* follow the generic syntax and those that don't, this class knows about a
* third form, named semi-generic, used by quite a few popular schemes.
* Semi-generic syntax treats the path part as opaque, i.e. has the form
* <scheme>://<authority>/<opaque> . Relative URI's of this
* type are only resolved as far as absolute paths - relative paths do not
* exist.
*
* <P>Ideally, java.net.URL should subclass URI.
*
* @see <A HREF="http://www.ics.uci.edu/pub/ietf/uri/rfc2396.txt">rfc-2396</A>
* @version 0.3-3 06/05/2001
* @author Ronald Tschal�r
* @since V0.3-1
*/
public class URI
{
/**
* If true, then the parser will resolve certain URI's in backwards
* compatible (but technically incorrect) manner. Example:
*
*<PRE>
* base = http://a/b/c/d;p?q
* rel = http:g
* result = http:g (correct)
* result = http://a/b/c/g (backwards compatible)
*</PRE>
*
* See rfc-2396, section 5.2, step 3, second paragraph.
*/
public static final boolean ENABLE_BACKWARDS_COMPATIBILITY = true;
protected static final Hashtable<String, Integer> defaultPorts = new Hashtable<>();
protected static final Hashtable<String, Boolean> usesGenericSyntax = new Hashtable<>();
protected static final Hashtable<String, Boolean> usesSemiGenericSyntax = new Hashtable<>();
/* various character classes as defined in the draft */
protected static final BitSet alphanumChar;
protected static final BitSet markChar;
protected static final BitSet reservedChar;
protected static final BitSet unreservedChar;
protected static final BitSet uricChar;
protected static final BitSet pcharChar;
protected static final BitSet userinfoChar;
protected static final BitSet schemeChar;
protected static final BitSet hostChar;
protected static final BitSet opaqueChar;
protected static final BitSet reg_nameChar;
/* These are not directly in the spec, but used for escaping and
* unescaping parts
*/
/** list of characters which must not be unescaped when unescaping a scheme */
public static final BitSet resvdSchemeChar;
/** list of characters which must not be unescaped when unescaping a userinfo */
public static final BitSet resvdUIChar;
/** list of characters which must not be unescaped when unescaping a host */
public static final BitSet resvdHostChar;
/** list of characters which must not be unescaped when unescaping a path */
public static final BitSet resvdPathChar;
/** list of characters which must not be unescaped when unescaping a query string */
public static final BitSet resvdQueryChar;
/** list of characters which must not be escaped when escaping a path */
public static final BitSet escpdPathChar;
/** list of characters which must not be escaped when escaping a query string */
public static final BitSet escpdQueryChar;
/** list of characters which must not be escaped when escaping a fragment identifier */
public static final BitSet escpdFragChar;
static
{
defaultPorts.put("http", new Integer(80));
defaultPorts.put("shttp", new Integer(80));
defaultPorts.put("http-ng", new Integer(80));
defaultPorts.put("coffee", new Integer(80));
defaultPorts.put("https", new Integer(443));
defaultPorts.put("ftp", new Integer(21));
defaultPorts.put("telnet", new Integer(23));
defaultPorts.put("nntp", new Integer(119));
defaultPorts.put("news", new Integer(119));
defaultPorts.put("snews", new Integer(563));
defaultPorts.put("hnews", new Integer(80));
defaultPorts.put("smtp", new Integer(25));
defaultPorts.put("gopher", new Integer(70));
defaultPorts.put("wais", new Integer(210));
defaultPorts.put("whois", new Integer(43));
defaultPorts.put("whois++", new Integer(63));
defaultPorts.put("rwhois", new Integer(4321));
defaultPorts.put("imap", new Integer(143));
defaultPorts.put("pop", new Integer(110));
defaultPorts.put("prospero", new Integer(1525));
defaultPorts.put("irc", new Integer(194));
defaultPorts.put("ldap", new Integer(389));
defaultPorts.put("nfs", new Integer(2049));
defaultPorts.put("z39.50r", new Integer(210));
defaultPorts.put("z39.50s", new Integer(210));
defaultPorts.put("vemmi", new Integer(575));
defaultPorts.put("videotex", new Integer(516));
defaultPorts.put("cmp", new Integer(829));
usesGenericSyntax.put("http", Boolean.TRUE);
usesGenericSyntax.put("https", Boolean.TRUE);
usesGenericSyntax.put("shttp", Boolean.TRUE);
usesGenericSyntax.put("coffee", Boolean.TRUE);
usesGenericSyntax.put("ftp", Boolean.TRUE);
usesGenericSyntax.put("file", Boolean.TRUE);
usesGenericSyntax.put("nntp", Boolean.TRUE);
usesGenericSyntax.put("news", Boolean.TRUE);
usesGenericSyntax.put("snews", Boolean.TRUE);
usesGenericSyntax.put("hnews", Boolean.TRUE);
usesGenericSyntax.put("imap", Boolean.TRUE);
usesGenericSyntax.put("wais", Boolean.TRUE);
usesGenericSyntax.put("nfs", Boolean.TRUE);
usesGenericSyntax.put("sip", Boolean.TRUE);
usesGenericSyntax.put("sips", Boolean.TRUE);
usesGenericSyntax.put("sipt", Boolean.TRUE);
usesGenericSyntax.put("sipu", Boolean.TRUE);
/* Note: schemes which definitely don't use the generic-URI syntax
* and must therefore never appear in the above list:
* "urn", "mailto", "sdp", "service", "tv", "gsm-sms", "tel", "fax",
* "modem", "eid", "cid", "mid", "data", "ldap"
*/
usesSemiGenericSyntax.put("ldap", Boolean.TRUE);
usesSemiGenericSyntax.put("irc", Boolean.TRUE);
usesSemiGenericSyntax.put("gopher", Boolean.TRUE);
usesSemiGenericSyntax.put("videotex", Boolean.TRUE);
usesSemiGenericSyntax.put("rwhois", Boolean.TRUE);
usesSemiGenericSyntax.put("whois++", Boolean.TRUE);
usesSemiGenericSyntax.put("smtp", Boolean.TRUE);
usesSemiGenericSyntax.put("telnet", Boolean.TRUE);
usesSemiGenericSyntax.put("prospero", Boolean.TRUE);
usesSemiGenericSyntax.put("pop", Boolean.TRUE);
usesSemiGenericSyntax.put("vemmi", Boolean.TRUE);
usesSemiGenericSyntax.put("z39.50r", Boolean.TRUE);
usesSemiGenericSyntax.put("z39.50s", Boolean.TRUE);
usesSemiGenericSyntax.put("stream", Boolean.TRUE);
usesSemiGenericSyntax.put("cmp", Boolean.TRUE);
alphanumChar = new BitSet(128);
for (int ch='0'; ch<='9'; ch++) alphanumChar.set(ch);
for (int ch='A'; ch<='Z'; ch++) alphanumChar.set(ch);
for (int ch='a'; ch<='z'; ch++) alphanumChar.set(ch);
markChar = new BitSet(128);
markChar.set('-');
markChar.set('_');
markChar.set('.');
markChar.set('!');
markChar.set('~');
markChar.set('*');
markChar.set('\'');
markChar.set('(');
markChar.set(')');
reservedChar = new BitSet(128);
reservedChar.set(';');
reservedChar.set('/');
reservedChar.set('?');
reservedChar.set(':');
reservedChar.set('@');
reservedChar.set('&');
reservedChar.set('=');
reservedChar.set('+');
reservedChar.set('$');
reservedChar.set(',');
unreservedChar = new BitSet(128);
unreservedChar.or(alphanumChar);
unreservedChar.or(markChar);
uricChar = new BitSet(128);
uricChar.or(unreservedChar);
uricChar.or(reservedChar);
uricChar.set('%');
pcharChar = new BitSet(128);
pcharChar.or(unreservedChar);
pcharChar.set('%');
pcharChar.set(':');
pcharChar.set('@');
pcharChar.set('&');
pcharChar.set('=');
pcharChar.set('+');
pcharChar.set('$');
pcharChar.set(',');
userinfoChar = new BitSet(128);
userinfoChar.or(unreservedChar);
userinfoChar.set('%');
userinfoChar.set(';');
userinfoChar.set(':');
userinfoChar.set('&');
userinfoChar.set('=');
userinfoChar.set('+');
userinfoChar.set('$');
userinfoChar.set(',');
// this actually shouldn't contain uppercase letters...
schemeChar = new BitSet(128);
schemeChar.or(alphanumChar);
schemeChar.set('+');
schemeChar.set('-');
schemeChar.set('.');
opaqueChar = new BitSet(128);
opaqueChar.or(uricChar);
hostChar = new BitSet(128);
hostChar.or(alphanumChar);
hostChar.set('-');
hostChar.set('.');
reg_nameChar = new BitSet(128);
reg_nameChar.or(unreservedChar);
reg_nameChar.set('$');
reg_nameChar.set(',');
reg_nameChar.set(';');
reg_nameChar.set(':');
reg_nameChar.set('@');
reg_nameChar.set('&');
reg_nameChar.set('=');
reg_nameChar.set('+');
resvdSchemeChar = new BitSet(128);
resvdSchemeChar.set(':');
resvdUIChar = new BitSet(128);
resvdUIChar.set('@');
resvdHostChar = new BitSet(128);
resvdHostChar.set(':');
resvdHostChar.set('/');
resvdHostChar.set('?');
resvdHostChar.set('#');
resvdPathChar = new BitSet(128);
resvdPathChar.set('/');
resvdPathChar.set(';');
resvdPathChar.set('?');
resvdPathChar.set('#');
resvdQueryChar = new BitSet(128);
resvdQueryChar.set('#');
escpdPathChar = new BitSet(128);
escpdPathChar.or(pcharChar);
escpdPathChar.set('%');
escpdPathChar.set('/');
escpdPathChar.set(';');
escpdQueryChar = new BitSet(128);
escpdQueryChar.or(uricChar);
escpdQueryChar.clear('#');
escpdFragChar = new BitSet(128);
escpdFragChar.or(uricChar);
}
/* our uri in pieces */
protected static final int OPAQUE = 0;
protected static final int SEMI_GENERIC = 1;
protected static final int GENERIC = 2;
protected int type;
protected String scheme;
protected String opaque;
protected String userinfo;
protected String host;
protected int port = -1;
protected String path;
protected String query;
protected String fragment;
/* cache the java.net.URL */
protected URL url = null;
// Constructors
/**
* Constructs a URI from the given string representation. The string
* must be an absolute URI.
*
* @param uri a String containing an absolute URI
* @exception ParseException if no scheme can be found or a specified
* port cannot be parsed as a number
*/
public URI(String uri) throws ParseException
{
this((URI) null, uri);
}
/**
* Constructs a URI from the given string representation, relative to
* the given base URI.
*
* @param base the base URI, relative to which <var>rel_uri</var>
* is to be parsed
* @param rel_uri a String containing a relative or absolute URI
* @exception ParseException if <var>base</var> is null and
* <var>rel_uri</var> is not an absolute URI, or
* if <var>base</var> is not null and the scheme
* is not known to use the generic syntax, or
* if a given port cannot be parsed as a number
*/
public URI(URI base, String rel_uri) throws ParseException
{
/* Parsing is done according to the following RE:
*
* ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
* 12 3 4 5 6 7 8 9
*
* 2: scheme
* 4: authority
* 5: path
* 7: query
* 9: fragment
*/
char[] uri = rel_uri.toCharArray();
int pos = 0, idx, len = uri.length;
// trim()
while (pos < len && Character.isWhitespace(uri[pos])) pos++;
while (len > 0 && Character.isWhitespace(uri[len-1])) len--;
// strip the special "url" or "uri" scheme
if (pos < len-3 && uri[pos+3] == ':' &&
(uri[pos+0] == 'u' || uri[pos+0] == 'U') &&
(uri[pos+1] == 'r' || uri[pos+1] == 'R') &&
(uri[pos+2] == 'i' || uri[pos+2] == 'I' ||
uri[pos+2] == 'l' || uri[pos+2] == 'L'))
pos += 4;
// get scheme: (([^:/?#]+):)?
idx = pos;
while (idx < len && uri[idx] != ':' && uri[idx] != '/' &&
uri[idx] != '?' && uri[idx] != '#')
idx++;
if (idx < len && uri[idx] == ':')
{
scheme = rel_uri.substring(pos, idx).trim().toLowerCase();
pos = idx + 1;
}
// check and resolve scheme
String final_scheme = scheme;
if (scheme == null)
{
if (base == null)
throw new ParseException("No scheme found");
final_scheme = base.scheme;
}
// check for generic vs. opaque
type = usesGenericSyntax(final_scheme) ? GENERIC :
usesSemiGenericSyntax(final_scheme) ? SEMI_GENERIC : OPAQUE;
if (type == OPAQUE)
{
if (base != null && scheme == null)
throw new ParseException("Can't resolve relative URI for " +
"scheme " + final_scheme);
opaque = escape(rel_uri.substring(pos), opaqueChar, true);
if (opaque.length() > 0 && opaque.charAt(0) == '/')
opaque = "%2F" + opaque.substring(1);
return;
}
// get authority: (//([^/?#]*))?
if (pos+1 < len && uri[pos] == '/' && uri[pos+1] == '/')
{
pos += 2;
idx = pos;
while (idx < len && uri[idx] != '/' && uri[idx] != '?' &&
uri[idx] != '#')
idx++;
parse_authority(rel_uri.substring(pos, idx), final_scheme);
pos = idx;
}
// handle semi-generic and generic uri's
if (type == SEMI_GENERIC)
{
path = escape(rel_uri.substring(pos), uricChar, true);
if (path.length() > 0 && path.charAt(0) != '/')
path = '/' + path;
}
else
{
// get path: ([^?#]*)
idx = pos;
while (idx < len && uri[idx] != '?' && uri[idx] != '#')
idx++;
path = escape(rel_uri.substring(pos, idx), escpdPathChar, true);
pos = idx;
// get query: (\?([^#]*))?
if (pos < len && uri[pos] == '?')
{
pos += 1;
idx = pos;
while (idx < len && uri[idx] != '#')
idx++;
this.query = escape(rel_uri.substring(pos, idx), escpdQueryChar, true);
pos = idx;
}
// get fragment: (#(.*))?
if (pos < len && uri[pos] == '#')
this.fragment = escape(rel_uri.substring(pos+1, len), escpdFragChar, true);
}
// now resolve the parts relative to the base
if (base != null)
{
if (scheme != null && // resolve scheme
!(scheme.equals(base.scheme) && ENABLE_BACKWARDS_COMPATIBILITY))
return;
scheme = base.scheme;
if (host != null) // resolve authority
return;
userinfo = base.userinfo;
host = base.host;
port = base.port;
if (type == SEMI_GENERIC) // can't resolve relative paths
return;
if (path.length() == 0 && query == null) // current doc
{
path = base.path;
query = base.query;
return;
}
if (path.length() == 0 || path.charAt(0) != '/') // relative path
{
idx = (base.path != null) ? base.path.lastIndexOf('/') : -1;
if (idx < 0)
path = '/' + path;
else
path = base.path.substring(0, idx+1) + path;
path = canonicalizePath(path);
}
}
}
/**
* Remove all "/../" and "/./" from path, where possible. Leading "/../"'s
* are not removed.
*
* @param path the path to canonicalize
* @return the canonicalized path
*/
public static String canonicalizePath(String path)
{
int idx, len = path.length();
if (!((idx = path.indexOf("/.")) != -1 &&
(idx == len-2 || path.charAt(idx+2) == '/' ||
(path.charAt(idx+2) == '.' &&
(idx == len-3 || path.charAt(idx+3) == '/')) )))
return path;
char[] p = new char[path.length()]; // clean path
path.getChars(0, p.length, p, 0);
int beg = 0;
for (idx=1; idx<len; idx++)
{
if (p[idx] == '.' && p[idx-1] == '/')
{
int end;
if (idx == len-1) // trailing "/."
{
end = idx;
idx += 1;
}
else if (p[idx+1] == '/') // "/./"
{
end = idx - 1;
idx += 1;
}
else if (p[idx+1] == '.' &&
(idx == len-2 || p[idx+2] == '/')) // "/../"
{
if (idx < beg + 2) // keep from backing up too much
{
beg = idx + 2;
continue;
}
end = idx - 2;
while (end > beg && p[end] != '/') end--;
if (p[end] != '/') continue;
if (idx == len-2) end++;
idx += 2;
}
else
continue;
System.arraycopy(p, idx, p, end, len-idx);
len -= idx - end;
idx = end;
}
}
return new String(p, 0, len);
}
/**
* Parse the authority specific part
*/
private void parse_authority(String authority, String scheme)
throws ParseException
{
/* The authority is further parsed according to:
*
* ^(([^@]*)@?)(\[[^]]*\]|[^:]*)?(:(.*))?
* 12 3 4 5
*
* 2: userinfo
* 3: host
* 5: port
*/
char[] uri = authority.toCharArray();
int pos = 0, idx, len = uri.length;
// get userinfo: (([^@]*)@?)
idx = pos;
while (idx < len && uri[idx] != '@')
idx++;
if (idx < len && uri[idx] == '@')
{
this.userinfo = escape(authority.substring(pos, idx), userinfoChar, true);
pos = idx + 1;
}
// get host: (\[[^]]*\]|[^:]*)?
idx = pos;
if (idx < len && uri[idx] == '[') // IPv6
{
while (idx < len && uri[idx] != ']')
idx++;
if (idx == len)
throw new ParseException("No closing ']' found for opening '['"+
" at position " + pos +
" in authority `" + authority + "'");
this.host = authority.substring(pos+1, idx);
idx++;
}
else
{
while (idx < len && uri[idx] != ':')
idx++;
this.host = escape(authority.substring(pos, idx), uricChar, true);
}
pos = idx;
// get port: (:(.*))?
if (pos < (len-1) && uri[pos] == ':')
{
int p;
try
{
p = Integer.parseInt(
unescape(authority.substring(pos+1, len), null));
if (p < 0) throw new NumberFormatException();
}
catch (NumberFormatException e)
{
throw new ParseException(authority.substring(pos+1, len) +
" is an invalid port number");
}
if (p == defaultPort(scheme))
this.port = -1;
else
this.port = p;
}
}
/**
* Construct a URI from the given URL.
*
* @param url the URL
* @exception ParseException if <code>url.toExternalForm()</code> generates
* an invalid string representation
*/
public URI(URL url) throws ParseException
{
this((URI) null, url.toExternalForm());
}
/**
* Constructs a URI from the given parts, using the default port for
* this scheme (if known). The parts must be in unescaped form.
*
* @param scheme the scheme (sometimes known as protocol)
* @param host the host
* @param path the path part
* @exception ParseException if <var>scheme</var> is null
*/
public URI(String scheme, String host, String path) throws ParseException
{
this(scheme, null, host, -1, path, null, null);
}
/**
* Constructs a URI from the given parts. The parts must be in unescaped
* form.
*
* @param scheme the scheme (sometimes known as protocol)
* @param host the host
* @param port the port
* @param path the path part
* @exception ParseException if <var>scheme</var> is null
*/
public URI(String scheme, String host, int port, String path)
throws ParseException
{
this(scheme, null, host, port, path, null, null);
}
/**
* Constructs a URI from the given parts. Any part except for the
* the scheme may be null. The parts must be in unescaped form.
*
* @param scheme the scheme (sometimes known as protocol)
* @param userinfo the userinfo
* @param host the host
* @param port the port
* @param path the path part
* @param query the query string
* @param fragment the fragment identifier
* @exception ParseException if <var>scheme</var> is null
*/
public URI(String scheme, String userinfo, String host, int port,
String path, String query, String fragment)
throws ParseException
{
if (scheme == null)
throw new ParseException("missing scheme");
this.scheme = escape(scheme.trim().toLowerCase(), schemeChar, true);
if (userinfo != null)
this.userinfo = escape(userinfo.trim(), userinfoChar, true);
if (host != null)
{
host = host.trim();
this.host = isIPV6Addr(host) ? host : escape(host, hostChar, true);
}
if (port != defaultPort(scheme))
this.port = port;
if (path != null)
this.path = escape(path.trim(), escpdPathChar, true); // ???
if (query != null)
this.query = escape(query.trim(), escpdQueryChar, true);
if (fragment != null)
this.fragment = escape(fragment.trim(), escpdFragChar, true);
type = usesGenericSyntax(scheme) ? GENERIC : SEMI_GENERIC;
}
private static final boolean isIPV6Addr(String host)
{
if (host.indexOf(':') < 0)
return false;
for (int idx=0; idx<host.length(); idx++)
{
char ch = host.charAt(idx);
if ((ch < '0' || ch > '9') && ch != ':')
return false;
}
return true;
}
/**
* Constructs an opaque URI from the given parts.
*
* @param scheme the scheme (sometimes known as protocol)
* @param opaque the opaque part
* @exception ParseException if <var>scheme</var> is null
*/
public URI(String scheme, String opaque)
throws ParseException
{
if (scheme == null)
throw new ParseException("missing scheme");
this.scheme = escape(scheme.trim().toLowerCase(), schemeChar, true);
this.opaque = escape(opaque, opaqueChar, true);
type = OPAQUE;
}
// Class Methods
/**
* @return true if the scheme should be parsed according to the
* generic-URI syntax
*/
public static boolean usesGenericSyntax(String scheme)
{
return usesGenericSyntax.containsKey(scheme.trim().toLowerCase());
}
/**
* @return true if the scheme should be parsed according to a
* semi-generic-URI syntax <scheme&tgt;://<hostport>/<opaque>
*/
public static boolean usesSemiGenericSyntax(String scheme)
{
return usesSemiGenericSyntax.containsKey(scheme.trim().toLowerCase());
}
/**
* Return the default port used by a given protocol.
*
* @param protocol the protocol
* @return the port number, or 0 if unknown
*/
public final static int defaultPort(String protocol)
{
Integer port = defaultPorts.get(protocol.trim().toLowerCase());
return (port != null) ? port.intValue() : 0;
}
// Instance Methods
/**
* @return the scheme (often also referred to as protocol)
*/
public String getScheme()
{
return scheme;
}
/**
* @return the opaque part, or null if this URI is generic
*/
public String getOpaque()
{
return opaque;
}
/**
* @return the host
*/
public String getHost()
{
return host;
}
/**
* @return the port, or -1 if it's the default port, or 0 if unknown
*/
public int getPort()
{
return port;
}
/**
* @return the user info
*/
public String getUserinfo()
{
return userinfo;
}
/**
* @return the path
*/
public String getPath()
{
return path;
}
/**
* @return the query string
*/
public String getQueryString()
{
return query;
}
/**
* @return the path and query
*/
public String getPathAndQuery()
{
if (query == null)
return path;
if (path == null)
return "?" + query;
return path + "?" + query;
}
/**
* @return the fragment
*/
public String getFragment()
{
return fragment;
}
/**
* Does the scheme specific part of this URI use the generic-URI syntax?
*
* <P>In general URI are split into two categories: opaque-URI and
* generic-URI. The generic-URI syntax is the syntax most are familiar
* with from URLs such as ftp- and http-URLs, which is roughly:
* <PRE>
* generic-URI = scheme ":" [ "//" server ] [ "/" ] [ path_segments ] [ "?" query ]
* </PRE>
* (see RFC-2396 for exact syntax). Only URLs using the generic-URI syntax
* can be used to create and resolve relative URIs.
*
* <P>Whether a given scheme is parsed according to the generic-URI
* syntax or wether it is treated as opaque is determined by an internal
* table of URI schemes.
*
* @see <A HREF="http://www.ics.uci.edu/pub/ietf/uri/rfc2396.txt">rfc-2396</A>
*/
public boolean isGenericURI()
{
return (type == GENERIC);
}
/**
* Does the scheme specific part of this URI use the semi-generic-URI syntax?
*
* <P>Many schemes which don't follow the full generic syntax actually
* follow a reduced form where the path part is treated is opaque. This
* is used for example by ldap, smtp, pop, etc, and is roughly
* <PRE>
* generic-URI = scheme ":" [ "//" server ] [ "/" [ opaque_path ] ]
* </PRE>
* I.e. parsing is identical to the generic-syntax, except that the path
* part is not further parsed. URLs using the semi-generic-URI syntax can
* be used to create and resolve relative URIs with the restriction that
* all paths are treated as absolute.
*
* <P>Whether a given scheme is parsed according to the semi-generic-URI
* syntax is determined by an internal table of URI schemes.
*
* @see #isGenericURI()
*/
public boolean isSemiGenericURI()
{
return (type == SEMI_GENERIC);
}
/**
* Will try to create a java.net.URL object from this URI.
*
* @return the URL
* @exception MalformedURLException if no handler is available for the
* scheme
*/
public URL toURL() throws MalformedURLException
{
if (url != null) return url;
if (opaque != null)
return (url = new URL(scheme + ":" + opaque));
String hostinfo;
if (userinfo != null && host != null)
hostinfo = userinfo + "@" + host;
else if (userinfo != null)
hostinfo = userinfo + "@";
else
hostinfo = host;
StringBuffer file = new StringBuffer(100);
assemblePath(file, true, true, false);
url = new URL(scheme, hostinfo, port, file.toString());
return url;
}
private final void assemblePath(StringBuffer buf, boolean printEmpty,
boolean incFragment, boolean unescape)
{
if ((path == null || path.length() == 0) && printEmpty)
buf.append('/');