KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sslexplorer > vfs > utils > URI


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  *
5  * Copyright (c) 1999 The Apache Software Foundation. All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
8  * conditions are met:
9  * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
11  * disclaimer in the documentation and/or other materials provided with the distribution.
12  * 3. The end-user documentation included with the redistribution, if any, must include the following acknowledgment: "This
13  * product includes software developed by the Apache Software Foundation (http://www.apache.org/)." Alternately, this
14  * acknowledgment may appear in the software itself, if and wherever such third-party acknowledgments normally appear.
15  * 4. The names "Xalan" and "Apache Software Foundation" must not be used to endorse or promote products derived from this
16  * software without prior written permission. For written permission, please contact apache@apache.org.
17  * 5. Products derived from this software may not be called "Apache", nor may "Apache" appear in their name, without prior written
18  * permission of the Apache Software Foundation.
19  *
20  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE
22  * FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  * ====================================================================
27  *
28  * This software consists of voluntary contributions made by many individuals on behalf of the Apache Software Foundation and was
29  * originally based on software copyright (c) 1999, Lotus Development Corporation., http://www.lotus.com. For more information on
30  * the Apache Software Foundation, please see <http://www.apache.org/> .
31  *
32  *
33  *
34  * Adapted for use as a standalone class in Maverick by removing references to XSLMessages and XSLErrorResources.
35  */

36 package com.sslexplorer.vfs.utils;
37
38 import java.io.IOException JavaDoc;
39 import java.io.Serializable JavaDoc;
40
41 /**
42  * A class to represent a Uniform Resource Identifier (URI). This class is
43  * designed to handle the parsing of URIs and provide access to the various
44  * components (scheme, host, port, userinfo, path, query string and fragment)
45  * that may constitute a URI.
46  * <p>
47  * Parsing of a URI specification is done according to the URI syntax described
48  * in RFC 2396 <http://www.ietf.org/rfc/rfc2396.txt?number=2396>. Every URI
49  * consists of a scheme, followed by a colon (':'), followed by a
50  * scheme-specific part. For URIs that follow the "generic URI" syntax, the
51  * scheme- specific part begins with two slashes ("//") and may be followed by
52  * an authority segment (comprised of user information, host, and port), path
53  * segment, query segment and fragment. Note that RFC 2396 no longer specifies
54  * the use of the parameters segment and excludes the "user:password" syntax as
55  * part of the authority segment. If "user:password" appears in a URI, the
56  * entire user/password string is stored as userinfo.
57  * <p>
58  * For URIs that do not follow the "generic URI" syntax (e.g. mailto), the
59  * entire scheme-specific part is treated as the "path" portion of the URI.
60  * <p>
61  * Note that, unlike the java.net.URL class, this class does not provide any
62  * built-in network access functionality nor does it provide any scheme-specific
63  * functionality (for example, it does not know a default port for a specific
64  * scheme). Rather, it only knows the grammar and basic set of operations that
65  * can be applied to a URI.
66  *
67  *
68  */

69 public class URI implements Serializable JavaDoc {
70
71     /**
72      * MalformedURIExceptions are thrown in the process of building a URI or
73      * setting fields on a URI when an operation would result in an invalid URI
74      * specification.
75      *
76      */

77     public static class MalformedURIException extends IOException JavaDoc {
78
79         /**
80          * Constructs a <code>MalformedURIException</code> with no specified
81          * detail message.
82          */

83         public MalformedURIException() {
84             super();
85         }
86
87         /**
88          * Constructs a <code>MalformedURIException</code> with the specified
89          * detail message.
90          *
91          * @param p_msg the detail message.
92          */

93         public MalformedURIException(String JavaDoc p_msg) {
94             super(p_msg);
95         }
96     }
97
98     /** reserved characters */
99     private static final String JavaDoc RESERVED_CHARACTERS = ";/?:@&=+$,";
100
101     /**
102      * URI punctuation mark characters - these, combined with alphanumerics,
103      * constitute the "unreserved" characters
104      */

105     private static final String JavaDoc MARK_CHARACTERS = "-_.!~*'() ";
106
107     /** scheme can be composed of alphanumerics and these characters */
108     private static final String JavaDoc SCHEME_CHARACTERS = "+-.";
109
110     /**
111      * userinfo can be composed of unreserved, escaped and these characters
112      */

113     private static final String JavaDoc USERINFO_CHARACTERS = ";:&=+$,";
114
115     /**
116      * Stores the scheme (usually the protocol) for this URI.
117      *
118      * @serial
119      */

120     private String JavaDoc m_scheme = null;
121
122     /**
123      * If specified, stores the userinfo for this URI; otherwise null.
124      *
125      * @serial
126      */

127     private String JavaDoc m_userinfo = null;
128
129     /**
130      * If specified, stores the host for this URI; otherwise null.
131      *
132      * @serial
133      */

134     private String JavaDoc m_host = null;
135
136     /**
137      * If specified, stores the port for this URI; otherwise -1.
138      *
139      * @serial
140      */

141     private int m_port = -1;
142
143     /**
144      * If specified, stores the path for this URI; otherwise null.
145      *
146      * @serial
147      */

148     private String JavaDoc m_path = null;
149
150     /**
151      * If specified, stores the query string for this URI; otherwise null.
152      *
153      * @serial
154      */

155     private String JavaDoc m_queryString = null;
156
157     /**
158      * If specified, stores the fragment for this URI; otherwise null.
159      *
160      * @serial
161      */

162     private String JavaDoc m_fragment = null;
163
164     /** Indicate whether in DEBUG mode */
165     // private static boolean DEBUG = false;
166
/**
167      * Construct a new and uninitialized URI.
168      */

169     public URI() {
170     }
171
172     /**
173      * Construct a new URI from another URI. All fields for this URI are set
174      * equal to the fields of the URI passed in.
175      *
176      * @param p_other the URI to copy (cannot be null)
177      */

178     public URI(URI p_other) {
179         initialize(p_other);
180     }
181
182     /**
183      * Construct a new URI from a URI specification string. If the specification
184      * follows the "generic URI" syntax, (two slashes following the first
185      * colon), the specification will be parsed accordingly - setting the
186      * scheme, userinfo, host,port, path, query string and fragment fields as
187      * necessary. If the specification does not follow the "generic URI" syntax,
188      * the specification is parsed into a scheme and scheme-specific part
189      * (stored as the path) only.
190      *
191      * @param p_uriSpec the URI specification string (cannot be null or empty)
192      *
193      * @throws MalformedURIException if p_uriSpec violates any syntax rules
194      */

195     public URI(String JavaDoc p_uriSpec) throws MalformedURIException {
196         this((URI) null, p_uriSpec);
197     }
198
199     /**
200      * Construct a new URI from a base URI and a URI specification string. The
201      * URI specification string may be a relative URI.
202      *
203      * @param p_base the base URI (cannot be null if p_uriSpec is null or empty)
204      * @param p_uriSpec the URI specification string (cannot be null or empty if
205      * p_base is null)
206      *
207      * @throws MalformedURIException if p_uriSpec violates any syntax rules
208      */

209     public URI(URI p_base, String JavaDoc p_uriSpec) throws MalformedURIException {
210         initialize(p_base, p_uriSpec);
211     }
212
213     /**
214      * Construct a new URI that does not follow the generic URI syntax. Only the
215      * scheme and scheme-specific part (stored as the path) are initialized.
216      *
217      * @param p_scheme the URI scheme (cannot be null or empty)
218      * @param p_schemeSpecificPart the scheme-specific part (cannot be null or
219      * empty)
220      *
221      * @throws MalformedURIException if p_scheme violates any syntax rules
222      */

223     public URI(String JavaDoc p_scheme, String JavaDoc p_schemeSpecificPart) throws MalformedURIException {
224
225         if (p_scheme == null || p_scheme.trim().length() == 0) {
226             throw new MalformedURIException("Cannot construct URI with null/empty scheme!");
227         }
228
229         if (p_schemeSpecificPart == null || p_schemeSpecificPart.trim().length() == 0) {
230             throw new MalformedURIException("Cannot construct URI with null/empty scheme-specific part!");
231         }
232
233         setScheme(p_scheme);
234         setPath(p_schemeSpecificPart);
235     }
236
237     /**
238      * Construct a new URI that follows the generic URI syntax from its
239      * component parts. Each component is validated for syntax and some basic
240      * semantic checks are performed as well. See the individual setter methods
241      * for specifics.
242      *
243      * @param p_scheme the URI scheme (cannot be null or empty)
244      * @param p_host the hostname or IPv4 address for the URI
245      * @param p_path the URI path - if the path contains '?' or '#', then the
246      * query string and/or fragment will be set from the path; however,
247      * if the query and fragment are specified both in the path and as
248      * separate parameters, an exception is thrown
249      * @param p_queryString the URI query string (cannot be specified if path is
250      * null)
251      * @param p_fragment the URI fragment (cannot be specified if path is null)
252      *
253      * @throws MalformedURIException if any of the parameters violates syntax
254      * rules or semantic rules
255      */

256     public URI(String JavaDoc p_scheme, String JavaDoc p_host, String JavaDoc p_path, String JavaDoc p_queryString, String JavaDoc p_fragment) throws MalformedURIException {
257         this(p_scheme, null, p_host, -1, p_path, p_queryString, p_fragment);
258     }
259
260     /**
261      * Construct a new URI that follows the generic URI syntax from its
262      * component parts. Each component is validated for syntax and some basic
263      * semantic checks are performed as well. See the individual setter methods
264      * for specifics.
265      *
266      * @param p_scheme the URI scheme (cannot be null or empty)
267      * @param p_userinfo the URI userinfo (cannot be specified if host is null)
268      * @param p_host the hostname or IPv4 address for the URI
269      * @param p_port the URI port (may be -1 for "unspecified"; cannot be
270      * specified if host is null)
271      * @param p_path the URI path - if the path contains '?' or '#', then the
272      * query string and/or fragment will be set from the path; however,
273      * if the query and fragment are specified both in the path and as
274      * separate parameters, an exception is thrown
275      * @param p_queryString the URI query string (cannot be specified if path is
276      * null)
277      * @param p_fragment the URI fragment (cannot be specified if path is null)
278      *
279      * @throws MalformedURIException if any of the parameters violates syntax
280      * rules or semantic rules
281      */

282     public URI(String JavaDoc p_scheme, String JavaDoc p_userinfo, String JavaDoc p_host, int p_port, String JavaDoc p_path, String JavaDoc p_queryString, String JavaDoc p_fragment)
283         throws MalformedURIException {
284
285         if (p_scheme == null || p_scheme.trim().length() == 0) {
286             throw new MalformedURIException("Scheme is required!");
287         }
288
289         if (p_host == null) {
290             if (p_userinfo != null) {
291                 throw new MalformedURIException("Userinfo may not be specified if host is not specified!");
292             }
293
294             if (p_port != -1) {
295                 throw new MalformedURIException("Port may not be specified if host is not specified!");
296             }
297         }
298
299         if (p_path != null) {
300             if (p_path.indexOf('?') != -1 && p_queryString != null) {
301                 throw new MalformedURIException("Query string cannot be specified in path and query string!");
302             }
303
304             if (p_path.indexOf('#') != -1 && p_fragment != null) {
305                 throw new MalformedURIException("Fragment cannot be specified in both the path and fragment!");
306             }
307         }
308
309         setScheme(p_scheme);
310         setHost(p_host);
311         setPort(p_port);
312         setUserinfo(p_userinfo);
313         setPath(p_path);
314         setQueryString(p_queryString);
315         setFragment(p_fragment);
316     }
317
318     /**
319      * Initialize all fields of this URI from another URI.
320      *
321      * @param p_other the URI to copy (cannot be null)
322      */

323     private void initialize(URI p_other) {
324
325         m_scheme = p_other.getScheme();
326         m_userinfo = p_other.getUserinfo();
327         m_host = p_other.getHost();
328         m_port = p_other.getPort();
329         m_path = p_other.getPath();
330         m_queryString = p_other.getQueryString();
331         m_fragment = p_other.getFragment();
332     }
333
334     /**
335      * Initializes this URI from a base URI and a URI specification string. See
336      * RFC 2396 Section 4 and Appendix B for specifications on parsing the URI
337      * and Section 5 for specifications on resolving relative URIs and relative
338      * paths.
339      *
340      * @param p_base the base URI (may be null if p_uriSpec is an absolute URI)
341      * @param p_uriSpec the URI spec string which may be an absolute or relative
342      * URI (can only be null/empty if p_base is not null)
343      *
344      * @throws MalformedURIException if p_base is null and p_uriSpec is not an
345      * absolute URI or if p_uriSpec violates syntax rules
346      */

347     private void initialize(URI p_base, String JavaDoc p_uriSpec) throws MalformedURIException {
348
349         if (p_base == null && (p_uriSpec == null || p_uriSpec.trim().length() == 0)) {
350             throw new MalformedURIException("Cannot initialize URI with empty parameters.");
351         }
352
353         // just make a copy of the base if spec is empty
354
if (p_uriSpec == null || p_uriSpec.trim().length() == 0) {
355             initialize(p_base);
356
357             return;
358         }
359
360         String JavaDoc uriSpec = p_uriSpec.trim();
361         int uriSpecLen = uriSpec.length();
362         int index = 0;
363
364         // check for scheme
365
if (uriSpec.indexOf(':') == -1) {
366             if (p_base == null) {
367                 throw new MalformedURIException("No scheme found in URI: " + uriSpec);
368             }
369         } else {
370             initializeScheme(uriSpec);
371
372             index = m_scheme.length() + 1;
373         }
374
375         // two slashes means generic URI syntax, so we get the authority
376
if (((index + 1) < uriSpecLen) && (uriSpec.substring(index).startsWith("//"))) {
377             index += 2;
378
379             int startPos = index;
380
381             // get authority - everything up to path, query or fragment
382
char testChar = '\0';
383
384             while (index < uriSpecLen) {
385                 testChar = uriSpec.charAt(index);
386
387                 if (testChar == '/' || testChar == '?' || testChar == '#') {
388                     break;
389                 }
390
391                 index++;
392             }
393
394             // if we found authority, parse it out, otherwise we set the
395
// host to empty string
396
if (index > startPos) {
397                 initializeAuthority(uriSpec.substring(startPos, index));
398             } else {
399                 m_host = "";
400             }
401         }
402
403         initializePath(uriSpec.substring(index));
404
405         // Resolve relative URI to base URI - see RFC 2396 Section 5.2
406
// In some cases, it might make more sense to throw an exception
407
// (when scheme is specified is the string spec and the base URI
408
// is also specified, for example), but we're just following the
409
// RFC specifications
410
if (p_base != null) {
411
412             // check to see if this is the current doc - RFC 2396 5.2 #2
413
// note that this is slightly different from the RFC spec in that
414
// we don't include the check for query string being null
415
// - this handles cases where the urispec is just a query
416
// string or a fragment (e.g. "?y" or "#s") -
417
// see <http://www.ics.uci.edu/~fielding/url/test1.html> which
418
// identified this as a bug in the RFC
419
if (m_path.length() == 0 && m_scheme == null && m_host == null) {
420                 m_scheme = p_base.getScheme();
421                 m_userinfo = p_base.getUserinfo();
422                 m_host = p_base.getHost();
423                 m_port = p_base.getPort();
424                 m_path = p_base.getPath();
425
426                 if (m_queryString == null) {
427                     m_queryString = p_base.getQueryString();
428                 }
429
430                 return;
431             }
432
433             // check for scheme - RFC 2396 5.2 #3
434
// if we found a scheme, it means absolute URI, so we're done
435
if (m_scheme == null) {
436                 m_scheme = p_base.getScheme();
437             } else {
438                 return;
439             }
440
441             // check for authority - RFC 2396 5.2 #4
442
// if we found a host, then we've got a network path, so we're done
443
if (m_host == null) {
444                 m_userinfo = p_base.getUserinfo();
445                 m_host = p_base.getHost();
446                 m_port = p_base.getPort();
447             } else {
448                 return;
449             }
450
451             // check for absolute path - RFC 2396 5.2 #5
452
if (m_path.length() > 0 && m_path.startsWith("/")) {
453                 return;
454             }
455
456             // if we get to this point, we need to resolve relative path
457
// RFC 2396 5.2 #6
458
String JavaDoc path = new String JavaDoc();
459             String JavaDoc basePath = p_base.getPath();
460
461             // 6a - get all but the last segment of the base URI path
462
if (basePath != null) {
463                 int lastSlash = basePath.lastIndexOf('/');
464
465                 if (lastSlash != -1) {
466                     path = basePath.substring(0, lastSlash + 1);
467                 }
468             }
469
470             // 6b - append the relative URI path
471
path = path.concat(m_path);
472
473             // 6c - remove all "./" where "." is a complete path segment
474
index = -1;
475
476             while ((index = path.indexOf("/./")) != -1) {
477                 path = path.substring(0, index + 1).concat(path.substring(index + 3));
478             }
479
480             // 6d - remove "." if path ends with "." as a complete path segment
481
if (path.endsWith("/.")) {
482                 path = path.substring(0, path.length() - 1);
483             }
484
485             // 6e - remove all "<segment>/../" where "<segment>" is a complete
486
// path segment not equal to ".."
487
index = -1;
488
489             int segIndex = -1;
490             String JavaDoc tempString = null;
491
492             while ((index = path.indexOf("/../")) > 0) {
493                 tempString = path.substring(0, path.indexOf("/../"));
494                 segIndex = tempString.lastIndexOf('/');
495
496                 if (segIndex != -1) {
497                     if (!tempString.substring(segIndex++).equals("..")) {
498                         path = path.substring(0, segIndex).concat(path.substring(index + 4));
499                     }
500                 }
501             }
502
503             // 6f - remove ending "<segment>/.." where "<segment>" is a
504
// complete path segment
505
if (path.endsWith("/..")) {
506                 tempString = path.substring(0, path.length() - 3);
507                 segIndex = tempString.lastIndexOf('/');
508
509                 if (segIndex != -1) {
510                     path = path.substring(0, segIndex + 1);
511                 }
512             }
513
514             m_path = path;
515         }
516     }
517
518     /**
519      * Initialize the scheme for this URI from a URI string spec.
520      *
521      * @param p_uriSpec the URI specification (cannot be null)
522      *
523      * @throws MalformedURIException if URI does not have a conformant scheme
524      */

525     private void initializeScheme(String JavaDoc p_uriSpec) throws MalformedURIException {
526
527         int uriSpecLen = p_uriSpec.length();
528         int index = 0;
529         String JavaDoc scheme = null;
530         char testChar = '\0';
531
532         while (index < uriSpecLen) {
533             testChar = p_uriSpec.charAt(index);
534
535             if (testChar == ':' || testChar == '/' || testChar == '?' || testChar == '#') {
536                 break;
537             }
538
539             index++;
540         }
541
542         scheme = p_uriSpec.substring(0, index);
543
544         if (scheme.length() == 0) {
545             throw new MalformedURIException("No scheme found in URI.");
546         } else {
547             setScheme(scheme);
548         }
549     }
550
551     /**
552      * Initialize the authority (userinfo, host and port) for this URI from a
553      * URI string spec.
554      *
555      * @param p_uriSpec the URI specification (cannot be null)
556      *
557      * @throws MalformedURIException if p_uriSpec violates syntax rules
558      */

559     private void initializeAuthority(String JavaDoc p_uriSpec) throws MalformedURIException {
560
561         int index = 0;
562         int start = 0;
563         int end = p_uriSpec.length();
564         char testChar = '\0';
565         String JavaDoc userinfo = null;
566
567         // userinfo is everything up @
568
if (p_uriSpec.indexOf('@', start) != -1) {
569             while (index < end) {
570                 testChar = p_uriSpec.charAt(index);
571
572                 if (testChar == '@') {
573                     break;
574                 }
575
576                 index++;
577             }
578
579             userinfo = p_uriSpec.substring(start, index);
580
581             index++;
582         }
583
584         // host is everything up to ':'
585
String JavaDoc host = null;
586
587         start = index;
588
589         while (index < end) {
590             testChar = p_uriSpec.charAt(index);
591
592             if (testChar == ':') {
593                 break;
594             }
595
596             index++;
597         }
598
599         host = p_uriSpec.substring(start, index);
600
601         int port = -1;
602
603         if (host.length() > 0) {
604
605             // port
606
if (testChar == ':') {
607                 index++;
608
609                 start = index;
610
611                 while (index < end) {
612                     index++;
613                 }
614
615                 String JavaDoc portStr = p_uriSpec.substring(start, index);
616
617                 if (portStr.length() > 0) {
618                     for (int i = 0; i < portStr.length(); i++) {
619                         if (!isDigit(portStr.charAt(i))) {
620                             throw new MalformedURIException(portStr + " is invalid. Port should only contain digits!");
621                         }
622                     }
623
624                     try {
625                         port = Integer.parseInt(portStr);
626                     } catch (NumberFormatException JavaDoc nfe) {
627
628                         // can't happen
629
}
630                 }
631             }
632         }
633
634         setHost(host);
635         setPort(port);
636         setUserinfo(userinfo);
637     }
638
639     /**
640      * Initialize the path for this URI from a URI string spec.
641      *
642      * @param p_uriSpec the URI specification (cannot be null)
643      *
644      * @throws MalformedURIException if p_uriSpec violates syntax rules
645      */

646     private void initializePath(String JavaDoc p_uriSpec) throws MalformedURIException {
647
648         if (p_uriSpec == null) {
649             throw new MalformedURIException("Cannot initialize path from null string!");
650         }
651
652         int index = 0;
653         int start = 0;
654         int end = p_uriSpec.length();
655         char testChar = '\0';
656
657         // path - everything up to query string or fragment
658
while (index < end) {
659             testChar = p_uriSpec.charAt(index);
660
661             if (testChar == '?' || testChar == '#') {
662                 break;
663             }
664
665             // check for valid escape sequence
666
if (testChar == '%') {
667                 if (index + 2 >= end || !isHex(p_uriSpec.charAt(index + 1)) || !isHex(p_uriSpec.charAt(index + 2))) {
668                     throw new MalformedURIException("Path contains invalid escape sequence!");
669                 }
670             }
671             // TODO NOTE Thsi is removed as it was throwing exceptions against
672
// certain characters which should have been allowed.
673
// else
674
// if (!isReservedCharacter(testChar) &&
675
// !isUnreservedCharacter(testChar)) {
676
// if ('\\' != testChar) {
677
// throw new MalformedURIException("Path contains invalid character:
678
// "
679
// + testChar);
680
// }
681
// }
682

683             index++;
684         }
685
686         m_path = p_uriSpec.substring(start, index);
687
688         // query - starts with ? and up to fragment or end
689
if (testChar == '?') {
690             index++;
691
692             start = index;
693
694             while (index < end) {
695                 testChar = p_uriSpec.charAt(index);
696
697                 if (testChar == '#') {
698                     break;
699                 }
700
701                 if (testChar == '%') {
702                     if (index + 2 >= end || !isHex(p_uriSpec.charAt(index + 1)) || !isHex(p_uriSpec.charAt(index + 2))) {
703                         throw new MalformedURIException("Query string contains invalid escape sequence!");
704                     }
705                 } else if (!isReservedCharacter(testChar) && !isUnreservedCharacter(testChar)) {
706                     throw new MalformedURIException("Query string contains invalid character:" + testChar);
707                 }
708
709                 index++;
710             }
711
712             m_queryString = p_uriSpec.substring(start, index);
713         }
714
715         // fragment - starts with #
716
if (testChar == '#') {
717             index++;
718
719             start = index;
720
721             while (index < end) {
722                 testChar = p_uriSpec.charAt(index);
723
724                 if (testChar == '%') {
725                     if (index + 2 >= end || !isHex(p_uriSpec.charAt(index + 1)) || !isHex(p_uriSpec.charAt(index + 2))) {
726                         throw new MalformedURIException("Fragment contains invalid escape sequence!");
727                     }
728                 } else if (!isReservedCharacter(testChar) && !isUnreservedCharacter(testChar)) {
729                     throw new MalformedURIException("Fragment contains invalid character:" + testChar);
730                 }
731
732                 index++;
733             }
734
735             m_fragment = p_uriSpec.substring(start, index);
736         }
737     }
738
739     /**
740      * Get the scheme for this URI.
741      *
742      * @return the scheme for this URI
743      */

744     public String JavaDoc getScheme() {
745         return m_scheme;
746     }
747
748     /**
749      * Get the scheme-specific part for this URI (everything following the
750      * scheme and the first colon). See RFC 2396 Section 5.2 for spec.
751      *
752      * @return the scheme-specific part for this URI
753      */

754     public String JavaDoc getSchemeSpecificPart() {
755
756         StringBuffer JavaDoc schemespec = new StringBuffer JavaDoc();
757
758         if (m_userinfo != null || m_host != null || m_port != -1) {
759             schemespec.append("//");
760         }
761
762         if (m_userinfo != null) {
763             schemespec.append(m_userinfo);
764             schemespec.append('@');
765         }
766
767         if (m_host != null) {
768             schemespec.append(m_host);
769         }
770
771         if (m_port != -1) {
772             schemespec.append(':');
773             schemespec.append(m_port);
774         }
775
776         if (m_path != null) {
777             schemespec.append((m_path));
778         }
779
780         if (m_queryString != null) {
781             schemespec.append('?');
782             schemespec.append(m_queryString);
783         }
784
785         if (m_fragment != null) {
786             schemespec.append('#');
787             schemespec.append(m_fragment);
788         }
789
790         return schemespec.toString();
791     }
792
793     public String JavaDoc getSchemeSpecificPartEncoded() {
794
795         StringBuffer JavaDoc schemespec = new StringBuffer JavaDoc();
796
797         if (m_userinfo != null || m_host != null || m_port != -1) {
798             schemespec.append("//");
799         }
800
801         if (m_userinfo != null) {
802             schemespec.append(m_userinfo);
803             schemespec.append('@');
804         }
805
806         if (m_host != null) {
807             schemespec.append(m_host);
808         }
809
810         if (m_port != -1) {
811             schemespec.append(':');
812             schemespec.append(m_port);
813         }
814
815         if (m_path != null) {
816             schemespec.append((m_path.replaceAll(" ", "%20")));
817         }
818
819         if (m_queryString != null) {
820             schemespec.append('?');
821             schemespec.append(m_queryString);
822         }
823
824         if (m_fragment != null) {
825             schemespec.append('#');
826             schemespec.append(m_fragment);
827         }
828
829         return schemespec.toString();
830     }
831
832     /**
833      * Get the userinfo for this URI.
834      *
835      * @return the userinfo for this URI (null if not specified).
836      */

837     public String JavaDoc getUserinfo() {
838         return m_userinfo;
839     }
840
841     /**
842      * Get the host for this URI.
843      *
844      * @return the host for this URI (null if not specified).
845      */

846     public String JavaDoc getHost() {
847         return m_host;
848     }
849
850     /**
851      * Get the port for this URI.
852      *
853      * @return the port for this URI (-1 if not specified).
854      */

855     public int getPort() {
856         return m_port;
857     }
858
859     /**
860      * Get the path for this URI (optionally with the query string and
861      * fragment).
862      *
863      * @param p_includeQueryString if true (and query string is not null), then
864      * a "?" followed by the query string will be appended
865      * @param p_includeFragment if true (and fragment is not null), then a "#"
866      * followed by the fragment will be appended
867      *
868      * @return the path for this URI possibly including the query string and
869      * fragment
870      */

871     public String JavaDoc getPath(boolean p_includeQueryString, boolean p_includeFragment) {
872
873         StringBuffer JavaDoc pathString = new StringBuffer JavaDoc(m_path);
874
875         if (p_includeQueryString && m_queryString != null) {
876             pathString.append('?');
877             pathString.append(m_queryString);
878         }
879
880         if (p_includeFragment && m_fragment != null) {
881             pathString.append('#');
882             pathString.append(m_fragment);
883         }
884
885         return pathString.toString();
886     }
887
888     /**
889      * Get the path for this URI. Note that the value returned is the path only
890      * and does not include the query string or fragment.
891      *
892      * @return the path for this URI.
893      */

894     public String JavaDoc getPath() {
895         return m_path;
896     }
897
898     /**
899      * Get the query string for this URI.
900      *
901      * @return the query string for this URI. Null is returned if there was no
902      * "?" in the URI spec, empty string if there was a "?" but no query
903      * string following it.
904      */

905     public String JavaDoc getQueryString() {
906         return m_queryString;
907     }
908
909     /**
910      * Get the fragment for this URI.
911      *
912      * @return the fragment for this URI. Null is returned if there was no "#"
913      * in the URI spec, empty string if there was a "#" but no fragment
914      * following it.
915      */

916     public String JavaDoc getFragment() {
917         return m_fragment;
918     }
919
920     /**
921      * Set the scheme for this URI. The scheme is converted to lowercase before
922      * it is set.
923      *
924      * @param p_scheme the scheme for this URI (cannot be null)
925      *
926      * @throws MalformedURIException if p_scheme is not a conformant scheme name
927      */

928     public void setScheme(String JavaDoc p_scheme) throws MalformedURIException {
929
930         if (p_scheme == null) {
931             throw new MalformedURIException("Cannot set scheme from null string!");
932         }
933
934         if (!isConformantSchemeName(p_scheme)) {
935             throw new MalformedURIException("The scheme is not conformant.");
936         }
937
938         m_scheme = p_scheme.toLowerCase();
939     }
940
941     /**
942      * Set the userinfo for this URI. If a non-null value is passed in and the
943      * host value is null, then an exception is thrown.
944      *
945      * @param p_userinfo the userinfo for this URI
946      *
947      * @throws MalformedURIException if p_userinfo contains invalid characters
948      */

949     public void setUserinfo(String JavaDoc p_userinfo) throws MalformedURIException {
950
951         if (p_userinfo == null) {
952             m_userinfo = null;
953         } else {
954             if (m_host == null) {
955                 throw new MalformedURIException("Userinfo cannot be set when host is null!");
956             }
957
958             // userinfo can contain alphanumerics, mark characters, escaped
959
// and ';',':','&','=','+','$',','
960
int index = 0;
961             int end = p_userinfo.length();
962             char testChar = '\0';
963
964             while (index < end) {
965                 testChar = p_userinfo.charAt(index);
966
967                 if (testChar == '%') {
968                     if (index + 2 >= end || !isHex(p_userinfo.charAt(index + 1)) || !isHex(p_userinfo.charAt(index + 2))) {
969                         throw new MalformedURIException("Userinfo contains invalid escape sequence!");
970                     }
971                 } else if (!isUnreservedCharacter(testChar) && USERINFO_CHARACTERS.indexOf(testChar) == -1) {
972                     throw new MalformedURIException("Userinfo contains invalid character:" + testChar);
973                 }
974
975                 index++;
976             }
977         }
978
979         m_userinfo = p_userinfo;
980     }
981
982     /**
983      * Set the host for this URI. If null is passed in, the userinfo field is
984      * also set to null and the port is set to -1.
985      *
986      * @param p_host the host for this URI
987      *
988      * @throws MalformedURIException if p_host is not a valid IP address or DNS
989      * hostname.
990      */

991     public void setHost(String JavaDoc p_host) throws MalformedURIException {
992
993         if (p_host == null || p_host.trim().length() == 0) {
994             m_host = p_host;
995             m_userinfo = null;
996             m_port = -1;
997         } else if (!isWellFormedAddress(p_host)) {
998             throw new MalformedURIException("Host is not a well formed address!");
999         }
1000
1001        m_host = p_host;
1002    }
1003
1004    /**
1005     * Set the port for this URI. -1 is used to indicate that the port is not
1006     * specified, otherwise valid port numbers are between 0 and 65535. If a
1007     * valid port number is passed in and the host field is null, an exception
1008     * is thrown.
1009     *
1010     * @param p_port the port number for this URI
1011     *
1012     * @throws MalformedURIException if p_port is not -1 and not a valid port
1013     * number
1014     */

1015    public void setPort(int p_port) throws MalformedURIException {
1016
1017        if (p_port >= 0 && p_port <= 65535) {
1018            if (m_host == null) {
1019                throw new MalformedURIException("Port cannot be set when host is null!");
1020            }
1021        } else if (p_port != -1) {
1022            throw new MalformedURIException("Invalid port number!");
1023        }
1024
1025        m_port = p_port;
1026    }
1027
1028    /**
1029     * Set the path for this URI. If the supplied path is null, then the query
1030     * string and fragment are set to null as well. If the supplied path
1031     * includes a query string and/or fragment, these fields will be parsed and
1032     * set as well. Note that, for URIs following the "generic URI" syntax, the
1033     * path specified should start with a slash. For URIs that do not follow the
1034     * generic URI syntax, this method sets the scheme-specific part.
1035     *
1036     * @param p_path the path for this URI (may be null)
1037     *
1038     * @throws MalformedURIException if p_path contains invalid characters
1039     */

1040    public void setPath(String JavaDoc p_path) throws MalformedURIException {
1041
1042        if (p_path == null) {
1043            m_path = null;
1044            m_queryString = null;
1045            m_fragment = null;
1046        } else {
1047            initializePath(p_path);
1048        }
1049    }
1050
1051    /**
1052     * Append to the end of the path of this URI. If the current path does not
1053     * end in a slash and the path to be appended does not begin with a slash, a
1054     * slash will be appended to the current path before the new segment is
1055     * added. Also, if the current path ends in a slash and the new segment
1056     * begins with a slash, the extra slash will be removed before the new
1057     * segment is appended.
1058     *
1059     * @param p_addToPath the new segment to be added to the current path
1060     *
1061     * @throws MalformedURIException if p_addToPath contains syntax errors
1062     */

1063    public void appendPath(String JavaDoc p_addToPath) throws MalformedURIException {
1064
1065        if (p_addToPath == null || p_addToPath.trim().length() == 0) {
1066            return;
1067        }
1068
1069        if (!isURIString(p_addToPath)) {
1070            throw new MalformedURIException("Path contains invalid character!");
1071        }
1072
1073        if (m_path == null || m_path.trim().length() == 0) {
1074            if (p_addToPath.startsWith("/")) {
1075                m_path = p_addToPath;
1076            } else {
1077                m_path = "/" + p_addToPath;
1078            }
1079        } else if (m_path.endsWith("/")) {
1080            if (p_addToPath.startsWith("/")) {
1081                m_path = m_path.concat(p_addToPath.substring(1));
1082            } else {
1083                m_path = m_path.concat(p_addToPath);
1084            }
1085        } else {
1086            if (p_addToPath.startsWith("/")) {
1087                m_path = m_path.concat(p_addToPath);
1088            } else {
1089                m_path = m_path.concat("/" + p_addToPath);
1090            }
1091        }
1092    }
1093
1094    /**
1095     * Set the query string for this URI. A non-null value is valid only if this
1096     * is an URI conforming to the generic URI syntax and the path value is not
1097     * null.
1098     *
1099     * @param p_queryString the query string for this URI
1100     *
1101     * @throws MalformedURIException if p_queryString is not null and this URI
1102     * does not conform to the generic URI syntax or if the path is null
1103     */

1104    public void setQueryString(String JavaDoc p_queryString) throws MalformedURIException {
1105
1106        if (p_queryString == null) {
1107            m_queryString = null;
1108        } else if (!isGenericURI()) {
1109            throw new MalformedURIException("Query string can only be set for a generic URI!");
1110        } else if (getPath() == null) {
1111            throw new MalformedURIException("Query string cannot be set when path is null!");
1112        } else if (!isURIString(p_queryString)) {
1113            throw new MalformedURIException("Query string contains invalid character!");
1114        } else {
1115            m_queryString = p_queryString;
1116        }
1117    }
1118
1119    /**
1120     * Set the fragment for this URI. A non-null value is valid only if this is
1121     * a URI conforming to the generic URI syntax and the path value is not
1122     * null.
1123     *
1124     * @param p_fragment the fragment for this URI
1125     *
1126     * @throws MalformedURIException if p_fragment is not null and this URI does
1127     * not conform to the generic URI syntax or if the path is null
1128     */

1129    public void setFragment(String JavaDoc p_fragment) throws MalformedURIException {
1130
1131        if (p_fragment == null) {
1132            m_fragment = null;
1133        } else if (!isGenericURI()) {
1134            throw new MalformedURIException("Fragment can only be set for a generic URI!");
1135        } else if (getPath() == null) {
1136            throw new MalformedURIException("Fragment cannot be set when path is null!");
1137        } else if (!isURIString(p_fragment)) {
1138            throw new MalformedURIException("Fragment contains invalid character!");
1139        } else {
1140            m_fragment = p_fragment;
1141        }
1142    }
1143
1144    /**
1145     * Determines if the passed-in Object is equivalent to this URI.
1146     *
1147     * @param p_test the Object to test for equality.
1148     *
1149     * @return true if p_test is a URI with all values equal to this URI, false
1150     * otherwise
1151     */

1152    public boolean equals(Object JavaDoc p_test) {
1153
1154        if (p_test instanceof URI) {
1155            URI testURI = (URI) p_test;
1156
1157            if (((m_scheme == null && testURI.m_scheme == null) || (m_scheme != null && testURI.m_scheme != null && m_scheme
1158                            .equals(testURI.m_scheme)))
1159                            && ((m_userinfo == null && testURI.m_userinfo == null) || (m_userinfo != null
1160                                            && testURI.m_userinfo != null && m_userinfo.equals(testURI.m_userinfo)))
1161                            && ((m_host == null && testURI.m_host == null) || (m_host != null && testURI.m_host != null && m_host
1162                                            .equals(testURI.m_host)))
1163                            && m_port == testURI.m_port
1164                            && ((m_path == null && testURI.m_path == null) || (m_path != null && testURI.m_path != null && m_path
1165                                            .equals(testURI.m_path)))
1166                            && ((m_queryString == null && testURI.m_queryString == null) || (m_queryString != null
1167                                            && testURI.m_queryString != null && m_queryString.equals(testURI.m_queryString)))
1168                            && ((m_fragment == null && testURI.m_fragment == null) || (m_fragment != null
1169                                            && testURI.m_fragment != null && m_fragment.equals(testURI.m_fragment)))) {
1170                return true;
1171            }
1172        }
1173
1174        return false;
1175    }
1176
1177    /**
1178     * Get the URI as a string specification. See RFC 2396 Section 5.2.
1179     *
1180     * @return the URI string specification
1181     */

1182    public String JavaDoc toString() {
1183
1184        StringBuffer JavaDoc uriSpecString = new StringBuffer JavaDoc();
1185
1186        if (m_scheme != null) {
1187            uriSpecString.append(m_scheme);
1188            uriSpecString.append(':');
1189        }
1190
1191        uriSpecString.append(getSchemeSpecificPart());
1192
1193        return uriSpecString.toString();
1194    }
1195
1196    public String JavaDoc toExternalForm() {
1197
1198        StringBuffer JavaDoc uriSpecString = new StringBuffer JavaDoc();
1199
1200        if (m_scheme != null) {
1201            uriSpecString.append(m_scheme);
1202            uriSpecString.append(':');
1203        }
1204
1205        uriSpecString.append(getSchemeSpecificPartEncoded());
1206
1207        return uriSpecString.toString();
1208    }
1209
1210    /**
1211     * Get the indicator as to whether this URI uses the "generic URI" syntax.
1212     *
1213     * @return true if this URI uses the "generic URI" syntax, false otherwise
1214     */

1215    public boolean isGenericURI() {
1216
1217        // presence of the host (whether valid or empty) means
1218
// double-slashes which means generic uri
1219
return (m_host != null);
1220    }
1221
1222    /**
1223     * Determine whether a scheme conforms to the rules for a scheme name. A
1224     * scheme is conformant if it starts with an alphanumeric, and contains only
1225     * alphanumerics, '+','-' and '.'.
1226     *
1227     * @param p_scheme The sheme name to check
1228     * @return true if the scheme is conformant, false otherwise
1229     */

1230    public static boolean isConformantSchemeName(String JavaDoc p_scheme) {
1231
1232        if (p_scheme == null || p_scheme.trim().length() == 0) {
1233            return false;
1234        }
1235
1236        if (!isAlpha(p_scheme.charAt(0))) {
1237            return false;
1238        }
1239
1240        char testChar;
1241
1242        for (int i = 1; i < p_scheme.length(); i++) {
1243            testChar = p_scheme.charAt(i);
1244
1245            if (!isAlphanum(testChar) && SCHEME_CHARACTERS.indexOf(testChar) == -1) {
1246                return false;
1247            }
1248        }
1249
1250        return true;
1251    }
1252
1253    /**
1254     * Determine whether a string is syntactically capable of representing a
1255     * valid IPv4 address or the domain name of a network host. A valid IPv4
1256     * address consists of four decimal digit groups separated by a '.'. A
1257     * hostname consists of domain labels (each of which must begin and end with
1258     * an alphanumeric but may contain '-') separated & by a '.'. See RFC 2396
1259     * Section 3.2.2.
1260     *
1261     * @param p_address The address string to check
1262     * @return true if the string is a syntactically valid IPv4 address or
1263     * hostname
1264     */

1265    public static boolean isWellFormedAddress(String JavaDoc p_address) {
1266
1267        if (p_address == null) {
1268            return false;
1269        }
1270
1271        String JavaDoc address = p_address.trim();
1272        int addrLength = address.length();
1273
1274        if (addrLength == 0 || addrLength > 255) {
1275            return false;
1276        }
1277
1278        if (address.startsWith(".") || address.startsWith("-")) {
1279            return false;
1280        }
1281
1282        // rightmost domain label starting with digit indicates IP address
1283
// since top level domain label can only start with an alpha
1284
// see RFC 2396 Section 3.2.2
1285
int index = address.lastIndexOf('.');
1286
1287        if (address.endsWith(".")) {
1288            index = address.substring(0, index).lastIndexOf('.');
1289        }
1290
1291        if (index + 1 < addrLength && isDigit(p_address.charAt(index + 1))) {
1292            char testChar;
1293            int numDots = 0;
1294
1295            // make sure that 1) we see only digits and dot separators, 2) that
1296
// any dot separator is preceded and followed by a digit and
1297
// 3) that we find 3 dots
1298
for (int i = 0; i < addrLength; i++) {
1299                testChar = address.charAt(i);
1300
1301                if (testChar == '.') {
1302                    if (!isDigit(address.charAt(i - 1)) || (i + 1 < addrLength && !isDigit(address.charAt(i + 1)))) {
1303                        return false;
1304                    }
1305
1306                    numDots++;
1307                } else if (!isDigit(testChar)) {
1308                    return false;
1309                }
1310            }
1311
1312            if (numDots != 3) {
1313                return false;
1314            }
1315        } else {
1316
1317            // domain labels can contain alphanumerics and '-"
1318
// but must start and end with an alphanumeric
1319
char testChar;
1320
1321            for (int i = 0; i < addrLength; i++) {
1322                testChar = address.charAt(i);
1323
1324                if (testChar == '.') {
1325                    if (!isAlphanum(address.charAt(i - 1))) {
1326                        return false;
1327                    }
1328
1329                    if (i + 1 < addrLength && !isAlphanum(address.charAt(i + 1))) {
1330                        return false;
1331                    }
1332                } else if (!isAlphanum(testChar) && testChar != '-') {
1333                    return false;
1334                }
1335            }
1336        }
1337
1338        return true;
1339    }
1340
1341    /**
1342     * Determine whether a char is a digit.
1343     *
1344     * @param p_char the character to check
1345     * @return true if the char is betweeen '0' and '9', false otherwise
1346     */

1347    private static boolean isDigit(char p_char) {
1348        return p_char >= '0' && p_char <= '9';
1349    }
1350
1351    /**
1352     * Determine whether a character is a hexadecimal character.
1353     *
1354     * @param p_char the character to check
1355     * @return true if the char is betweeen '0' and '9', 'a' and 'f' or 'A' and
1356     * 'F', false otherwise
1357     */

1358    private static boolean isHex(char p_char) {
1359        return (isDigit(p_char) || (p_char >= 'a' && p_char <= 'f') || (p_char >= 'A' && p_char <= 'F'));
1360    }
1361
1362    /**
1363     * Determine whether a char is an alphabetic character: a-z or A-Z
1364     *
1365     * @param p_char the character to check
1366     * @return true if the char is alphabetic, false otherwise
1367     */

1368    private static boolean isAlpha(char p_char) {
1369        return ((p_char >= 'a' && p_char <= 'z') || (p_char >= 'A' && p_char <= 'Z'));
1370    }
1371
1372    /**
1373     * Determine whether a char is an alphanumeric: 0-9, a-z or A-Z
1374     *
1375     * @param p_char the character to check
1376     * @return true if the char is alphanumeric, false otherwise
1377     */

1378    private static boolean isAlphanum(char p_char) {
1379        return (isAlpha(p_char) || isDigit(p_char));
1380    }
1381
1382    /**
1383     * Determine whether a character is a reserved character: ';', '/', '?',
1384     * ':', '@', '&', '=', '+', '$' or ','
1385     *
1386     * @param p_char the character to check
1387     * @return true if the string contains any reserved characters
1388     */

1389    private static boolean isReservedCharacter(char p_char) {
1390        return RESERVED_CHARACTERS.indexOf(p_char) != -1;
1391    }
1392
1393    /**
1394     * Determine whether a char is an unreserved character.
1395     *
1396     * @param p_char the character to check
1397     * @return true if the char is unreserved, false otherwise
1398     */

1399    private static boolean isUnreservedCharacter(char p_char) {
1400        return (isAlphanum(p_char) || MARK_CHARACTERS.indexOf(p_char) != -1);
1401    }
1402
1403    /**
1404     * Determine whether a given string contains only URI characters (also
1405     * called "uric" in RFC 2396). uric consist of all reserved characters,
1406     * unreserved characters and escaped characters.
1407     *
1408     * @param p_uric URI string
1409     * @return true if the string is comprised of uric, false otherwise
1410     */

1411    private static boolean isURIString(String JavaDoc p_uric) {
1412
1413        if (p_uric == null) {
1414            return false;
1415        }
1416
1417        int end = p_uric.length();
1418        char testChar = '\0';
1419
1420        for (int i = 0; i < end; i++) {
1421            testChar = p_uric.charAt(i);
1422
1423            if (testChar == '%') {
1424                if (i + 2 >= end || !isHex(p_uric.charAt(i + 1)) || !isHex(p_uric.charAt(i + 2))) {
1425                    return false;
1426                } else {
1427                    i += 2;
1428
1429                    continue;
1430                }
1431            }
1432
1433            if (isReservedCharacter(testChar) || isUnreservedCharacter(testChar)) {
1434                continue;
1435            } else {
1436                return false;
1437            }
1438        }
1439
1440        return true;
1441    }
1442}
1443
Popular Tags