KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > org > apache > xerces > internal > util > URI


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  *
5  * Copyright (c) 1999-2003 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
58 package com.sun.org.apache.xerces.internal.util;
59
60 import java.io.IOException JavaDoc;
61 import java.io.Serializable JavaDoc;
62
63 /**********************************************************************
64 * A class to represent a Uniform Resource Identifier (URI). This class
65 * is designed to handle the parsing of URIs and provide access to
66 * the various components (scheme, host, port, userinfo, path, query
67 * string and fragment) that may constitute a URI.
68 * <p>
69 * Parsing of a URI specification is done according to the URI
70 * syntax described in
71 * <a HREF="http://www.ietf.org/rfc/rfc2396.txt?number=2396">RFC 2396</a>,
72 * and amended by
73 * <a HREF="http://www.ietf.org/rfc/rfc2732.txt?number=2732">RFC 2732</a>.
74 * <p>
75 * Every absolute URI consists of a scheme, followed by a colon (':'),
76 * followed by a scheme-specific part. For URIs that follow the
77 * "generic URI" syntax, the scheme-specific part begins with two
78 * slashes ("//") and may be followed by an authority segment (comprised
79 * of user information, host, and port), path segment, query segment
80 * and fragment. Note that RFC 2396 no longer specifies the use of the
81 * parameters segment and excludes the "user:password" syntax as part of
82 * the authority segment. If "user:password" appears in a URI, the entire
83 * user/password string is stored as userinfo.
84 * <p>
85 * For URIs that do not follow the "generic URI" syntax (e.g. mailto),
86 * the entire scheme-specific part is treated as the "path" portion
87 * of the URI.
88 * <p>
89 * Note that, unlike the java.net.URL class, this class does not provide
90 * any built-in network access functionality nor does it provide any
91 * scheme-specific functionality (for example, it does not know a
92 * default port for a specific scheme). Rather, it only knows the
93 * grammar and basic set of operations that can be applied to a URI.
94 *
95 * @version $Id: URI.java,v 1.17 2004/03/28 16:12:19 mrglavas Exp $
96 *
97 **********************************************************************/

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

106   public static class MalformedURIException extends IOException JavaDoc {
107
108    /******************************************************************
109     * Constructs a <code>MalformedURIException</code> with no specified
110     * detail message.
111     ******************************************************************/

112     public MalformedURIException() {
113       super();
114     }
115
116     /*****************************************************************
117     * Constructs a <code>MalformedURIException</code> with the
118     * specified detail message.
119     *
120     * @param p_msg the detail message.
121     ******************************************************************/

122     public MalformedURIException(String JavaDoc p_msg) {
123       super(p_msg);
124     }
125   }
126
127   private static final byte [] fgLookupTable = new byte[128];
128   
129   /**
130    * Character Classes
131    */

132   
133   /** reserved characters ;/?:@&=+$,[] */
134   //RFC 2732 added '[' and ']' as reserved characters
135
private static final int RESERVED_CHARACTERS = 0x01;
136   
137   /** URI punctuation mark characters: -_.!~*'() - these, combined with
138       alphanumerics, constitute the "unreserved" characters */

139   private static final int MARK_CHARACTERS = 0x02;
140   
141   /** scheme can be composed of alphanumerics and these characters: +-. */
142   private static final int SCHEME_CHARACTERS = 0x04;
143   
144   /** userinfo can be composed of unreserved, escaped and these
145       characters: ;:&=+$, */

146   private static final int USERINFO_CHARACTERS = 0x08;
147   
148   /** ASCII letter characters */
149   private static final int ASCII_ALPHA_CHARACTERS = 0x10;
150   
151   /** ASCII digit characters */
152   private static final int ASCII_DIGIT_CHARACTERS = 0x20;
153   
154   /** ASCII hex characters */
155   private static final int ASCII_HEX_CHARACTERS = 0x40;
156   
157   /** Path characters */
158   private static final int PATH_CHARACTERS = 0x80;
159
160   /** Mask for alpha-numeric characters */
161   private static final int MASK_ALPHA_NUMERIC = ASCII_ALPHA_CHARACTERS | ASCII_DIGIT_CHARACTERS;
162   
163   /** Mask for unreserved characters */
164   private static final int MASK_UNRESERVED_MASK = MASK_ALPHA_NUMERIC | MARK_CHARACTERS;
165   
166   /** Mask for URI allowable characters except for % */
167   private static final int MASK_URI_CHARACTER = MASK_UNRESERVED_MASK | RESERVED_CHARACTERS;
168   
169   /** Mask for scheme characters */
170   private static final int MASK_SCHEME_CHARACTER = MASK_ALPHA_NUMERIC | SCHEME_CHARACTERS;
171   
172   /** Mask for userinfo characters */
173   private static final int MASK_USERINFO_CHARACTER = MASK_UNRESERVED_MASK | USERINFO_CHARACTERS;
174   
175   /** Mask for path characters */
176   private static final int MASK_PATH_CHARACTER = MASK_UNRESERVED_MASK | PATH_CHARACTERS;
177
178   static {
179       // Add ASCII Digits and ASCII Hex Numbers
180
for (int i = '0'; i <= '9'; ++i) {
181           fgLookupTable[i] |= ASCII_DIGIT_CHARACTERS | ASCII_HEX_CHARACTERS;
182       }
183
184       // Add ASCII Letters and ASCII Hex Numbers
185
for (int i = 'A'; i <= 'F'; ++i) {
186           fgLookupTable[i] |= ASCII_ALPHA_CHARACTERS | ASCII_HEX_CHARACTERS;
187           fgLookupTable[i+0x00000020] |= ASCII_ALPHA_CHARACTERS | ASCII_HEX_CHARACTERS;
188       }
189
190       // Add ASCII Letters
191
for (int i = 'G'; i <= 'Z'; ++i) {
192           fgLookupTable[i] |= ASCII_ALPHA_CHARACTERS;
193           fgLookupTable[i+0x00000020] |= ASCII_ALPHA_CHARACTERS;
194       }
195
196       // Add Reserved Characters
197
fgLookupTable[';'] |= RESERVED_CHARACTERS;
198       fgLookupTable['/'] |= RESERVED_CHARACTERS;
199       fgLookupTable['?'] |= RESERVED_CHARACTERS;
200       fgLookupTable[':'] |= RESERVED_CHARACTERS;
201       fgLookupTable['@'] |= RESERVED_CHARACTERS;
202       fgLookupTable['&'] |= RESERVED_CHARACTERS;
203       fgLookupTable['='] |= RESERVED_CHARACTERS;
204       fgLookupTable['+'] |= RESERVED_CHARACTERS;
205       fgLookupTable['$'] |= RESERVED_CHARACTERS;
206       fgLookupTable[','] |= RESERVED_CHARACTERS;
207       fgLookupTable['['] |= RESERVED_CHARACTERS;
208       fgLookupTable[']'] |= RESERVED_CHARACTERS;
209
210       // Add Mark Characters
211
fgLookupTable['-'] |= MARK_CHARACTERS;
212       fgLookupTable['_'] |= MARK_CHARACTERS;
213       fgLookupTable['.'] |= MARK_CHARACTERS;
214       fgLookupTable['!'] |= MARK_CHARACTERS;
215       fgLookupTable['~'] |= MARK_CHARACTERS;
216       fgLookupTable['*'] |= MARK_CHARACTERS;
217       fgLookupTable['\''] |= MARK_CHARACTERS;
218       fgLookupTable['('] |= MARK_CHARACTERS;
219       fgLookupTable[')'] |= MARK_CHARACTERS;
220
221       // Add Scheme Characters
222
fgLookupTable['+'] |= SCHEME_CHARACTERS;
223       fgLookupTable['-'] |= SCHEME_CHARACTERS;
224       fgLookupTable['.'] |= SCHEME_CHARACTERS;
225
226       // Add Userinfo Characters
227
fgLookupTable[';'] |= USERINFO_CHARACTERS;
228       fgLookupTable[':'] |= USERINFO_CHARACTERS;
229       fgLookupTable['&'] |= USERINFO_CHARACTERS;
230       fgLookupTable['='] |= USERINFO_CHARACTERS;
231       fgLookupTable['+'] |= USERINFO_CHARACTERS;
232       fgLookupTable['$'] |= USERINFO_CHARACTERS;
233       fgLookupTable[','] |= USERINFO_CHARACTERS;
234       
235       // Add Path Characters
236
fgLookupTable[';'] |= PATH_CHARACTERS;
237       fgLookupTable['/'] |= PATH_CHARACTERS;
238       fgLookupTable[':'] |= PATH_CHARACTERS;
239       fgLookupTable['@'] |= PATH_CHARACTERS;
240       fgLookupTable['&'] |= PATH_CHARACTERS;
241       fgLookupTable['='] |= PATH_CHARACTERS;
242       fgLookupTable['+'] |= PATH_CHARACTERS;
243       fgLookupTable['$'] |= PATH_CHARACTERS;
244       fgLookupTable[','] |= PATH_CHARACTERS;
245   }
246
247   /** Stores the scheme (usually the protocol) for this URI. */
248   private String JavaDoc m_scheme = null;
249
250   /** If specified, stores the userinfo for this URI; otherwise null */
251   private String JavaDoc m_userinfo = null;
252
253   /** If specified, stores the host for this URI; otherwise null */
254   private String JavaDoc m_host = null;
255
256   /** If specified, stores the port for this URI; otherwise -1 */
257   private int m_port = -1;
258   
259   /** If specified, stores the registry based authority for this URI; otherwise -1 */
260   private String JavaDoc m_regAuthority = null;
261
262   /** If specified, stores the path for this URI; otherwise null */
263   private String JavaDoc m_path = null;
264
265   /** If specified, stores the query string for this URI; otherwise
266       null. */

