KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > apache > xerces > utils > URI


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

56
57 package org.enhydra.apache.xerces.utils;
58
59 import java.io.IOException JavaDoc;
60 import java.io.Serializable JavaDoc;
61
62 /**********************************************************************
63 * A class to represent a Uniform Resource Identifier (URI). This class
64 * is designed to handle the parsing of URIs and provide access to
65 * the various components (scheme, host, port, userinfo, path, query
66 * string and fragment) that may constitute a URI.
67 * <p>
68 * Parsing of a URI specification is done according to the URI
69 * syntax described in RFC 2396
70 * <http://www.ietf.org/rfc/rfc2396.txt?number=2396>. Every URI consists
71 * of a scheme, followed by a colon (':'), followed by a scheme-specific
72 * part. For URIs that follow the "generic URI" syntax, the scheme-
73 * specific part begins with two slashes ("//") and may be followed
74 * by an authority segment (comprised of user information, host, and
75 * port), path segment, query segment and fragment. Note that RFC 2396
76 * no longer specifies the use of the parameters segment and excludes
77 * the "user:password" syntax as part of the authority segment. If
78 * "user:password" appears in a URI, the entire user/password string
79 * is stored as userinfo.
80 * <p>
81 * For URIs that do not follow the "generic URI" syntax (e.g. mailto),
82 * the entire scheme-specific part is treated as the "path" portion
83 * of the URI.
84 * <p>
85 * Note that, unlike the java.net.URL class, this class does not provide
86 * any built-in network access functionality nor does it provide any
87 * scheme-specific functionality (for example, it does not know a
88 * default port for a specific scheme). Rather, it only knows the
89 * grammar and basic set of operations that can be applied to a URI.
90 *
91 * @version $Id: URI.java,v 1.1.1.1 2003/03/10 16:34:40 taweili Exp $
92 *
93 **********************************************************************/