267   private String JavaDoc m_queryString = null;
268
269   /** If specified, stores the fragment for this URI; otherwise null */
270   private String JavaDoc m_fragment = null;
271
272   private static boolean DEBUG = false;
273
274   /**
275   * Construct a new and uninitialized URI.
276   */

277   public URI() {
278   }
279
280  /**
281   * Construct a new URI from another URI. All fields for this URI are
282   * set equal to the fields of the URI passed in.
283   *
284   * @param p_other the URI to copy (cannot be null)
285   */

286   public URI(URI p_other) {
287     initialize(p_other);
288   }
289
290  /**
291   * Construct a new URI from a URI specification string. If the
292   * specification follows the "generic URI" syntax, (two slashes
293   * following the first colon), the specification will be parsed
294   * accordingly - setting the scheme, userinfo, host,port, path, query
295   * string and fragment fields as necessary. If the specification does
296   * not follow the "generic URI" syntax, the specification is parsed
297   * into a scheme and scheme-specific part (stored as the path) only.
298   *
299   * @param p_uriSpec the URI specification string (cannot be null or
300   * empty)
301   *
302   * @exception MalformedURIException if p_uriSpec violates any syntax
303   * rules
304   */

305   public URI(String JavaDoc p_uriSpec) throws MalformedURIException {
306     this((URI)null, p_uriSpec);
307   }
308
309  /**
310   * Construct a new URI from a base URI and a URI specification string.
311   * The URI specification string may be a relative URI.
312   *
313   * @param p_base the base URI (cannot be null if p_uriSpec is null or
314   * empty)
315   * @param p_uriSpec the URI specification string (cannot be null or
316   * empty if p_base is null)
317   *
318   * @exception MalformedURIException if p_uriSpec violates any syntax
319   * rules
320   */

321   public URI(URI p_base, String JavaDoc p_uriSpec) throws MalformedURIException {
322     initialize(p_base, p_uriSpec);
323   }
324
325  /**
326   * Construct a new URI that does not follow the generic URI syntax.
327   * Only the scheme and scheme-specific part (stored as the path) are
328   * initialized.
329   *
330   * @param p_scheme the URI scheme (cannot be null or empty)
331   * @param p_schemeSpecificPart the scheme-specific part (cannot be
332   * null or empty)
333   *
334   * @exception MalformedURIException if p_scheme violates any
335   * syntax rules
336   */

337   public URI(String JavaDoc p_scheme, String JavaDoc p_schemeSpecificPart)
338              throws MalformedURIException {
339     if (p_scheme == null || p_scheme.trim().length() == 0) {
340       throw new MalformedURIException(
341             "Cannot construct URI with null/empty scheme!");
342     }
343     if (p_schemeSpecificPart == null ||
344         p_schemeSpecificPart.trim().length() == 0) {
345       throw new MalformedURIException(
346           "Cannot construct URI with null/empty scheme-specific part!");
347     }
348     setScheme(p_scheme);
349     setPath(p_schemeSpecificPart);
350   }
351
352  /**
353   * Construct a new URI that follows the generic URI syntax from its
354   * component parts. Each component is validated for syntax and some
355   * basic semantic checks are performed as well. See the individual
356   * setter methods for specifics.
357   *
358   * @param p_scheme the URI scheme (cannot be null or empty)
359   * @param p_host the hostname, IPv4 address or IPv6 reference for the URI
360   * @param p_path the URI path - if the path contains '?' or '#',
361   * then the query string and/or fragment will be
362   * set from the path; however, if the query and
363   * fragment are specified both in the path and as
364   * separate parameters, an exception is thrown
365   * @param p_queryString the URI query string (cannot be specified
366   * if path is null)
367   * @param p_fragment the URI fragment (cannot be specified if path
368   * is null)
369   *
370   * @exception MalformedURIException if any of the parameters violates
371   * syntax rules or semantic rules
372   */

373   public URI(String JavaDoc p_scheme, String JavaDoc p_host, String JavaDoc p_path,
374              String JavaDoc p_queryString, String JavaDoc p_fragment)
375          throws MalformedURIException {
376     this(p_scheme, null, p_host, -1, p_path, p_queryString, p_fragment);
377   }
378
379  /**
380   * Construct a new URI that follows the generic URI syntax from its
381   * component parts. Each component is validated for syntax and some
382   * basic semantic checks are performed as well. See the individual
383   * setter methods for specifics.
384   *
385   * @param p_scheme the URI scheme (cannot be null or empty)
386   * @param p_userinfo the URI userinfo (cannot be specified if host
387   * is null)
388   * @param p_host the hostname, IPv4 address or IPv6 reference for the URI
389   * @param p_port the URI port (may be -1 for "unspecified"; cannot
390   * be specified if host is null)
391   * @param p_path the URI path - if the path contains '?' or '#',
392   * then the query string and/or fragment will be
393   * set from the path; however, if the query and
394   * fragment are specified both in the path and as
395   * separate parameters, an exception is thrown
396   * @param p_queryString the URI query string (cannot be specified
397   * if path is null)
398   * @param p_fragment the URI fragment (cannot be specified if path
399   * is null)
400   *
401   * @exception MalformedURIException if any of the parameters violates
402   * syntax rules or semantic rules
403   */

404   public URI(String JavaDoc p_scheme, String JavaDoc p_userinfo,
405              String JavaDoc p_host, int p_port, String JavaDoc p_path,
406              String JavaDoc p_queryString, String JavaDoc p_fragment)
407          throws MalformedURIException {
408     if (p_scheme == null || p_scheme.trim().length() == 0) {
409       throw new MalformedURIException("Scheme is required!");
410     }
411
412     if (p_host == null) {
413       if (p_userinfo != null) {
414         throw new MalformedURIException(
415              "Userinfo may not be specified if host is not specified!");
416       }
417       if (p_port != -1) {
418         throw new MalformedURIException(
419              "Port may not be specified if host is not specified!");
420       }
421     }
422
423     if (p_path != null) {
424       if (p_path.indexOf('?') != -1 && p_queryString != null) {
425         throw new MalformedURIException(
426           "Query string cannot be specified in path and query string!");
427       }
428
429       if (p_path.indexOf('#') != -1 && p_fragment != null) {
430         throw new MalformedURIException(
431           "Fragment cannot be specified in both the path and fragment!");
432       }
433     }
434
435     setScheme(p_scheme);
436     setHost(p_host);
437     setPort(p_port);
438     setUserinfo(p_userinfo);
439     setPath(p_path);
440     setQueryString(p_queryString);
441     setFragment(p_fragment);
442   }
443
444  /**
445   * Initialize all fields of this URI from another URI.
446   *
447   * @param p_other the URI to copy (cannot be null)
448   */

449   private void initialize(URI p_other) {
450     m_scheme = p_other.getScheme();
451     m_userinfo = p_other.getUserinfo();
452     m_host = p_other.getHost();
453     m_port = p_other.getPort();
454     m_regAuthority = p_other.getRegBasedAuthority();
455     m_path = p_other.getPath();
456     m_queryString = p_other.getQueryString();
457     m_fragment = p_other.getFragment();
458   }
459
460  /**
461   * Initializes this URI from a base URI and a URI specification string.
462   * See RFC 2396 Section 4 and Appendix B for specifications on parsing
463   * the URI and Section 5 for specifications on resolving relative URIs
464   * and relative paths.
465   *
466   * @param p_base the base URI (may be null if p_uriSpec is an absolute
467   * URI)
468   * @param p_uriSpec the URI spec string which may be an absolute or
469   * relative URI (can only be null/empty if p_base
470   * is not null)
471   *
472   * @exception MalformedURIException if p_base is null and p_uriSpec
473   * is not an absolute URI or if
474   * p_uriSpec violates syntax rules
475   */