94  public class URI implements Serializable JavaDoc {
95
96   /*******************************************************************
97   * MalformedURIExceptions are thrown in the process of building a URI
98   * or setting fields on a URI when an operation would result in an
99   * invalid URI specification.
100   *
101   ********************************************************************/

102   public static class MalformedURIException extends IOException JavaDoc {
103
104    /******************************************************************
105     * Constructs a <code>MalformedURIException</code> with no specified
106     * detail message.
107     ******************************************************************/

108     public MalformedURIException() {
109       super();
110     }
111
112     /*****************************************************************
113     * Constructs a <code>MalformedURIException</code> with the
114     * specified detail message.
115     *
116     * @param p_msg the detail message.
117     ******************************************************************/

118     public MalformedURIException(String JavaDoc p_msg) {
119       super(p_msg);
120     }
121   }
122
123   /** reserved characters */
124   private static final String JavaDoc RESERVED_CHARACTERS = ";/?:@&=+$,";
125
126   /** URI punctuation mark characters - these, combined with
127       alphanumerics, constitute the "unreserved" characters */

128   private static final String JavaDoc MARK_CHARACTERS = "-_.!~*'() ";
129
130   /** scheme can be composed of alphanumerics and these characters */
131   private static final String JavaDoc SCHEME_CHARACTERS = "+-.";
132
133   /** userinfo can be composed of unreserved, escaped and these
134       characters */

135   private static final String JavaDoc USERINFO_CHARACTERS = ";:&=+$,";
136
137   /** Stores the scheme (usually the protocol) for this URI. */
138   private String JavaDoc m_scheme = null;
139
140   /** If specified, stores the userinfo for this URI; otherwise null */
141   private String JavaDoc m_userinfo = null;
142
143   /** If specified, stores the host for this URI; otherwise null */
144   private String JavaDoc m_host = null;
145
146   /** If specified, stores the port for this URI; otherwise -1 */
147   private int m_port = -1;
148
149   /** If specified, stores the path for this URI; otherwise null */
150   private String JavaDoc m_path = null;
151
152   /** If specified, stores the query string for this URI; otherwise
153       null. */

154   private String JavaDoc m_queryString = null;
155
156   /** If specified, stores the fragment for this URI; otherwise null */
157   private String JavaDoc m_fragment = null;
158
159   private static boolean DEBUG = false;
160
161   /**
162   * Construct a new and uninitialized URI.
163   */

164   public URI() {
165   }
166
167  /**
168   * Construct a new URI from another URI. All fields for this URI are
169   * set equal to the fields of the URI passed in.
170   *
171   * @param p_other the URI to copy (cannot be null)
172   */

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

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

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

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

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

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

336   private void initialize(URI p_other) {
337     m_scheme = p_other.getScheme();
338     m_userinfo = p_other.getUserinfo();
339     m_host = p_other.getHost();
340     m_port = p_other.getPort();
341     m_path = p_other.getPath();
342     m_queryString = p_other.getQueryString();
343     m_fragment = p_other.getFragment();
344   }
345
346  /**
347   * Initializes this URI from a base URI and a URI specification string.
348   * See RFC 2396 Section 4 and Appendix B for specifications on parsing
349   * the URI and Section 5 for specifications on resolving relative URIs
350   * and relative paths.
351   *
352   * @param p_base the base URI (may be null if p_uriSpec is an absolute
353   * URI)
354   * @param p_uriSpec the URI spec string which may be an absolute or
355   * relative URI (can only be null/empty if p_base
356   * is not null)
357   *
358   * @exception MalformedURIException if p_base is null and p_uriSpec
359   * is not an absolute URI or if
360   * p_uriSpec violates syntax rules
361   */

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

548   private void initializeScheme(String JavaDoc p_uriSpec)
549                  throws MalformedURIException {
550     int uriSpecLen = p_uriSpec.length();
551     int index = 0;
552     String JavaDoc scheme = null;
553     char testChar = '\0';
554
555     while (index < uriSpecLen) {
556       testChar = p_uriSpec.charAt(index);
557       if (testChar == ':' || testChar == '/' ||
558           testChar == '?' || testChar == '#') {
559         break;
560       }
561       index++;
562     }
563     scheme = p_uriSpec.substring(0, index);
564
565     if (scheme.length() == 0) {
566       throw new MalformedURIException("No scheme found in URI.");
567     }
568     else {
569       setScheme(scheme);
570     }
571   }
572
573  /**
574   * Initialize the authority (userinfo, host and port) for this
575   * URI from a URI string spec.
576   *
577   * @param p_uriSpec the URI specification (cannot be null)
578   *
579   * @exception MalformedURIException if p_uriSpec violates syntax rules
580   */

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

652   private void initializePath(String JavaDoc p_uriSpec)
653                  throws MalformedURIException {
654     if (p_uriSpec == null) {
655       throw new MalformedURIException(
656                 "Cannot initialize path from null string!");
657     }
658
659     int index = 0;
660     int start = 0;
661     int end = p_uriSpec.length();
662     char testChar = '\0';
663
664     // path - everything up to query string or fragment
665
while (index < end) {
666       testChar = p_uriSpec.charAt(index);
667       if (testChar == '?' || testChar == '#') {
668         break;
669       }
670       // check for valid escape sequence
671
if (testChar == '%') {
672          if (index+2 >= end ||
673             !isHex(p_uriSpec.charAt(index+1)) ||
674             !isHex(p_uriSpec.charAt(index+2))) {
675           throw new MalformedURIException(
676                 "Path contains invalid escape sequence!");
677          }
678       }
679       else if (!isReservedCharacter(testChar) &&
680                !isUnreservedCharacter(testChar)) {
681         throw new MalformedURIException(
682                   "Path contains invalid character: " + testChar);
683       }
684       index++;
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       start = index;
692       while (index < end) {
693         testChar = p_uriSpec.charAt(index);
694         if (testChar == '#') {
695           break;
696         }
697         if (testChar == '%') {
698            if (index+2 >= end ||
699               !isHex(p_uriSpec.charAt(index+1)) ||
700               !isHex(p_uriSpec.charAt(index+2))) {
701             throw new MalformedURIException(
702                     "Query string contains invalid escape sequence!");
703            }
704         }
705         else if (!isReservedCharacter(testChar) &&
706                  !isUnreservedCharacter(testChar)) {
707           throw new MalformedURIException(
708                 "Query string contains invalid character:" + testChar);
709         }
710         index++;
711       }
712       m_queryString = p_uriSpec.substring(start, index);
713     }
714
715     // fragment - starts with #
716
if (testChar == '#') {
717       index++;
718       start = index;
719       while (index < end) {
720         testChar = p_uriSpec.charAt(index);
721
722         if (testChar == '%') {
723            if (index+2 >= end ||
724               !isHex(p_uriSpec.charAt(index+1)) ||
725               !isHex(p_uriSpec.charAt(index+2))) {
726             throw new MalformedURIException(
727                     "Fragment contains invalid escape sequence!");
728            }
729         }
730         else if (!isReservedCharacter(testChar) &&
731                  !isUnreservedCharacter(testChar)) {
732           throw new MalformedURIException(
733                 "Fragment contains invalid character:"+testChar);
734         }
735         index++;
736       }
737       m_fragment = p_uriSpec.substring(start, index);
738     }
739   }
740
741  /**
742   * Get the scheme for this URI.
743   *
744   * @return the scheme for this URI
745   */

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

756   public String JavaDoc getSchemeSpecificPart() {
757     StringBuffer JavaDoc schemespec = new StringBuffer JavaDoc();
758
759     if (m_userinfo != null || m_host != null || m_port != -1) {
760       schemespec.append("//");
761     }
762
763     if (m_userinfo != null) {
764       schemespec.append(m_userinfo);
765       schemespec.append('@');
766     }
767
768     if (m_host != null) {
769       schemespec.append(m_host);
770     }
771
772     if (m_port != -1) {
773       schemespec.append(':');
774       schemespec.append(m_port);
775     }
776
777     if (m_path != null) {
778       schemespec.append((m_path));
779     }
780
781     if (m_queryString != null) {
782       schemespec.append('?');
783       schemespec.append(m_queryString);
784     }
785
786     if (m_fragment != null) {
787       schemespec.append('#');
788       schemespec.append(m_fragment);
789     }
790
791     return schemespec.toString();
792   }
793
794  /**
795   * Get the userinfo for this URI.
796   *
797   * @return the userinfo for this URI (null if not specified).
798   */

799   public String JavaDoc getUserinfo() {
800     return m_userinfo;
801   }
802
803   /**
804   * Get the host for this URI.
805   *
806   * @return the host for this URI (null if not specified).
807   */

808   public String JavaDoc getHost() {
809     return m_host;
810   }
811
812  /**
813   * Get the port for this URI.
814   *
815   * @return the port for this URI (-1 if not specified).
816   */

817   public int getPort() {
818     return m_port;
819   }
820
821  /**
822   * Get the path for this URI (optionally with the query string and
823   * fragment).
824   *
825   * @param p_includeQueryString if true (and query string is not null),
826   * then a "?" followed by the query string
827   * will be appended
828   * @param p_includeFragment if true (and fragment is not null),
829   * then a "#" followed by the fragment
830   * will be appended
831   *
832   * @return the path for this URI possibly including the query string
833   * and fragment
834   */

835   public String JavaDoc getPath(boolean p_includeQueryString,
836                         boolean p_includeFragment) {
837     StringBuffer JavaDoc pathString = new StringBuffer JavaDoc(m_path);
838
839     if (p_includeQueryString && m_queryString != null) {
840       pathString.append('?');
841       pathString.append(m_queryString);
842     }
843
844     if (p_includeFragment && m_fragment != null) {
845       pathString.append('#');
846       pathString.append(m_fragment);
847     }
848     return pathString.toString();
849   }
850
851  /**
852   * Get the path for this URI. Note that the value returned is the path
853   * only and does not include the query string or fragment.
854   *
855   * @return the path for this URI.
856   */

857   public String JavaDoc getPath() {
858     return m_path;
859   }
860
861  /**
862   * Get the query string for this URI.
863   *
864   * @return the query string for this URI. Null is returned if there
865   * was no "?" in the URI spec, empty string if there was a
866   * "?" but no query string following it.
867   */

868   public String JavaDoc getQueryString() {
869     return m_queryString;
870   }
871
872  /**
873   * Get the fragment for this URI.
874   *
875   * @return the fragment for this URI. Null is returned if there
876   * was no "#" in the URI spec, empty string if there was a
877   * "#" but no fragment following it.
878   */

879   public String JavaDoc getFragment() {
880     return m_fragment;
881   }
882
883  /**
884   * Set the scheme for this URI. The scheme is converted to lowercase
885   * before it is set.
886   *
887   * @param p_scheme the scheme for this URI (cannot be null)
888   *
889   * @exception MalformedURIException if p_scheme is not a conformant
890   * scheme name
891   */

892   public void setScheme(String JavaDoc p_scheme) throws MalformedURIException {
893     if (p_scheme == null) {
894       throw new MalformedURIException(
895                 "Cannot set scheme from null string!");
896     }
897     if (!isConformantSchemeName(p_scheme)) {
898       throw new MalformedURIException("The scheme is not conformant.");
899     }
900
901     m_scheme = p_scheme.toLowerCase();
902   }
903
904  /**
905   * Set the userinfo for this URI. If a non-null value is passed in and
906   * the host value is null, then an exception is thrown.
907   *
908   * @param p_userinfo the userinfo for this URI
909   *
910   * @exception MalformedURIException if p_userinfo contains invalid
911   * characters
912   */

913   public void setUserinfo(String JavaDoc p_userinfo) throws MalformedURIException {
914     if (p_userinfo == null) {
915       m_userinfo = null;
916     }
917     else {
918       if (m_host == null) {
919         throw new MalformedURIException(
920                      "Userinfo cannot be set when host is null!");
921       }
922
923       // userinfo can contain alphanumerics, mark characters, escaped
924
// and ';',':','&','=','+','$',','
925
int index = 0;
926       int end = p_userinfo.length();
927       char testChar = '\0';
928       while (index < end) {
929         testChar = p_userinfo.charAt(index);
930         if (testChar == '%') {
931           if (index+2 >= end ||
932               !isHex(p_userinfo.charAt(index+1)) ||
933               !isHex(p_userinfo.charAt(index+2))) {
934             throw new MalformedURIException(
935                   "Userinfo contains invalid escape sequence!");
936           }
937         }
938         else if (!isUnreservedCharacter(testChar) &&
939                  USERINFO_CHARACTERS.indexOf(testChar) == -1) {
940           throw new MalformedURIException(
941                   "Userinfo contains invalid character:"+testChar);
942         }
943         index++;
944       }
945     }
946     m_userinfo = p_userinfo;
947   }
948
949   /**
950   * Set the host for this URI. If null is passed in, the userinfo
951   * field is also set to null and the port is set to -1.
952   *
953   * @param p_host the host for this URI
954   *
955   * @exception MalformedURIException if p_host is not a valid IP
956   * address or DNS hostname.
957   */

958   public void setHost(String JavaDoc p_host) throws MalformedURIException {
959     if (p_host == null || p_host.trim().length() == 0) {
960       m_host = p_host;
961       m_userinfo = null;
962       m_port = -1;
963     }
964     else if (!isWellFormedAddress(p_host)) {
965       throw new MalformedURIException("Host is not a well formed address!");
966     }
967     m_host = p_host;
968   }
969
970  /**
971   * Set the port for this URI. -1 is used to indicate that the port is
972   * not specified, otherwise valid port numbers are between 0 and 65535.
973   * If a valid port number is passed in and the host field is null,
974   * an exception is thrown.
975   *
976   * @param p_port the port number for this URI
977   *
978   * @exception MalformedURIException if p_port is not -1 and not a
979   * valid port number
980   */

981   public void setPort(int p_port) throws MalformedURIException {
982     if (p_port >= 0 && p_port <= 65535) {
983       if (m_host == null) {
984         throw new MalformedURIException(
985                       "Port cannot be set when host is null!");
986       }
987     }
988     else if (p_port != -1) {
989       throw new MalformedURIException("Invalid port number!");
990     }
991     m_port = p_port;
992   }
993
994  /**
995   * Set the path for this URI. If the supplied path is null, then the
996   * query string and fragment are set to null as well. If the supplied
997   * path includes a query string and/or fragment, these fields will be
998   * parsed and set as well. Note that, for URIs following the "generic
999   * URI" syntax, the path specified should start with a slash.
1000  * For URIs that do not follow the generic URI syntax, this method
1001  * sets the scheme-specific part.
1002  *
1003  * @param p_path the path for this URI (may be null)
1004  *
1005  * @exception MalformedURIException if p_path contains invalid
1006  * characters
1007  */

1008  public void setPath(String JavaDoc p_path) throws MalformedURIException {
1009    if (p_path == null) {
1010      m_path = null;
1011      m_queryString = null;
1012      m_fragment = null;
1013    }
1014    else {
1015      initializePath(p_path);
1016    }
1017  }
1018
1019 /**
1020  * Append to the end of the path of this URI. If the current path does
1021  * not end in a slash and the path to be appended does not begin with
1022  * a slash, a slash will be appended to the current path before the
1023  * new segment is added. Also, if the current path ends in a slash
1024  * and the new segment begins with a slash, the extra slash will be
1025  * removed before the new segment is appended.
1026  *
1027  * @param p_addToPath the new segment to be added to the current path
1028  *
1029  * @exception MalformedURIException if p_addToPath contains syntax
1030  * errors
1031  */

1032  public void appendPath(String JavaDoc p_addToPath)
1033                         throws MalformedURIException {
1034    if (p_addToPath == null || p_addToPath.trim().length() == 0) {
1035      return;
1036    }
1037
1038    if (!isURIString(p_addToPath)) {
1039      throw new MalformedURIException(
1040              "Path contains invalid character!");
1041    }
1042
1043    if (m_path == null || m_path.trim().length() == 0) {
1044      if (p_addToPath.startsWith("/")) {
1045        m_path = p_addToPath;
1046      }
1047      else {
1048        m_path = "/" + p_addToPath;
1049      }
1050    }
1051    else if (m_path.endsWith("/")) {
1052      if (p_addToPath.startsWith("/")) {
1053        m_path = m_path.concat(p_addToPath.substring(1));
1054      }
1055      else {
1056        m_path = m_path.concat(p_addToPath);
1057      }
1058    }
1059    else {
1060      if (p_addToPath.startsWith("/")) {
1061        m_path = m_path.concat(p_addToPath);
1062      }
1063      else {
1064        m_path = m_path.concat("/" + p_addToPath);
1065      }
1066    }
1067  }
1068
1069 /**
1070  * Set the query string for this URI. A non-null value is valid only
1071  * if this is an URI conforming to the generic URI syntax and
1072  * the path value is not null.
1073  *
1074  * @param p_queryString the query string for this URI
1075  *
1076  * @exception MalformedURIException if p_queryString is not null and this
1077  * URI does not conform to the generic
1078  * URI syntax or if the path is null
1079  */

1080  public void setQueryString(String JavaDoc p_queryString) throws MalformedURIException {
1081    if (p_queryString == null) {
1082      m_queryString = null;
1083    }
1084    else if (!isGenericURI()) {
1085      throw new MalformedURIException(
1086              "Query string can only be set for a generic URI!");
1087    }
1088    else if (getPath() == null) {
1089      throw new MalformedURIException(
1090              "Query string cannot be set when path is null!");
1091    }
1092    else if (!isURIString(p_queryString)) {
1093      throw new MalformedURIException(
1094              "Query string contains invalid character!");
1095    }
1096    else {
1097      m_queryString = p_queryString;
1098    }
1099  }
1100
1101 /**
1102  * Set the fragment for this URI. A non-null value is valid only
1103  * if this is a URI conforming to the generic URI syntax and
1104  * the path value is not null.
1105  *
1106  * @param p_fragment the fragment for this URI
1107  *
1108  * @exception MalformedURIException if p_fragment is not null and this
1109  * URI does not conform to the generic
1110  * URI syntax or if the path is null
1111  */

1112  public void setFragment(String JavaDoc p_fragment) throws MalformedURIException {
1113    if (p_fragment == null) {
1114      m_fragment = null;
1115    }
1116    else if (!isGenericURI()) {
1117      throw new MalformedURIException(
1118         "Fragment can only be set for a generic URI!");
1119    }
1120    else if (getPath() == null) {
1121      throw new MalformedURIException(
1122              "Fragment cannot be set when path is null!");
1123    }
1124    else if (!isURIString(p_fragment)) {
1125      throw new MalformedURIException(
1126              "Fragment contains invalid character!");
1127    }
1128    else {
1129      m_fragment = p_fragment;
1130    }
1131  }
1132
1133 /**
1134  * Determines if the passed-in Object is equivalent to this URI.
1135  *
1136  * @param p_test the Object to test for equality.
1137  *
1138  * @return true if p_test is a URI with all values equal to this
1139  * URI, false otherwise
1140  */

1141  public boolean equals(Object JavaDoc p_test) {
1142    if (p_test instanceof URI) {
1143      URI testURI = (URI) p_test;
1144      if (((m_scheme == null && testURI.m_scheme == null) ||
1145           (m_scheme != null && testURI.m_scheme != null &&
1146            m_scheme.equals(testURI.m_scheme))) &&
1147          ((m_userinfo == null && testURI.m_userinfo == null) ||
1148           (m_userinfo != null && testURI.m_userinfo != null &&
1149            m_userinfo.equals(testURI.m_userinfo))) &&
1150          ((m_host == null && testURI.m_host == null) ||
1151           (m_host != null && testURI.m_host != null &&
1152            m_host.equals(testURI.m_host))) &&
1153            m_port == testURI.m_port &&
1154          ((m_path == null && testURI.m_path == null) ||
1155           (m_path != null && testURI.m_path != null &&
1156            m_path.equals(testURI.m_path))) &&
1157          ((m_queryString == null && testURI.m_queryString == null) ||
1158           (m_queryString != null && testURI.m_queryString != null &&
1159            m_queryString.equals(testURI.m_queryString))) &&
1160          ((m_fragment == null && testURI.m_fragment == null) ||
1161           (m_fragment != null && testURI.m_fragment != null &&
1162            m_fragment.equals(testURI.m_fragment)))) {
1163        return true;
1164      }
1165    }
1166    return false;
1167  }
1168
1169 /**
1170  * Get the URI as a string specification. See RFC 2396 Section 5.2.
1171  *
1172  * @return the URI string specification
1173  */

1174  public String JavaDoc toString() {
1175    StringBuffer JavaDoc uriSpecString = new StringBuffer JavaDoc();
1176
1177    if (m_scheme != null) {
1178      uriSpecString.append(m_scheme);
1179      uriSpecString.append(':');
1180    }
1181    uriSpecString.append(getSchemeSpecificPart());
1182    return uriSpecString.toString();
1183  }
1184
1185 /**
1186  * Get the indicator as to whether this URI uses the "generic URI"
1187  * syntax.
1188  *
1189  * @return true if this URI uses the "generic URI" syntax, false
1190  * otherwise
1191  */

1192  public boolean isGenericURI() {
1193    // presence of the host (whether valid or empty) means
1194
// double-slashes which means generic uri
1195
return (m_host != null);
1196  }
1197
1198 /**
1199  * Determine whether a scheme conforms to the rules for a scheme name.
1200  * A scheme is conformant if it starts with an alphanumeric, and
1201  * contains only alphanumerics, '+','-' and '.'.
1202  *
1203  * @return true if the scheme is conformant, false otherwise
1204  */

1205  public static boolean isConformantSchemeName(String JavaDoc p_scheme) {
1206    if (p_scheme == null || p_scheme.trim().length() == 0) {
1207      return false;
1208    }
1209
1210    if (!isAlpha(p_scheme.charAt(0))) {
1211      return false;
1212    }
1213
1214    char testChar;
1215    for (int i = 1; i < p_scheme.length(); i++) {
1216      testChar = p_scheme.charAt(i);
1217      if (!isAlphanum(testChar) &&
1218          SCHEME_CHARACTERS.indexOf(testChar) == -1) {
1219        return false;
1220      }
1221    }
1222
1223    return true;
1224  }
1225
1226 /**
1227  * Determine whether a string is syntactically capable of representing
1228  * a valid IPv4 address or the domain name of a network host. A valid
1229  * IPv4 address consists of four decimal digit groups separated by a
1230  * '.'. A hostname consists of domain labels (each of which must
1231  * begin and end with an alphanumeric but may contain '-') separated
1232  & by a '.'. See RFC 2396 Section 3.2.2.
1233  *
1234  * @return true if the string is a syntactically valid IPv4 address
1235  * or hostname
1236  */

1237  public static boolean isWellFormedAddress(String JavaDoc p_address) {
1238    if (p_address == null) {
1239      return false;
1240    }
1241
1242    String JavaDoc address = p_address.trim();
1243    int addrLength = address.length();
1244    if (addrLength == 0 || addrLength > 255) {
1245      return false;
1246    }
1247
1248    if (address.startsWith(".") || address.startsWith("-")) {
1249      return false;
1250    }
1251
1252    // rightmost domain label starting with digit indicates IP address
1253
// since top level domain label can only start with an alpha
1254
// see RFC 2396 Section 3.2.2
1255
int index = address.lastIndexOf('.');
1256    if (address.endsWith(".")) {
1257      index = address.substring(0, index).lastIndexOf('.');
1258    }
1259
1260    if (index+1 < addrLength && isDigit(p_address.charAt(index+1))) {
1261      char testChar;
1262      int numDots = 0;
1263
1264      // make sure that 1) we see only digits and dot separators, 2) that
1265
// any dot separator is preceded and followed by a digit and
1266
// 3) that we find 3 dots
1267
for (int i = 0; i < addrLength; i++) {
1268        testChar = address.charAt(i);
1269        if (testChar == '.') {
1270          if (!isDigit(address.charAt(i-1)) ||
1271              (i+1 < addrLength && !isDigit(address.charAt(i+1)))) {
1272            return false;
1273          }
1274          numDots++;
1275        }
1276        else if (!isDigit(testChar)) {
1277          return false;
1278        }
1279      }
1280      if (numDots != 3) {
1281        return false;
1282      }
1283    }
1284    else {
1285      // domain labels can contain alphanumerics and '-"
1286
// but must start and end with an alphanumeric
1287
char testChar;
1288
1289      for (int i = 0; i < addrLength; i++) {
1290        testChar = address.charAt(i);
1291        if (testChar == '.') {
1292          if (!isAlphanum(address.charAt(i-1))) {
1293            return false;
1294          }
1295          if (i+1 < addrLength && !isAlphanum(address.charAt(i+1))) {
1296            return false;
1297          }
1298        }
1299        else if (!isAlphanum(testChar) && testChar != '-') {
1300          return false;
1301        }
1302      }
1303    }
1304    return true;
1305  }
1306
1307
1308 /**
1309  * Determine whether a char is a digit.
1310  *
1311  * @return true if the char is betweeen '0' and '9', false otherwise
1312  */

1313  private static boolean isDigit(char p_char) {
1314    return p_char >= '0' && p_char <= '9';
1315  }
1316
1317 /**
1318  * Determine whether a character is a hexadecimal character.
1319  *
1320  * @return true if the char is betweeen '0' and '9', 'a' and 'f'
1321  * or 'A' and 'F', false otherwise
1322  */

1323  private static boolean isHex(char p_char) {
1324    return (isDigit(p_char) ||
1325            (p_char >= 'a' && p_char <= 'f') ||
1326            (p_char >= 'A' && p_char <= 'F'));
1327  }
1328
1329 /**
1330  * Determine whether a char is an alphabetic character: a-z or A-Z
1331  *
1332  * @return true if the char is alphabetic, false otherwise
1333  */

1334  private static boolean isAlpha(char p_char) {
1335    return ((p_char >= 'a' && p_char <= 'z') ||
1336            (p_char >= 'A' && p_char <= 'Z' ));
1337  }
1338
1339 /**
1340  * Determine whether a char is an alphanumeric: 0-9, a-z or A-Z
1341  *
1342  * @return true if the char is alphanumeric, false otherwise
1343  */

1344  private static boolean isAlphanum(char p_char) {
1345    return (isAlpha(p_char) || isDigit(p_char));
1346  }
1347
1348 /**
1349  * Determine whether a character is a reserved character:
1350  * ';', '/', '?', ':', '@', '&', '=', '+', '$' or ','
1351  *
1352  * @return true if the string contains any reserved characters
1353  */

1354  private static boolean isReservedCharacter(char p_char) {
1355    return RESERVED_CHARACTERS.indexOf(p_char) != -1;
1356  }
1357
1358 /**
1359  * Determine whether a char is an unreserved character.
1360  *
1361  * @return true if the char is unreserved, false otherwise
1362  */

1363  private static boolean isUnreservedCharacter(char p_char) {
1364    return (isAlphanum(p_char) ||
1365            MARK_CHARACTERS.indexOf(p_char) != -1);
1366  }
1367
1368 /**
1369  * Determine whether a given string contains only URI characters (also
1370  * called "uric" in RFC 2396). uric consist of all reserved
1371  * characters, unreserved characters and escaped characters.
1372  *
1373  * @return true if the string is comprised of uric, false otherwise
1374  */

1375  private static boolean isURIString(String JavaDoc p_uric) {
1376    if (p_uric == null) {
1377      return false;
1378    }
1379    int end = p_uric.length();
1380    char testChar = '\0';
1381    for (int i = 0; i < end; i++) {
1382      testChar = p_uric.charAt(i);
1383      if (testChar == '%') {
1384        if (i+2 >= end ||
1385            !isHex(p_uric.charAt(i+1)) ||
1386            !isHex(p_uric.charAt(i+2))) {
1387          return false;
1388        }
1389        else {
1390          i += 2;
1391          continue;
1392        }
1393      }
1394      if (isReservedCharacter(testChar) ||
1395          isUnreservedCharacter(testChar)) {
1396          continue;
1397      }
1398      else {
1399        return false;
1400      }
1401    }
1402    return true;
1403  }
1404}
1405
Popular Tags