476   private void initialize(URI p_base, String JavaDoc p_uriSpec)
477                          throws MalformedURIException {
478       
479     String JavaDoc uriSpec = p_uriSpec;
480     int uriSpecLen = (uriSpec != null) ? uriSpec.length() : 0;
481     
482     if (p_base == null && uriSpecLen == 0) {
483       throw new MalformedURIException(
484                   "Cannot initialize URI with empty parameters.");
485     }
486
487     // just make a copy of the base if spec is empty
488
if (uriSpecLen == 0) {
489       initialize(p_base);
490       return;
491     }
492
493     int index = 0;
494
495     // Check for scheme, which must be before '/', '?' or '#'. Also handle
496
// names with DOS drive letters ('D:'), so 1-character schemes are not
497
// allowed.
498
int colonIdx = uriSpec.indexOf(':');
499     if (colonIdx != -1) {
500         final int searchFrom = colonIdx - 1;
501         // search backwards starting from character before ':'.
502
int slashIdx = uriSpec.lastIndexOf('/', searchFrom);
503         int queryIdx = uriSpec.lastIndexOf('?', searchFrom);
504         int fragmentIdx = uriSpec.lastIndexOf('#', searchFrom);
505        
506         if (colonIdx < 2 || slashIdx != -1 ||
507             queryIdx != -1 || fragmentIdx != -1) {
508             // A standalone base is a valid URI according to spec
509
if (colonIdx == 0 || (p_base == null && fragmentIdx != 0)) {
510                 throw new MalformedURIException("No scheme found in URI.");
511             }
512         }
513         else {
514             initializeScheme(uriSpec);
515             index = m_scheme.length()+1;
516             
517             // Neither 'scheme:' or 'scheme:#fragment' are valid URIs.
518
if (colonIdx == uriSpecLen - 1 || uriSpec.charAt(colonIdx+1) == '#') {
519                 throw new MalformedURIException("Scheme specific part cannot be empty.");
520             }
521         }
522     }
523     else if (p_base == null && uriSpec.indexOf('#') != 0) {
524         throw new MalformedURIException("No scheme found in URI.");
525     }
526
527     // Two slashes means we may have authority, but definitely means we're either
528
// matching net_path or abs_path. These two productions are ambiguous in that
529
// every net_path (except those containing an IPv6Reference) is an abs_path.
530
// RFC 2396 resolves this ambiguity by applying a greedy left most matching rule.
531
// Try matching net_path first, and if that fails we don't have authority so
532
// then attempt to match abs_path.
533
//
534
// net_path = "//" authority [ abs_path ]
535
// abs_path = "/" path_segments
536
if (((index+1) < uriSpecLen) &&
537         (uriSpec.charAt(index) == '/' && uriSpec.charAt(index+1) == '/')) {
538       index += 2;
539       int startPos = index;
540
541       // Authority will be everything up to path, query or fragment
542
char testChar = '\0';
543       while (index < uriSpecLen) {
544         testChar = uriSpec.charAt(index);
545         if (testChar == '/' || testChar == '?' || testChar == '#') {
546           break;
547         }
548         index++;
549       }
550
551       // Attempt to parse authority. If the section is an empty string
552
// this is a valid server based authority, so set the host to this
553
// value.
554
if (index > startPos) {
555         // If we didn't find authority we need to back up. Attempt to
556
// match against abs_path next.
557
if (!initializeAuthority(uriSpec.substring(startPos, index))) {
558           index = startPos - 2;
559         }
560       }
561       else {
562         m_host = "";
563       }
564     }
565
566     initializePath(uriSpec, index);
567
568     // Resolve relative URI to base URI - see RFC 2396 Section 5.2
569
// In some cases, it might make more sense to throw an exception
570
// (when scheme is specified is the string spec and the base URI
571
// is also specified, for example), but we're just following the
572
// RFC specifications
573
if (p_base != null) {
574
575       // check to see if this is the current doc - RFC 2396 5.2 #2
576
// note that this is slightly different from the RFC spec in that
577
// we don't include the check for query string being null
578
// - this handles cases where the urispec is just a query
579
// string or a fragment (e.g. "?y" or "#s") -
580
// see <http://www.ics.uci.edu/~fielding/url/test1.html> which
581
// identified this as a bug in the RFC
582
if (m_path.length() == 0 && m_scheme == null &&
583           m_host == null && m_regAuthority == null) {
584         m_scheme = p_base.getScheme();
585         m_userinfo = p_base.getUserinfo();
586         m_host = p_base.getHost();
587         m_port = p_base.getPort();
588         m_regAuthority = p_base.getRegBasedAuthority();
589         m_path = p_base.getPath();
590
591         if (m_queryString == null) {
592           m_queryString = p_base.getQueryString();
593         }
594         return;
595       }
596
597       // check for scheme - RFC 2396 5.2 #3
598
// if we found a scheme, it means absolute URI, so we're done
599
if (m_scheme == null) {
600         m_scheme = p_base.getScheme();
601       }
602       else {
603         return;
604       }
605
606       // check for authority - RFC 2396 5.2 #4
607
// if we found a host, then we've got a network path, so we're done
608
if (m_host == null && m_regAuthority == null) {
609         m_userinfo = p_base.getUserinfo();
610         m_host = p_base.getHost();
611         m_port = p_base.getPort();
612         m_regAuthority = p_base.getRegBasedAuthority();
613       }
614       else {
615         return;
616       }
617
618       // check for absolute path - RFC 2396 5.2 #5
619
if (m_path.length() > 0 &&
620           m_path.startsWith("/")) {
621         return;
622       }
623
624       // if we get to this point, we need to resolve relative path
625
// RFC 2396 5.2 #6
626
String JavaDoc path = "";
627       String JavaDoc basePath = p_base.getPath();
628
629       // 6a - get all but the last segment of the base URI path
630
if (basePath != null && basePath.length() > 0) {
631         int lastSlash = basePath.lastIndexOf('/');
632         if (lastSlash != -1) {
633           path = basePath.substring(0, lastSlash+1);
634         }
635       }
636       else if (m_path.length() > 0) {
637         path = "/";
638       }
639
640       // 6b - append the relative URI path
641
path = path.concat(m_path);
642
643       // 6c - remove all "./" where "." is a complete path segment
644
index = -1;
645       while ((index = path.indexOf("/./")) != -1) {
646         path = path.substring(0, index+1).concat(path.substring(index+3));
647       }
648
649       // 6d - remove "." if path ends with "." as a complete path segment
650
if (path.endsWith("/.")) {
651         path = path.substring(0, path.length()-1);
652       }
653
654       // 6e - remove all "<segment>/../" where "<segment>" is a complete
655
// path segment not equal to ".."
656
index = 1;
657       int segIndex = -1;
658       String JavaDoc tempString = null;
659
660       while ((index = path.indexOf("/../", index)) > 0) {
661         tempString = path.substring(0, path.indexOf("/../"));
662         segIndex = tempString.lastIndexOf('/');
663         if (segIndex != -1) {
664           if (!tempString.substring(segIndex).equals("..")) {
665             path = path.substring(0, segIndex+1).concat(path.substring(index+4));
666             index = segIndex;
667           }
668           else
669             index += 4;
670         }
671         else
672           index += 4;
673       }
674
675       // 6f - remove ending "<segment>/.." where "<segment>" is a
676
// complete path segment
677
if (path.endsWith("/..")) {
678         tempString = path.substring(0, path.length()-3);
679         segIndex = tempString.lastIndexOf('/');
680         if (segIndex != -1) {
681           path = path.substring(0, segIndex+1);
682         }
683       }
684       m_path = path;
685     }
686   }
687
688  /**
689   * Initialize the scheme for this URI from a URI string spec.
690   *
691   * @param p_uriSpec the URI specification (cannot be null)
692   *
693   * @exception MalformedURIException if URI does not have a conformant
694   * scheme
695   */

696   private void initializeScheme(String JavaDoc p_uriSpec)
697                  throws MalformedURIException {
698     int uriSpecLen = p_uriSpec.length();
699     int index = 0;
700     String JavaDoc scheme = null;
701     char testChar = '\0';
702
703     while (index < uriSpecLen) {
704       testChar = p_uriSpec.charAt(index);
705       if (testChar == ':' || testChar == '/' ||
706           testChar == '?' || testChar == '#') {
707         break;
708       }
709       index++;
710     }
711     scheme = p_uriSpec.substring(0, index);
712
713     if (scheme.length() == 0) {
714       throw new MalformedURIException("No scheme found in URI.");
715     }
716     else {
717       setScheme(scheme);
718     }
719   }
720
721  /**
722   * Initialize the authority (either server or registry based)
723   * for this URI from a URI string spec.
724   *
725   * @param p_uriSpec the URI specification (cannot be null)
726   *
727   * @return true if the given string matched server or registry
728   * based authority
729   */

730   private boolean initializeAuthority(String JavaDoc p_uriSpec) {
731     
732     int index = 0;
733     int start = 0;
734     int end = p_uriSpec.length();
735
736     char testChar = '\0';
737     String JavaDoc userinfo = null;
738
739     // userinfo is everything up to @
740
if (p_uriSpec.indexOf('@', start) != -1) {
741       while (index < end) {
742         testChar = p_uriSpec.charAt(index);
743         if (testChar == '@') {
744           break;
745         }
746         index++;
747       }
748       userinfo = p_uriSpec.substring(start, index);
749       index++;
750     }
751
752     // host is everything up to last ':', or up to
753
// and including ']' if followed by ':'.
754
String JavaDoc host = null;
755     start = index;
756     boolean hasPort = false;
757     if (index < end) {
758       if (p_uriSpec.charAt(start) == '[') {
759         int bracketIndex = p_uriSpec.indexOf(']', start);
760         index = (bracketIndex != -1) ? bracketIndex : end;
761         if (index+1 < end && p_uriSpec.charAt(index+1) == ':') {
762           ++index;
763           hasPort = true;
764         }
765         else {
766           index = end;
767         }
768       }
769       else {
770         int colonIndex = p_uriSpec.lastIndexOf(':', end);
771         index = (colonIndex > start) ? colonIndex : end;
772         hasPort = (index != end);
773       }
774     }
775     host = p_uriSpec.substring(start, index);
776     int port = -1;
777     if (host.length() > 0) {
778       // port
779
if (hasPort) {
780         index++;
781         start = index;
782         while (index < end) {
783           index++;
784         }
785         String JavaDoc portStr = p_uriSpec.substring(start, index);
786         if (portStr.length() > 0) {
787           // REVISIT: Remove this code.
788
/** for (int i = 0; i < portStr.length(); i++) {
789             if (!isDigit(portStr.charAt(i))) {
790               throw new MalformedURIException(
791                    portStr +
792                    " is invalid. Port should only contain digits!");
793             }
794           }**/

795           // REVISIT: Remove this code.
796
// Store port value as string instead of integer.
797
try {
798             port = Integer.parseInt(portStr);
799             if (port == -1) --port;
800           }
801           catch (NumberFormatException JavaDoc nfe) {
802             port = -2;
803           }
804         }
805       }
806     }
807     
808     if (isValidServerBasedAuthority(host, port, userinfo)) {
809       m_host = host;
810       m_port = port;
811       m_userinfo = userinfo;
812       return true;
813     }
814     // Note: Registry based authority is being removed from a
815
// new spec for URI which would obsolete RFC 2396. If the
816
// spec is added to XML errata, processing of reg_name
817
// needs to be removed. - mrglavas.
818
else if (isValidRegistryBasedAuthority(p_uriSpec)) {
819       m_regAuthority = p_uriSpec;
820       return true;
821     }
822     return false;
823   }
824   
825   /**
826    * Determines whether the components host, port, and user info
827    * are valid as a server authority.
828    *
829    * @param host the host component of authority
830    * @param port the port number component of authority
831    * @param userinfo the user info component of authority
832    *
833    * @return true if the given host, port, and userinfo compose
834    * a valid server authority
835    */

836   private boolean isValidServerBasedAuthority(String JavaDoc host, int port, String JavaDoc userinfo) {
837     
838     // Check if the host is well formed.
839
if (!isWellFormedAddress(host)) {
840       return false;
841     }
842     
843     // Check that port is well formed if it exists.
844
// REVISIT: There's no restriction on port value ranges, but
845
// perform the same check as in setPort to be consistent. Pass
846
// in a string to this method instead of an integer.
847
if (port < -1 || port > 65535) {
848       return false;
849     }
850     
851     // Check that userinfo is well formed if it exists.
852
if (userinfo != null) {
853       // Userinfo can contain alphanumerics, mark characters, escaped
854
// and ';',':','&','=','+','$',','
855
int index = 0;
856       int end = userinfo.length();
857       char testChar = '\0';
858       while (index < end) {
859         testChar = userinfo.charAt(index);
860         if (testChar == '%') {
861           if (index+2 >= end ||
862             !isHex(userinfo.charAt(index+1)) ||
863             !isHex(userinfo.charAt(index+2))) {
864             return false;
865           }
866           index += 2;
867         }
868         else if (!isUserinfoCharacter(testChar)) {
869           return false;
870         }
871         ++index;
872       }
873     }
874     return true;
875   }
876   
877   /**
878    * Determines whether the given string is a registry based authority.
879    *
880    * @param authority the authority component of a URI
881    *
882    * @return true if the given string is a registry based authority
883    */

884   private boolean isValidRegistryBasedAuthority(String JavaDoc authority) {
885     int index = 0;
886     int end = authority.length();
887     char testChar;
888     
889     while (index < end) {
890       testChar = authority.charAt(index);
891       
892       // check for valid escape sequence
893
if (testChar == '%') {
894         if (index+2 >= end ||
895             !isHex(authority.charAt(index+1)) ||
896             !isHex(authority.charAt(index+2))) {
897             return false;
898         }
899         index += 2;
900       }
901       // can check against path characters because the set
902
// is the same except for '/' which we've already excluded.
903
else if (!isPathCharacter(testChar)) {
904         return false;
905       }
906       ++index;
907     }
908     return true;
909   }
910     
911  /**
912   * Initialize the path for this URI from a URI string spec.
913   *
914   * @param p_uriSpec the URI specification (cannot be null)
915   * @param p_nStartIndex the index to begin scanning from
916   *
917   * @exception MalformedURIException if p_uriSpec violates syntax rules
918   */

919   private void initializePath(String JavaDoc p_uriSpec, int p_nStartIndex)
920                  throws MalformedURIException {
921     if (p_uriSpec == null) {
922       throw new MalformedURIException(
923                 "Cannot initialize path from null string!");
924     }
925
926     int index = p_nStartIndex;
927     int start = p_nStartIndex;
928     int end = p_uriSpec.length();
929     char testChar = '\0';
930
931     // path - everything up to query string or fragment
932
if (start < end) {
933         // RFC 2732 only allows '[' and ']' to appear in the opaque part.
934
if (getScheme() == null || p_uriSpec.charAt(start) == '/') {
935         
936             // Scan path.
937
// abs_path = "/" path_segments
938
// rel_path = rel_segment [ abs_path ]
939
while (index < end) {
940                 testChar = p_uriSpec.charAt(index);
941             
942                 // check for valid escape sequence
943
if (testChar == '%') {
944                     if (index+2 >= end ||
945                     !isHex(p_uriSpec.charAt(index+1)) ||
946                     !isHex(p_uriSpec.charAt(index+2))) {
947                         throw new MalformedURIException(
948                             "Path contains invalid escape sequence!");
949                     }
950                     index += 2;
951                 }
952                 // Path segments cannot contain '[' or ']' since pchar
953
// production was not changed by RFC 2732.
954
else if (!isPathCharacter(testChar)) {
955                     if (testChar == '?' || testChar == '#') {
956                         break;
957                     }
958                     throw new MalformedURIException(
959                         "Path contains invalid character: " + testChar);
960                 }
961                 ++index;
962             }
963         }
964         else {
965             
966             // Scan opaque part.
967
// opaque_part = uric_no_slash *uric
968
while (index < end) {
969                 testChar = p_uriSpec.charAt(index);
970             
971                 if (testChar == '?' || testChar == '#') {
972                     break;
973                 }
974                 
975                 // check for valid escape sequence
976
if (testChar == '%') {
977                     if (index+2 >= end ||
978                     !isHex(p_uriSpec.charAt(index+1)) ||
979                     !isHex(p_uriSpec.charAt(index+2))) {
980                         throw new MalformedURIException(
981                             "Opaque part contains invalid escape sequence!");
982                     }
983                     index += 2;
984                 }
985                 // If the scheme specific part is opaque, it can contain '['
986
// and ']'. uric_no_slash wasn't modified by RFC 2732, which
987
// I've interpreted as an error in the spec, since the
988
// production should be equivalent to (uric - '/'), and uric
989
// contains '[' and ']'. - mrglavas
990
else if (!isURICharacter(testChar)) {
991                     throw new MalformedURIException(
992                         "Opaque part contains invalid character: " + testChar);
993                 }
994                 ++index;
995             }
996         }
997     }
998     m_path = p_uriSpec.substring(start, index);
999
1000    // query - starts with ? and up to fragment or end
1001
if (testChar == '?') {
1002      index++;
1003      start = index;
1004      while (index < end) {
1005        testChar = p_uriSpec.charAt(index);
1006        if (testChar == '#') {
1007          break;
1008        }
1009        if (testChar == '%') {
1010           if (index+2 >= end ||
1011              !isHex(p_uriSpec.charAt(index+1)) ||
1012              !isHex(p_uriSpec.charAt(index+2))) {
1013            throw new MalformedURIException(
1014                    "Query string contains invalid escape sequence!");
1015           }
1016           index += 2;
1017        }
1018        else if (!isURICharacter(testChar)) {
1019          throw new MalformedURIException(
1020                "Query string contains invalid character: " + testChar);
1021        }
1022        index++;
1023      }
1024      m_queryString = p_uriSpec.substring(start, index);
1025    }
1026
1027    // fragment - starts with #
1028
if (testChar == '#') {
1029      index++;
1030      start = index;
1031      while (index < end) {
1032        testChar = p_uriSpec.charAt(index);
1033
1034        if (testChar == '%') {
1035           if (index+2 >= end ||
1036              !isHex(p_uriSpec.charAt(index+1)) ||
1037              !isHex(p_uriSpec.charAt(index+2))) {
1038            throw new MalformedURIException(
1039                    "Fragment contains invalid escape sequence!");
1040           }
1041           index += 2;
1042        }
1043        else if (!isURICharacter(testChar)) {
1044          throw new MalformedURIException(
1045                "Fragment contains invalid character: "+testChar);
1046        }
1047        index++;
1048      }
1049      m_fragment = p_uriSpec.substring(start, index);
1050    }
1051  }
1052
1053 /**
1054  * Get the scheme for this URI.
1055  *
1056  * @return the scheme for this URI
1057  */

1058  public String JavaDoc getScheme() {
1059    return m_scheme;
1060  }
1061
1062 /**
1063  * Get the scheme-specific part for this URI (everything following the
1064  * scheme and the first colon). See RFC 2396 Section 5.2 for spec.
1065  *
1066  * @return the scheme-specific part for this URI
1067  */

1068  public String JavaDoc getSchemeSpecificPart() {
1069    StringBuffer JavaDoc schemespec = new StringBuffer JavaDoc();
1070
1071    if (m_host != null || m_regAuthority != null) {
1072      schemespec.append("//");
1073    
1074      // Server based authority.
1075
if (m_host != null) {
1076
1077        if (m_userinfo != null) {
1078          schemespec.append(m_userinfo);
1079          schemespec.append('@');
1080        }
1081        
1082        schemespec.append(m_host);
1083        
1084        if (m_port != -1) {
1085          schemespec.append(':');
1086          schemespec.append(m_port);
1087        }
1088      }
1089      // Registry based authority.
1090
else {
1091        schemespec.append(m_regAuthority);
1092      }
1093    }
1094
1095    if (m_path != null) {
1096      schemespec.append((m_path));
1097    }
1098
1099    if (m_queryString != null) {
1100      schemespec.append('?');
1101      schemespec.append(m_queryString);
1102    }
1103
1104    if (m_fragment != null) {
1105      schemespec.append('#');
1106      schemespec.append(m_fragment);
1107    }
1108
1109    return schemespec.toString();
1110  }
1111
1112 /**
1113  * Get the userinfo for this URI.
1114  *
1115  * @return the userinfo for this URI (null if not specified).
1116  */

1117  public String JavaDoc getUserinfo() {
1118    return m_userinfo;
1119  }
1120
1121  /**
1122  * Get the host for this URI.
1123  *
1124  * @return the host for this URI (null if not specified).
1125  */

1126  public String JavaDoc getHost() {
1127    return m_host;
1128  }
1129
1130 /**
1131  * Get the port for this URI.
1132  *
1133  * @return the port for this URI (-1 if not specified).
1134  */

1135  public int getPort() {
1136    return m_port;
1137  }
1138  
1139  /**
1140   * Get the registry based authority for this URI.
1141   *
1142   * @return the registry based authority (null if not specified).
1143   */

1144  public String JavaDoc getRegBasedAuthority() {
1145    return m_regAuthority;
1146  }
1147
1148 /**
1149  * Get the path for this URI (optionally with the query string and
1150  * fragment).
1151  *
1152  * @param p_includeQueryString if true (and query string is not null),
1153  * then a "?" followed by the query string
1154  * will be appended
1155  * @param p_includeFragment if true (and fragment is not null),
1156  * then a "#" followed by the fragment
1157  * will be appended
1158  *
1159  * @return the path for this URI possibly including the query string
1160  * and fragment
1161  */

1162  public String JavaDoc getPath(boolean p_includeQueryString,
1163                        boolean p_includeFragment) {
1164    StringBuffer JavaDoc pathString = new StringBuffer JavaDoc(m_path);
1165
1166    if (p_includeQueryString && m_queryString != null) {
1167      pathString.append('?');
1168      pathString.append(m_queryString);
1169    }
1170
1171    if (p_includeFragment && m_fragment != null) {
1172      pathString.append('#');
1173      pathString.append(m_fragment);
1174    }
1175    return pathString.toString();
1176  }
1177
1178 /**
1179  * Get the path for this URI. Note that the value returned is the path
1180  * only and does not include the query string or fragment.
1181  *
1182  * @return the path for this URI.
1183  */

1184  public String JavaDoc getPath() {
1185    return m_path;
1186  }
1187
1188 /**
1189  * Get the query string for this URI.
1190  *
1191  * @return the query string for this URI. Null is returned if there
1192  * was no "?" in the URI spec, empty string if there was a
1193  * "?" but no query string following it.
1194  */

1195  public String JavaDoc getQueryString() {
1196    return m_queryString;
1197  }
1198
1199 /**
1200  * Get the fragment for this URI.
1201  *
1202  * @return the fragment for this URI. Null is returned if there
1203  * was no "#" in the URI spec, empty string if there was a
1204  * "#" but no fragment following it.
1205  */

1206  public String JavaDoc getFragment() {
1207    return m_fragment;
1208  }
1209
1210 /**
1211  * Set the scheme for this URI. The scheme is converted to lowercase
1212  * before it is set.
1213  *
1214  * @param p_scheme the scheme for this URI (cannot be null)
1215  *
1216  * @exception MalformedURIException if p_scheme is not a conformant
1217  * scheme name
1218  */

1219  public void setScheme(String JavaDoc p_scheme) throws MalformedURIException {
1220    if (p_scheme == null) {
1221      throw new MalformedURIException(
1222                "Cannot set scheme from null string!");
1223    }
1224    if (!isConformantSchemeName(p_scheme)) {
1225      throw new MalformedURIException("The scheme is not conformant.");
1226    }
1227
1228    m_scheme = p_scheme.toLowerCase();
1229  }
1230
1231 /**
1232  * Set the userinfo for this URI. If a non-null value is passed in and
1233  * the host value is null, then an exception is thrown.
1234  *
1235  * @param p_userinfo the userinfo for this URI
1236  *
1237  * @exception MalformedURIException if p_userinfo contains invalid
1238  * characters
1239  */

1240  public void setUserinfo(String JavaDoc p_userinfo) throws MalformedURIException {
1241    if (p_userinfo == null) {
1242      m_userinfo = null;
1243      return;
1244    }
1245    else {
1246      if (m_host == null) {
1247        throw new MalformedURIException(
1248                     "Userinfo cannot be set when host is null!");
1249      }
1250
1251      // userinfo can contain alphanumerics, mark characters, escaped
1252
// and ';',':','&','=','+','$',','
1253
int index = 0;
1254      int end = p_userinfo.length();
1255      char testChar = '\0';
1256      while (index < end) {
1257        testChar = p_userinfo.charAt(index);
1258        if (testChar == '%') {
1259          if (index+2 >= end ||
1260              !isHex(p_userinfo.charAt(index+1)) ||
1261              !isHex(p_userinfo.charAt(index+2))) {
1262            throw new MalformedURIException(
1263                  "Userinfo contains invalid escape sequence!");
1264          }
1265        }
1266        else if (!isUserinfoCharacter(testChar)) {
1267          throw new MalformedURIException(
1268                  "Userinfo contains invalid character:"+testChar);
1269        }
1270        index++;
1271      }
1272    }
1273    m_userinfo = p_userinfo;
1274  }
1275
1276 /**
1277  * <p>Set the host for this URI. If null is passed in, the userinfo
1278  * field is also set to null and the port is set to -1.</p>
1279  *
1280  * <p>Note: This method overwrites registry based authority if it
1281  * previously existed in this URI.</p>
1282  *
1283  * @param p_host the host for this URI
1284  *
1285  * @exception MalformedURIException if p_host is not a valid IP
1286  * address or DNS hostname.
1287  */

1288  public void setHost(String JavaDoc p_host) throws MalformedURIException {
1289    if (p_host == null || p_host.length() == 0) {
1290      if (p_host != null) {
1291        m_regAuthority = null;
1292      }
1293      m_host = p_host;
1294      m_userinfo = null;
1295      m_port = -1;
1296      return;
1297    }
1298    else if (!isWellFormedAddress(p_host)) {
1299      throw new MalformedURIException("Host is not a well formed address!");
1300    }
1301    m_host = p_host;
1302    m_regAuthority = null;
1303  }
1304
1305 /**
1306  * Set the port for this URI. -1 is used to indicate that the port is
1307  * not specified, otherwise valid port numbers are between 0 and 65535.
1308  * If a valid port number is passed in and the host field is null,
1309  * an exception is thrown.
1310  *
1311  * @param p_port the port number for this URI
1312  *
1313  * @exception MalformedURIException if p_port is not -1 and not a
1314  * valid port number
1315  */

1316  public void setPort(int p_port) throws MalformedURIException {
1317    if (p_port >= 0 && p_port <= 65535) {
1318      if (m_host == null) {
1319        throw new MalformedURIException(
1320                      "Port cannot be set when host is null!");
1321      }
1322    }
1323    else if (p_port != -1) {
1324      throw new MalformedURIException("Invalid port number!");
1325    }
1326    m_port = p_port;
1327  }
1328  
1329  /**
1330   * <p>Sets the registry based authority for this URI.</p>
1331   *
1332   * <p>Note: This method overwrites server based authority
1333   * if it previously existed in this URI.</p>
1334   *
1335   * @param authority the registry based authority for this URI
1336   *
1337   * @exception MalformedURIException it authority is not a
1338   * well formed registry based authority
1339   */

1340  public void setRegBasedAuthority(String JavaDoc authority)
1341    throws MalformedURIException {
1342
1343    if (authority == null) {
1344      m_regAuthority = null;
1345      return;
1346    }
1347    // reg_name = 1*( unreserved | escaped | "$" | "," |
1348
// ";" | ":" | "@" | "&" | "=" | "+" )
1349
else if (authority.length() < 1 ||
1350      !isValidRegistryBasedAuthority(authority) ||
1351      authority.indexOf('/') != -1) {
1352      throw new MalformedURIException("Registry based authority is not well formed.");
1353    }
1354    m_regAuthority = authority;
1355    m_host = null;
1356    m_userinfo = null;
1357    m_port = -1;
1358  }
1359
1360 /**
1361  * Set the path for this URI. If the supplied path is null, then the
1362  * query string and fragment are set to null as well. If the supplied
1363  * path includes a query string and/or fragment, these fields will be
1364  * parsed and set as well. Note that, for URIs following the "generic
1365  * URI" syntax, the path specified should start with a slash.
1366  * For URIs that do not follow the generic URI syntax, this method
1367  * sets the scheme-specific part.
1368  *
1369  * @param p_path the path for this URI (may be null)
1370  *
1371  * @exception MalformedURIException if p_path contains invalid
1372  * characters
1373  */

1374  public void setPath(String JavaDoc p_path) throws MalformedURIException {
1375    if (p_path == null) {
1376      m_path = null;
1377      m_queryString = null;
1378      m_fragment = null;
1379    }
1380    else {
1381      initializePath(p_path, 0);
1382    }
1383  }
1384
1385 /**
1386  * Append to the end of the path of this URI. If the current path does
1387  * not end in a slash and the path to be appended does not begin with
1388  * a slash, a slash will be appended to the current path before the
1389  * new segment is added. Also, if the current path ends in a slash
1390  * and the new segment begins with a slash, the extra slash will be
1391  * removed before the new segment is appended.
1392  *
1393  * @param p_addToPath the new segment to be added to the current path
1394  *
1395  * @exception MalformedURIException if p_addToPath contains syntax
1396  * errors
1397  */

1398  public void appendPath(String JavaDoc p_addToPath)
1399                         throws MalformedURIException {
1400    if (p_addToPath == null || p_addToPath.trim().length() == 0) {
1401      return;
1402    }
1403
1404    if (!isURIString(p_addToPath)) {
1405      throw new MalformedURIException(
1406              "Path contains invalid character!");
1407    }
1408
1409    if (m_path == null || m_path.trim().length() == 0) {
1410      if (p_addToPath.startsWith("/")) {
1411        m_path = p_addToPath;
1412      }
1413      else {
1414        m_path = "/" + p_addToPath;
1415      }
1416    }
1417    else if (m_path.endsWith("/")) {
1418      if (p_addToPath.startsWith("/")) {
1419        m_path = m_path.concat(p_addToPath.substring(1));
1420      }
1421      else {
1422        m_path = m_path.concat(p_addToPath);
1423      }
1424    }
1425    else {
1426      if (p_addToPath.startsWith("/")) {
1427        m_path = m_path.concat(p_addToPath);
1428      }
1429      else {
1430        m_path = m_path.concat("/" + p_addToPath);
1431      }
1432    }
1433  }
1434
1435 /**
1436  * Set the query string for this URI. A non-null value is valid only
1437  * if this is an URI conforming to the generic URI syntax and
1438  * the path value is not null.
1439  *
1440  * @param p_queryString the query string for this URI
1441  *
1442  * @exception MalformedURIException if p_queryString is not null and this
1443  * URI does not conform to the generic
1444  * URI syntax or if the path is null
1445  */

1446  public void setQueryString(String JavaDoc p_queryString) throws MalformedURIException {
1447    if (p_queryString == null) {
1448      m_queryString = null;
1449    }
1450    else if (!isGenericURI()) {
1451      throw new MalformedURIException(
1452              "Query string can only be set for a generic URI!");
1453    }
1454    else if (getPath() == null) {
1455      throw new MalformedURIException(
1456              "Query string cannot be set when path is null!");
1457    }
1458    else if (!isURIString(p_queryString)) {
1459      throw new MalformedURIException(
1460              "Query string contains invalid character!");
1461    }
1462    else {
1463      m_queryString = p_queryString;
1464    }
1465  }
1466
1467 /**
1468  * Set the fragment for this URI. A non-null value is valid only
1469  * if this is a URI conforming to the generic URI syntax and
1470  * the path value is not null.
1471  *
1472  * @param p_fragment the fragment for this URI
1473  *
1474  * @exception MalformedURIException if p_fragment is not null and this
1475  * URI does not conform to the generic
1476  * URI syntax or if the path is null
1477  */

1478  public void setFragment(String JavaDoc p_fragment) throws MalformedURIException {
1479    if (p_fragment == null) {
1480      m_fragment = null;
1481    }
1482    else if (!isGenericURI()) {
1483      throw new MalformedURIException(
1484         "Fragment can only be set for a generic URI!");
1485    }
1486    else if (getPath() == null) {
1487      throw new MalformedURIException(
1488              "Fragment cannot be set when path is null!");
1489    }
1490    else if (!isURIString(p_fragment)) {
1491      throw new MalformedURIException(
1492              "Fragment contains invalid character!");
1493    }
1494    else {
1495      m_fragment = p_fragment;
1496    }
1497  }
1498
1499 /**
1500  * Determines if the passed-in Object is equivalent to this URI.
1501  *
1502  * @param p_test the Object to test for equality.
1503  *
1504  * @return true if p_test is a URI with all values equal to this
1505  * URI, false otherwise
1506  */

1507  public boolean equals(Object JavaDoc p_test) {
1508    if (p_test instanceof URI) {
1509      URI testURI = (URI) p_test;
1510      if (((m_scheme == null && testURI.m_scheme == null) ||
1511           (m_scheme != null && testURI.m_scheme != null &&
1512            m_scheme.equals(testURI.m_scheme))) &&
1513          ((m_userinfo == null && testURI.m_userinfo == null) ||
1514           (m_userinfo != null && testURI.m_userinfo != null &&
1515            m_userinfo.equals(testURI.m_userinfo))) &&
1516          ((m_host == null && testURI.m_host == null) ||
1517           (m_host != null && testURI.m_host != null &&
1518            m_host.equals(testURI.m_host))) &&
1519            m_port == testURI.m_port &&
1520          ((m_path == null && testURI.m_path == null) ||
1521           (m_path != null && testURI.m_path != null &&
1522            m_path.equals(testURI.m_path))) &&
1523          ((m_queryString == null && testURI.m_queryString == null) ||
1524           (m_queryString != null && testURI.m_queryString != null &&
1525            m_queryString.equals(testURI.m_queryString))) &&
1526          ((m_fragment == null && testURI.m_fragment == null) ||
1527           (m_fragment != null && testURI.m_fragment != null &&
1528            m_fragment.equals(testURI.m_fragment)))) {
1529        return true;
1530      }
1531    }
1532    return false;
1533  }
1534
1535 /**
1536  * Get the URI as a string specification. See RFC 2396 Section 5.2.
1537  *
1538  * @return the URI string specification
1539  */

1540  public String JavaDoc toString() {
1541    StringBuffer JavaDoc uriSpecString = new StringBuffer JavaDoc();
1542
1543    if (m_scheme != null) {
1544      uriSpecString.append(m_scheme);
1545      uriSpecString.append(':');
1546    }
1547    uriSpecString.append(getSchemeSpecificPart());
1548    return uriSpecString.toString();
1549  }
1550
1551 /**
1552  * Get the indicator as to whether this URI uses the "generic URI"
1553  * syntax.
1554  *
1555  * @return true if this URI uses the "generic URI" syntax, false
1556  * otherwise
1557  */

1558  public boolean isGenericURI() {
1559    // presence of the host (whether valid or empty) means
1560
// double-slashes which means generic uri
1561
return (m_host != null);
1562  }
1563
1564 /**
1565  * Determine whether a scheme conforms to the rules for a scheme name.
1566  * A scheme is conformant if it starts with an alphanumeric, and
1567  * contains only alphanumerics, '+','-' and '.'.
1568  *
1569  * @return true if the scheme is conformant, false otherwise
1570  */

1571  public static boolean isConformantSchemeName(String JavaDoc p_scheme) {
1572    if (p_scheme == null || p_scheme.trim().length() == 0) {
1573      return false;
1574    }
1575
1576    if (!isAlpha(p_scheme.charAt(0))) {
1577      return false;
1578    }
1579
1580    char testChar;
1581    int schemeLength = p_scheme.length();
1582    for (int i = 1; i < schemeLength; ++i) {
1583      testChar = p_scheme.charAt(i);
1584      if (!isSchemeCharacter(testChar)) {
1585        return false;
1586      }
1587    }
1588
1589    return true;
1590  }
1591
1592 /**
1593  * Determine whether a string is syntactically capable of representing
1594  * a valid IPv4 address, IPv6 reference or the domain name of a network host.
1595  * A valid IPv4 address consists of four decimal digit groups separated by a
1596  * '.'. Each group must consist of one to three digits. See RFC 2732 Section 3,
1597  * and RFC 2373 Section 2.2, for the definition of IPv6 references. A hostname
1598  * consists of domain labels (each of which must begin and end with an alphanumeric
1599  * but may contain '-') separated & by a '.'. See RFC 2396 Section 3.2.2.
1600  *
1601  * @return true if the string is a syntactically valid IPv4 address,
1602  * IPv6 reference or hostname
1603  */

1604  public static boolean isWellFormedAddress(String JavaDoc address) {
1605    if (address == null) {
1606      return false;
1607    }
1608
1609    int addrLength = address.length();
1610    if (addrLength == 0) {
1611      return false;
1612    }
1613    
1614    // Check if the host is a valid IPv6reference.
1615
if (address.startsWith("[")) {
1616      return isWellFormedIPv6Reference(address);
1617    }
1618
1619    // Cannot start with a '.', '-', or end with a '-'.
1620
if (address.startsWith(".") ||
1621        address.startsWith("-") ||
1622        address.endsWith("-")) {
1623      return false;
1624    }
1625
1626    // rightmost domain label starting with digit indicates IP address
1627
// since top level domain label can only start with an alpha
1628
// see RFC 2396 Section 3.2.2
1629
int index = address.lastIndexOf('.');
1630    if (address.endsWith(".")) {
1631      index = address.substring(0, index).lastIndexOf('.');
1632    }
1633
1634    if (index+1 < addrLength && isDigit(address.charAt(index+1))) {
1635      return isWellFormedIPv4Address(address);
1636    }
1637    else {
1638      // hostname = *( domainlabel "." ) toplabel [ "." ]
1639
// domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum
1640
// toplabel = alpha | alpha *( alphanum | "-" ) alphanum
1641

1642      // RFC 2396 states that hostnames take the form described in
1643
// RFC 1034 (Section 3) and RFC 1123 (Section 2.1). According
1644
// to RFC 1034, hostnames are limited to 255 characters.
1645
if (addrLength > 255) {
1646        return false;
1647      }
1648      
1649      // domain labels can contain alphanumerics and '-"
1650
// but must start and end with an alphanumeric
1651
char testChar;
1652      int labelCharCount = 0;
1653
1654      for (int i = 0; i < addrLength; i++) {
1655        testChar = address.charAt(i);
1656        if (testChar == '.') {
1657          if (!isAlphanum(address.charAt(i-1))) {
1658            return false;
1659          }
1660          if (i+1 < addrLength && !isAlphanum(address.charAt(i+1))) {
1661            return false;
1662          }
1663          labelCharCount = 0;
1664        }
1665        else if (!isAlphanum(testChar) && testChar != '-') {
1666          return false;
1667        }
1668        // RFC 1034: Labels must be 63 characters or less.
1669
else if (++labelCharCount > 63) {
1670          return false;
1671        }
1672      }
1673    }
1674    return true;
1675  }
1676  
1677  /**
1678   * <p>Determines whether a string is an IPv4 address as defined by
1679   * RFC 2373, and under the further constraint that it must be a 32-bit
1680   * address. Though not expressed in the grammar, in order to satisfy
1681   * the 32-bit address constraint, each segment of the address cannot
1682   * be greater than 255 (8 bits of information).</p>
1683   *
1684   * <p><code>IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT</code></p>
1685   *
1686   * @return true if the string is a syntactically valid IPv4 address
1687   */

1688  public static boolean isWellFormedIPv4Address(String JavaDoc address) {
1689      
1690      int addrLength = address.length();
1691      char testChar;
1692      int numDots = 0;
1693      int numDigits = 0;
1694
1695      // make sure that 1) we see only digits and dot separators, 2) that
1696
// any dot separator is preceded and followed by a digit and
1697
// 3) that we find 3 dots
1698
//
1699
// RFC 2732 amended RFC 2396 by replacing the definition
1700
// of IPv4address with the one defined by RFC 2373. - mrglavas
1701
//
1702
// IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT
1703
//
1704
// One to three digits must be in each segment.
1705
for (int i = 0; i < addrLength; i++) {
1706        testChar = address.charAt(i);
1707        if (testChar == '.') {
1708          if ((i > 0 && !isDigit(address.charAt(i-1))) ||
1709              (i+1 < addrLength && !isDigit(address.charAt(i+1)))) {
1710            return false;
1711          }
1712          numDigits = 0;
1713          if (++numDots > 3) {
1714            return false;
1715          }
1716        }
1717        else if (!isDigit(testChar)) {
1718          return false;
1719        }
1720        // Check that that there are no more than three digits
1721
// in this segment.
1722
else if (++numDigits > 3) {
1723          return false;
1724        }
1725        // Check that this segment is not greater than 255.
1726
else if (numDigits == 3) {
1727          char first = address.charAt(i-2);
1728          char second = address.charAt(i-1);
1729          if (!(first < '2' ||
1730               (first == '2' &&
1731               (second < '5' ||
1732               (second == '5' && testChar <= '5'))))) {
1733            return false;
1734          }
1735        }
1736      }
1737      return (numDots == 3);
1738  }
1739  
1740  /**
1741   * <p>Determines whether a string is an IPv6 reference as defined
1742   * by RFC 2732, where IPv6address is defined in RFC 2373. The
1743   * IPv6 address is parsed according to Section 2.2 of RFC 2373,
1744   * with the additional constraint that the address be composed of
1745   * 128 bits of information.</p>
1746   *
1747   * <p><code>IPv6reference = "[" IPv6address "]"</code></p>
1748   *
1749   * <p>Note: The BNF expressed in RFC 2373 Appendix B does not
1750   * accurately describe section 2.2, and was in fact removed from
1751   * RFC 3513, the successor of RFC 2373.</p>
1752   *
1753   * @return true if the string is a syntactically valid IPv6 reference
1754   */

1755  public static boolean isWellFormedIPv6Reference(String JavaDoc address) {
1756
1757      int addrLength = address.length();
1758      int index = 1;
1759      int end = addrLength-1;
1760      
1761      // Check if string is a potential match for IPv6reference.
1762
if (!(addrLength > 2 && address.charAt(0) == '['
1763          && address.charAt(end) == ']')) {
1764          return false;
1765      }
1766      
1767      // Counter for the number of 16-bit sections read in the address.
1768
int [] counter = new int[1];
1769      
1770      // Scan hex sequence before possible '::' or IPv4 address.
1771
index = scanHexSequence(address, index, end, counter);
1772      if (index == -1) {
1773          return false;
1774      }
1775      // Address must contain 128-bits of information.
1776
else if (index == end) {
1777          return (counter[0] == 8);
1778      }
1779      
1780      if (index+1 < end && address.charAt(index) == ':') {
1781          if (address.charAt(index+1) == ':') {
1782              // '::' represents at least one 16-bit group of zeros.
1783
if (++counter[0] > 8) {
1784                  return false;
1785              }
1786              index += 2;
1787              // Trailing zeros will fill out the rest of the address.
1788
if (index == end) {
1789                 return true;
1790              }
1791          }
1792          // If the second character wasn't ':', in order to be valid,
1793
// the remainder of the string must match IPv4Address,
1794
// and we must have read exactly 6 16-bit groups.
1795
else {
1796              return (counter[0] == 6) &&
1797                  isWellFormedIPv4Address(address.substring(index+1, end));
1798          }
1799      }
1800      else {
1801          return false;
1802      }
1803      
1804      // 3. Scan hex sequence after '::'.
1805
int prevCount = counter[0];
1806      index = scanHexSequence(address, index, end, counter);
1807
1808      // We've either reached the end of the string, the address ends in
1809
// an IPv4 address, or it is invalid. scanHexSequence has already
1810
// made sure that we have the right number of bits.
1811
return (index == end) ||
1812          (index != -1 && isWellFormedIPv4Address(
1813          address.substring((counter[0] > prevCount) ? index+1 : index, end)));
1814  }
1815  
1816  /**
1817   * Helper method for isWellFormedIPv6Reference which scans the
1818   * hex sequences of an IPv6 address. It returns the index of the
1819   * next character to scan in the address, or -1 if the string
1820   * cannot match a valid IPv6 address.
1821   *
1822   * @param address the string to be scanned
1823   * @param index the beginning index (inclusive)
1824   * @param end the ending index (exclusive)
1825   * @param counter a counter for the number of 16-bit sections read
1826   * in the address
1827   *
1828   * @return the index of the next character to scan, or -1 if the
1829   * string cannot match a valid IPv6 address
1830   */

1831  private static int scanHexSequence (String JavaDoc address, int index, int end, int [] counter) {
1832    
1833      char testChar;
1834      int numDigits = 0;
1835      int start = index;
1836      
1837      // Trying to match the following productions:
1838
// hexseq = hex4 *( ":" hex4)
1839
// hex4 = 1*4HEXDIG
1840
for (; index < end; ++index) {
1841        testChar = address.charAt(index);
1842        if (testChar == ':') {
1843            // IPv6 addresses are 128-bit, so there can be at most eight sections.
1844
if (numDigits > 0 && ++counter[0] > 8) {
1845                return -1;
1846            }
1847            // This could be '::'.
1848
if (numDigits == 0 || ((index+1 < end) && address.charAt(index+1) == ':')) {
1849                return index;
1850            }
1851            numDigits = 0;
1852        }
1853        // This might be invalid or an IPv4address. If it's potentially an IPv4address,
1854
// backup to just after the last valid character that matches hexseq.
1855
else if (!isHex(testChar)) {
1856            if (testChar == '.' && numDigits < 4 && numDigits > 0 && counter[0] <= 6) {
1857                int back = index - numDigits - 1;
1858                return (back >= start) ? back : (back+1);
1859            }
1860            return -1;
1861        }
1862        // There can be at most 4 hex digits per group.
1863
else if (++numDigits > 4) {
1864            return -1;
1865        }
1866      }
1867      return (numDigits > 0 && ++counter[0] <= 8) ? end : -1;
1868  }
1869
1870
1871 /**
1872  * Determine whether a char is a digit.
1873  *
1874  * @return true if the char is betweeen '0' and '9', false otherwise
1875  */

1876  private static boolean isDigit(char p_char) {
1877    return p_char >= '0' && p_char <= '9';
1878  }
1879
1880 /**
1881  * Determine whether a character is a hexadecimal character.
1882  *
1883  * @return true if the char is betweeen '0' and '9', 'a' and 'f'
1884  * or 'A' and 'F', false otherwise
1885  */

1886  private static boolean isHex(char p_char) {
1887    return (p_char <= 'f' && (fgLookupTable[p_char] & ASCII_HEX_CHARACTERS) != 0);
1888  }
1889
1890 /**
1891  * Determine whether a char is an alphabetic character: a-z or A-Z
1892  *
1893  * @return true if the char is alphabetic, false otherwise
1894  */

1895  private static boolean isAlpha(char p_char) {
1896      return ((p_char >= 'a' && p_char <= 'z') || (p_char >= 'A' && p_char <= 'Z' ));
1897  }
1898
1899 /**
1900  * Determine whether a char is an alphanumeric: 0-9, a-z or A-Z
1901  *
1902  * @return true if the char is alphanumeric, false otherwise
1903  */

1904  private static boolean isAlphanum(char p_char) {
1905     return (p_char <= 'z' && (fgLookupTable[p_char] & MASK_ALPHA_NUMERIC) != 0);
1906  }
1907
1908 /**
1909  * Determine whether a character is a reserved character:
1910  * ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '[', or ']'
1911  *
1912  * @return true if the string contains any reserved characters
1913  */

1914  private static boolean isReservedCharacter(char p_char) {
1915     return (p_char <= ']' && (fgLookupTable[p_char] & RESERVED_CHARACTERS) != 0);
1916  }
1917
1918 /**
1919  * Determine whether a char is an unreserved character.
1920  *
1921  * @return true if the char is unreserved, false otherwise
1922  */

1923  private static boolean isUnreservedCharacter(char p_char) {
1924     return (p_char <= '~' && (fgLookupTable[p_char] & MASK_UNRESERVED_MASK) != 0);
1925  }
1926
1927 /**
1928  * Determine whether a char is a URI character (reserved or
1929  * unreserved, not including '%' for escaped octets).
1930  *
1931  * @return true if the char is a URI character, false otherwise
1932  */

1933  private static boolean isURICharacter (char p_char) {
1934      return (p_char <= '~' && (fgLookupTable[p_char] & MASK_URI_CHARACTER) != 0);
1935  }
1936
1937 /**
1938  * Determine whether a char is a scheme character.
1939  *
1940  * @return true if the char is a scheme character, false otherwise
1941  */

1942  private static boolean isSchemeCharacter (char p_char) {
1943      return (p_char <= 'z' && (fgLookupTable[p_char] & MASK_SCHEME_CHARACTER) != 0);
1944  }
1945
1946 /**
1947  * Determine whether a char is a userinfo character.
1948  *
1949  * @return true if the char is a userinfo character, false otherwise
1950  */

1951  private static boolean isUserinfoCharacter (char p_char) {
1952      return (p_char <= 'z' && (fgLookupTable[p_char] & MASK_USERINFO_CHARACTER) != 0);
1953  }
1954  
1955 /**
1956  * Determine whether a char is a path character.
1957  *
1958  * @return true if the char is a path character, false otherwise
1959  */

1960  private static boolean isPathCharacter (char p_char) {
1961      return (p_char <= '~' && (fgLookupTable[p_char] & MASK_PATH_CHARACTER) != 0);
1962  }
1963
1964
1965 /**
1966  * Determine whether a given string contains only URI characters (also
1967  * called "uric" in RFC 2396). uric consist of all reserved
1968  * characters, unreserved characters and escaped characters.
1969  *
1970  * @return true if the string is comprised of uric, false otherwise
1971  */

1972  private static boolean isURIString(String JavaDoc p_uric) {
1973    if (p_uric == null) {
1974      return false;
1975    }
1976    int end = p_uric.length();
1977    char testChar = '\0';
1978    for (int i = 0; i < end; i++) {
1979      testChar = p_uric.charAt(i);
1980      if (testChar == '%') {
1981        if (i+2 >= end ||
1982            !isHex(p_uric.charAt(i+1)) ||
1983            !isHex(p_uric.charAt(i+2))) {
1984          return false;
1985        }
1986        else {
1987          i += 2;
1988          continue;
1989        }
1990      }
1991      if (isURICharacter(testChar)) {
1992          continue;
1993      }
1994      else {
1995        return false;
1996      }
1997    }
1998    return true;
1999  }
2000}
2001
Popular Tags