View Javadoc
1   /*
2    * reserved comment block
3    * DO NOT REMOVE OR ALTER!
4    */
5   /*
6    * Copyright 1999-2005 The Apache Software Foundation.
7    *
8    * Licensed under the Apache License, Version 2.0 (the "License");
9    * you may not use this file except in compliance with the License.
10   * You may obtain a copy of the License at
11   *
12   *      http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS,
16   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17   * See the License for the specific language governing permissions and
18   * limitations under the License.
19   */
20  
21  package com.sun.org.apache.xerces.internal.util;
22  
23  import java.io.IOException;
24  import java.io.Serializable;
25  import java.util.Objects;
26  
27  /**********************************************************************
28  * A class to represent a Uniform Resource Identifier (URI). This class
29  * is designed to handle the parsing of URIs and provide access to
30  * the various components (scheme, host, port, userinfo, path, query
31  * string and fragment) that may constitute a URI.
32  * <p>
33  * Parsing of a URI specification is done according to the URI
34  * syntax described in
35  * <a href="http://www.ietf.org/rfc/rfc2396.txt?number=2396">RFC 2396</a>,
36  * and amended by
37  * <a href="http://www.ietf.org/rfc/rfc2732.txt?number=2732">RFC 2732</a>.
38  * <p>
39  * Every absolute URI consists of a scheme, followed by a colon (':'),
40  * followed by a scheme-specific part. For URIs that follow the
41  * "generic URI" syntax, the scheme-specific part begins with two
42  * slashes ("//") and may be followed by an authority segment (comprised
43  * of user information, host, and port), path segment, query segment
44  * and fragment. Note that RFC 2396 no longer specifies the use of the
45  * parameters segment and excludes the "user:password" syntax as part of
46  * the authority segment. If "user:password" appears in a URI, the entire
47  * user/password string is stored as userinfo.
48  * <p>
49  * For URIs that do not follow the "generic URI" syntax (e.g. mailto),
50  * the entire scheme-specific part is treated as the "path" portion
51  * of the URI.
52  * <p>
53  * Note that, unlike the java.net.URL class, this class does not provide
54  * any built-in network access functionality nor does it provide any
55  * scheme-specific functionality (for example, it does not know a
56  * default port for a specific scheme). Rather, it only knows the
57  * grammar and basic set of operations that can be applied to a URI.
58  *
59  *
60  **********************************************************************/
61   public class URI implements Serializable {
62  
63    /*******************************************************************
64    * MalformedURIExceptions are thrown in the process of building a URI
65    * or setting fields on a URI when an operation would result in an
66    * invalid URI specification.
67    *
68    ********************************************************************/
69    public static class MalformedURIException extends IOException {
70  
71     /** Serialization version. */
72     static final long serialVersionUID = -6695054834342951930L;
73  
74     /******************************************************************
75      * Constructs a <code>MalformedURIException</code> with no specified
76      * detail message.
77      ******************************************************************/
78      public MalformedURIException() {
79        super();
80      }
81  
82      /*****************************************************************
83      * Constructs a <code>MalformedURIException</code> with the
84      * specified detail message.
85      *
86      * @param p_msg the detail message.
87      ******************************************************************/
88      public MalformedURIException(String p_msg) {
89        super(p_msg);
90      }
91    }
92  
93    /** Serialization version. */
94    static final long serialVersionUID = 1601921774685357214L;
95  
96    private static final byte [] fgLookupTable = new byte[128];
97  
98    /**
99     * Character Classes
100    */
101 
102   /** reserved characters ;/?:@&=+$,[] */
103   //RFC 2732 added '[' and ']' as reserved characters
104   private static final int RESERVED_CHARACTERS = 0x01;
105 
106   /** URI punctuation mark characters: -_.!~*'() - these, combined with
107       alphanumerics, constitute the "unreserved" characters */
108   private static final int MARK_CHARACTERS = 0x02;
109 
110   /** scheme can be composed of alphanumerics and these characters: +-. */
111   private static final int SCHEME_CHARACTERS = 0x04;
112 
113   /** userinfo can be composed of unreserved, escaped and these
114       characters: ;:&=+$, */
115   private static final int USERINFO_CHARACTERS = 0x08;
116 
117   /** ASCII letter characters */
118   private static final int ASCII_ALPHA_CHARACTERS = 0x10;
119 
120   /** ASCII digit characters */
121   private static final int ASCII_DIGIT_CHARACTERS = 0x20;
122 
123   /** ASCII hex characters */
124   private static final int ASCII_HEX_CHARACTERS = 0x40;
125 
126   /** Path characters */
127   private static final int PATH_CHARACTERS = 0x80;
128 
129   /** Mask for alpha-numeric characters */
130   private static final int MASK_ALPHA_NUMERIC = ASCII_ALPHA_CHARACTERS | ASCII_DIGIT_CHARACTERS;
131 
132   /** Mask for unreserved characters */
133   private static final int MASK_UNRESERVED_MASK = MASK_ALPHA_NUMERIC | MARK_CHARACTERS;
134 
135   /** Mask for URI allowable characters except for % */
136   private static final int MASK_URI_CHARACTER = MASK_UNRESERVED_MASK | RESERVED_CHARACTERS;
137 
138   /** Mask for scheme characters */
139   private static final int MASK_SCHEME_CHARACTER = MASK_ALPHA_NUMERIC | SCHEME_CHARACTERS;
140 
141   /** Mask for userinfo characters */
142   private static final int MASK_USERINFO_CHARACTER = MASK_UNRESERVED_MASK | USERINFO_CHARACTERS;
143 
144   /** Mask for path characters */
145   private static final int MASK_PATH_CHARACTER = MASK_UNRESERVED_MASK | PATH_CHARACTERS;
146 
147   static {
148       // Add ASCII Digits and ASCII Hex Numbers
149       for (int i = '0'; i <= '9'; ++i) {
150           fgLookupTable[i] |= ASCII_DIGIT_CHARACTERS | ASCII_HEX_CHARACTERS;
151       }
152 
153       // Add ASCII Letters and ASCII Hex Numbers
154       for (int i = 'A'; i <= 'F'; ++i) {
155           fgLookupTable[i] |= ASCII_ALPHA_CHARACTERS | ASCII_HEX_CHARACTERS;
156           fgLookupTable[i+0x00000020] |= ASCII_ALPHA_CHARACTERS | ASCII_HEX_CHARACTERS;
157       }
158 
159       // Add ASCII Letters
160       for (int i = 'G'; i <= 'Z'; ++i) {
161           fgLookupTable[i] |= ASCII_ALPHA_CHARACTERS;
162           fgLookupTable[i+0x00000020] |= ASCII_ALPHA_CHARACTERS;
163       }
164 
165       // Add Reserved Characters
166       fgLookupTable[';'] |= RESERVED_CHARACTERS;
167       fgLookupTable['/'] |= RESERVED_CHARACTERS;
168       fgLookupTable['?'] |= RESERVED_CHARACTERS;
169       fgLookupTable[':'] |= RESERVED_CHARACTERS;
170       fgLookupTable['@'] |= RESERVED_CHARACTERS;
171       fgLookupTable['&'] |= RESERVED_CHARACTERS;
172       fgLookupTable['='] |= RESERVED_CHARACTERS;
173       fgLookupTable['+'] |= RESERVED_CHARACTERS;
174       fgLookupTable['$'] |= RESERVED_CHARACTERS;
175       fgLookupTable[','] |= RESERVED_CHARACTERS;
176       fgLookupTable['['] |= RESERVED_CHARACTERS;
177       fgLookupTable[']'] |= RESERVED_CHARACTERS;
178 
179       // Add Mark Characters
180       fgLookupTable['-'] |= MARK_CHARACTERS;
181       fgLookupTable['_'] |= MARK_CHARACTERS;
182       fgLookupTable['.'] |= MARK_CHARACTERS;
183       fgLookupTable['!'] |= MARK_CHARACTERS;
184       fgLookupTable['~'] |= MARK_CHARACTERS;
185       fgLookupTable['*'] |= MARK_CHARACTERS;
186       fgLookupTable['\''] |= MARK_CHARACTERS;
187       fgLookupTable['('] |= MARK_CHARACTERS;
188       fgLookupTable[')'] |= MARK_CHARACTERS;
189 
190       // Add Scheme Characters
191       fgLookupTable['+'] |= SCHEME_CHARACTERS;
192       fgLookupTable['-'] |= SCHEME_CHARACTERS;
193       fgLookupTable['.'] |= SCHEME_CHARACTERS;
194 
195       // Add Userinfo Characters
196       fgLookupTable[';'] |= USERINFO_CHARACTERS;
197       fgLookupTable[':'] |= USERINFO_CHARACTERS;
198       fgLookupTable['&'] |= USERINFO_CHARACTERS;
199       fgLookupTable['='] |= USERINFO_CHARACTERS;
200       fgLookupTable['+'] |= USERINFO_CHARACTERS;
201       fgLookupTable['$'] |= USERINFO_CHARACTERS;
202       fgLookupTable[','] |= USERINFO_CHARACTERS;
203 
204       // Add Path Characters
205       fgLookupTable[';'] |= PATH_CHARACTERS;
206       fgLookupTable['/'] |= PATH_CHARACTERS;
207       fgLookupTable[':'] |= PATH_CHARACTERS;
208       fgLookupTable['@'] |= PATH_CHARACTERS;
209       fgLookupTable['&'] |= PATH_CHARACTERS;
210       fgLookupTable['='] |= PATH_CHARACTERS;
211       fgLookupTable['+'] |= PATH_CHARACTERS;
212       fgLookupTable['$'] |= PATH_CHARACTERS;
213       fgLookupTable[','] |= PATH_CHARACTERS;
214   }
215 
216   /** Stores the scheme (usually the protocol) for this URI. */
217   private String m_scheme = null;
218 
219   /** If specified, stores the userinfo for this URI; otherwise null */
220   private String m_userinfo = null;
221 
222   /** If specified, stores the host for this URI; otherwise null */
223   private String m_host = null;
224 
225   /** If specified, stores the port for this URI; otherwise -1 */
226   private int m_port = -1;
227 
228   /** If specified, stores the registry based authority for this URI; otherwise -1 */
229   private String m_regAuthority = null;
230 
231   /** If specified, stores the path for this URI; otherwise null */
232   private String m_path = null;
233 
234   /** If specified, stores the query string for this URI; otherwise
235       null.  */
236   private String m_queryString = null;
237 
238   /** If specified, stores the fragment for this URI; otherwise null */
239   private String m_fragment = null;
240 
241   private static boolean DEBUG = false;
242 
243   /**
244   * Construct a new and uninitialized URI.
245   */
246   public URI() {
247   }
248 
249  /**
250   * Construct a new URI from another URI. All fields for this URI are
251   * set equal to the fields of the URI passed in.
252   *
253   * @param p_other the URI to copy (cannot be null)
254   */
255   public URI(URI p_other) {
256     initialize(p_other);
257   }
258 
259  /**
260   * Construct a new URI from a URI specification string. If the
261   * specification follows the "generic URI" syntax, (two slashes
262   * following the first colon), the specification will be parsed
263   * accordingly - setting the scheme, userinfo, host,port, path, query
264   * string and fragment fields as necessary. If the specification does
265   * not follow the "generic URI" syntax, the specification is parsed
266   * into a scheme and scheme-specific part (stored as the path) only.
267   *
268   * @param p_uriSpec the URI specification string (cannot be null or
269   *                  empty)
270   *
271   * @exception MalformedURIException if p_uriSpec violates any syntax
272   *                                   rules
273   */
274   public URI(String p_uriSpec) throws MalformedURIException {
275     this((URI)null, p_uriSpec);
276   }
277 
278   /**
279    * Construct a new URI from a URI specification string. If the
280    * specification follows the "generic URI" syntax, (two slashes
281    * following the first colon), the specification will be parsed
282    * accordingly - setting the scheme, userinfo, host,port, path, query
283    * string and fragment fields as necessary. If the specification does
284    * not follow the "generic URI" syntax, the specification is parsed
285    * into a scheme and scheme-specific part (stored as the path) only.
286    * Construct a relative URI if boolean is assigned to "true"
287    * and p_uriSpec is not valid absolute URI, instead of throwing an exception.
288    *
289    * @param p_uriSpec the URI specification string (cannot be null or
290    *                  empty)
291    * @param allowNonAbsoluteURI true to permit non-absolute URIs,
292    *                            false otherwise.
293    *
294    * @exception MalformedURIException if p_uriSpec violates any syntax
295    *                                   rules
296    */
297   public URI(String p_uriSpec, boolean allowNonAbsoluteURI) throws MalformedURIException {
298       this((URI)null, p_uriSpec, allowNonAbsoluteURI);
299   }
300 
301  /**
302   * Construct a new URI from a base URI and a URI specification string.
303   * The URI specification string may be a relative URI.
304   *
305   * @param p_base the base URI (cannot be null if p_uriSpec is null or
306   *               empty)
307   * @param p_uriSpec the URI specification string (cannot be null or
308   *                  empty if p_base is null)
309   *
310   * @exception MalformedURIException if p_uriSpec violates any syntax
311   *                                  rules
312   */
313   public URI(URI p_base, String p_uriSpec) throws MalformedURIException {
314     initialize(p_base, p_uriSpec);
315   }
316 
317   /**
318    * Construct a new URI from a base URI and a URI specification string.
319    * The URI specification string may be a relative URI.
320    * Construct a relative URI if boolean is assigned to "true"
321    * and p_uriSpec is not valid absolute URI and p_base is null
322    * instead of throwing an exception.
323    *
324    * @param p_base the base URI (cannot be null if p_uriSpec is null or
325    *               empty)
326    * @param p_uriSpec the URI specification string (cannot be null or
327    *                  empty if p_base is null)
328    * @param allowNonAbsoluteURI true to permit non-absolute URIs,
329    *                            false otherwise.
330    *
331    * @exception MalformedURIException if p_uriSpec violates any syntax
332    *                                  rules
333    */
334   public URI(URI p_base, String p_uriSpec, boolean allowNonAbsoluteURI) throws MalformedURIException {
335       initialize(p_base, p_uriSpec, allowNonAbsoluteURI);
336   }
337 
338  /**
339   * Construct a new URI that does not follow the generic URI syntax.
340   * Only the scheme and scheme-specific part (stored as the path) are
341   * initialized.
342   *
343   * @param p_scheme the URI scheme (cannot be null or empty)
344   * @param p_schemeSpecificPart the scheme-specific part (cannot be
345   *                             null or empty)
346   *
347   * @exception MalformedURIException if p_scheme violates any
348   *                                  syntax rules
349   */
350   public URI(String p_scheme, String p_schemeSpecificPart)
351              throws MalformedURIException {
352     if (p_scheme == null || p_scheme.trim().length() == 0) {
353       throw new MalformedURIException(
354             "Cannot construct URI with null/empty scheme!");
355     }
356     if (p_schemeSpecificPart == null ||
357         p_schemeSpecificPart.trim().length() == 0) {
358       throw new MalformedURIException(
359           "Cannot construct URI with null/empty scheme-specific part!");
360     }
361     setScheme(p_scheme);
362     setPath(p_schemeSpecificPart);
363   }
364 
365  /**
366   * Construct a new URI that follows the generic URI syntax from its
367   * component parts. Each component is validated for syntax and some
368   * basic semantic checks are performed as well.  See the individual
369   * setter methods for specifics.
370   *
371   * @param p_scheme the URI scheme (cannot be null or empty)
372   * @param p_host the hostname, IPv4 address or IPv6 reference for the URI
373   * @param p_path the URI path - if the path contains '?' or '#',
374   *               then the query string and/or fragment will be
375   *               set from the path; however, if the query and
376   *               fragment are specified both in the path and as
377   *               separate parameters, an exception is thrown
378   * @param p_queryString the URI query string (cannot be specified
379   *                      if path is null)
380   * @param p_fragment the URI fragment (cannot be specified if path
381   *                   is null)
382   *
383   * @exception MalformedURIException if any of the parameters violates
384   *                                  syntax rules or semantic rules
385   */
386   public URI(String p_scheme, String p_host, String p_path,
387              String p_queryString, String p_fragment)
388          throws MalformedURIException {
389     this(p_scheme, null, p_host, -1, p_path, p_queryString, p_fragment);
390   }
391 
392  /**
393   * Construct a new URI that follows the generic URI syntax from its
394   * component parts. Each component is validated for syntax and some
395   * basic semantic checks are performed as well.  See the individual
396   * setter methods for specifics.
397   *
398   * @param p_scheme the URI scheme (cannot be null or empty)
399   * @param p_userinfo the URI userinfo (cannot be specified if host
400   *                   is null)
401   * @param p_host the hostname, IPv4 address or IPv6 reference for the URI
402   * @param p_port the URI port (may be -1 for "unspecified"; cannot
403   *               be specified if host is null)
404   * @param p_path the URI path - if the path contains '?' or '#',
405   *               then the query string and/or fragment will be
406   *               set from the path; however, if the query and
407   *               fragment are specified both in the path and as
408   *               separate parameters, an exception is thrown
409   * @param p_queryString the URI query string (cannot be specified
410   *                      if path is null)
411   * @param p_fragment the URI fragment (cannot be specified if path
412   *                   is null)
413   *
414   * @exception MalformedURIException if any of the parameters violates
415   *                                  syntax rules or semantic rules
416   */
417   public URI(String p_scheme, String p_userinfo,
418              String p_host, int p_port, String p_path,
419              String p_queryString, String p_fragment)
420          throws MalformedURIException {
421     if (p_scheme == null || p_scheme.trim().length() == 0) {
422       throw new MalformedURIException("Scheme is required!");
423     }
424 
425     if (p_host == null) {
426       if (p_userinfo != null) {
427         throw new MalformedURIException(
428              "Userinfo may not be specified if host is not specified!");
429       }
430       if (p_port != -1) {
431         throw new MalformedURIException(
432              "Port may not be specified if host is not specified!");
433       }
434     }
435 
436     if (p_path != null) {
437       if (p_path.indexOf('?') != -1 && p_queryString != null) {
438         throw new MalformedURIException(
439           "Query string cannot be specified in path and query string!");
440       }
441 
442       if (p_path.indexOf('#') != -1 && p_fragment != null) {
443         throw new MalformedURIException(
444           "Fragment cannot be specified in both the path and fragment!");
445       }
446     }
447 
448     setScheme(p_scheme);
449     setHost(p_host);
450     setPort(p_port);
451     setUserinfo(p_userinfo);
452     setPath(p_path);
453     setQueryString(p_queryString);
454     setFragment(p_fragment);
455   }
456 
457  /**
458   * Initialize all fields of this URI from another URI.
459   *
460   * @param p_other the URI to copy (cannot be null)
461   */
462   private void initialize(URI p_other) {
463     m_scheme = p_other.getScheme();
464     m_userinfo = p_other.getUserinfo();
465     m_host = p_other.getHost();
466     m_port = p_other.getPort();
467     m_regAuthority = p_other.getRegBasedAuthority();
468     m_path = p_other.getPath();
469     m_queryString = p_other.getQueryString();
470     m_fragment = p_other.getFragment();
471   }
472 
473   /**
474    * Initializes this URI from a base URI and a URI specification string.
475    * See RFC 2396 Section 4 and Appendix B for specifications on parsing
476    * the URI and Section 5 for specifications on resolving relative URIs
477    * and relative paths.
478    *
479    * @param p_base the base URI (may be null if p_uriSpec is an absolute
480    *               URI)
481    * @param p_uriSpec the URI spec string which may be an absolute or
482    *                  relative URI (can only be null/empty if p_base
483    *                  is not null)
484    * @param allowNonAbsoluteURI true to permit non-absolute URIs,
485    *                         in case of relative URI, false otherwise.
486    *
487    * @exception MalformedURIException if p_base is null and p_uriSpec
488    *                                  is not an absolute URI or if
489    *                                  p_uriSpec violates syntax rules
490    */
491   private void initialize(URI p_base, String p_uriSpec, boolean allowNonAbsoluteURI)
492       throws MalformedURIException {
493 
494       String uriSpec = p_uriSpec;
495       int uriSpecLen = (uriSpec != null) ? uriSpec.length() : 0;
496 
497       if (p_base == null && uriSpecLen == 0) {
498           if (allowNonAbsoluteURI) {
499               m_path = "";
500               return;
501           }
502           throw new MalformedURIException("Cannot initialize URI with empty parameters.");
503       }
504 
505       // just make a copy of the base if spec is empty
506       if (uriSpecLen == 0) {
507           initialize(p_base);
508           return;
509       }
510 
511       int index = 0;
512 
513       // Check for scheme, which must be before '/', '?' or '#'.
514       int colonIdx = uriSpec.indexOf(':');
515       if (colonIdx != -1) {
516           final int searchFrom = colonIdx - 1;
517           // search backwards starting from character before ':'.
518           int slashIdx = uriSpec.lastIndexOf('/', searchFrom);
519           int queryIdx = uriSpec.lastIndexOf('?', searchFrom);
520           int fragmentIdx = uriSpec.lastIndexOf('#', searchFrom);
521 
522           if (colonIdx == 0 || slashIdx != -1 ||
523               queryIdx != -1 || fragmentIdx != -1) {
524               // A standalone base is a valid URI according to spec
525               if (colonIdx == 0 || (p_base == null && fragmentIdx != 0 && !allowNonAbsoluteURI)) {
526                   throw new MalformedURIException("No scheme found in URI.");
527               }
528           }
529           else {
530               initializeScheme(uriSpec);
531               index = m_scheme.length()+1;
532 
533               // Neither 'scheme:' or 'scheme:#fragment' are valid URIs.
534               if (colonIdx == uriSpecLen - 1 || uriSpec.charAt(colonIdx+1) == '#') {
535                   throw new MalformedURIException("Scheme specific part cannot be empty.");
536               }
537           }
538       }
539       else if (p_base == null && uriSpec.indexOf('#') != 0 && !allowNonAbsoluteURI) {
540           throw new MalformedURIException("No scheme found in URI.");
541       }
542 
543       // Two slashes means we may have authority, but definitely means we're either
544       // matching net_path or abs_path. These two productions are ambiguous in that
545       // every net_path (except those containing an IPv6Reference) is an abs_path.
546       // RFC 2396 resolves this ambiguity by applying a greedy left most matching rule.
547       // Try matching net_path first, and if that fails we don't have authority so
548       // then attempt to match abs_path.
549       //
550       // net_path = "//" authority [ abs_path ]
551       // abs_path = "/"  path_segments
552       if (((index+1) < uriSpecLen) &&
553           (uriSpec.charAt(index) == '/' && uriSpec.charAt(index+1) == '/')) {
554           index += 2;
555           int startPos = index;
556 
557           // Authority will be everything up to path, query or fragment
558           char testChar = '\0';
559           while (index < uriSpecLen) {
560               testChar = uriSpec.charAt(index);
561               if (testChar == '/' || testChar == '?' || testChar == '#') {
562                   break;
563               }
564               index++;
565           }
566 
567           // Attempt to parse authority. If the section is an empty string
568           // this is a valid server based authority, so set the host to this
569           // value.
570           if (index > startPos) {
571               // If we didn't find authority we need to back up. Attempt to
572               // match against abs_path next.
573               if (!initializeAuthority(uriSpec.substring(startPos, index))) {
574                   index = startPos - 2;
575               }
576           }
577           else {
578               m_host = "";
579           }
580       }
581 
582       initializePath(uriSpec, index);
583 
584       // Resolve relative URI to base URI - see RFC 2396 Section 5.2
585       // In some cases, it might make more sense to throw an exception
586       // (when scheme is specified is the string spec and the base URI
587       // is also specified, for example), but we're just following the
588       // RFC specifications
589       if (p_base != null) {
590           absolutize(p_base);
591       }
592   }
593 
594  /**
595   * Initializes this URI from a base URI and a URI specification string.
596   * See RFC 2396 Section 4 and Appendix B for specifications on parsing
597   * the URI and Section 5 for specifications on resolving relative URIs
598   * and relative paths.
599   *
600   * @param p_base the base URI (may be null if p_uriSpec is an absolute
601   *               URI)
602   * @param p_uriSpec the URI spec string which may be an absolute or
603   *                  relative URI (can only be null/empty if p_base
604   *                  is not null)
605   *
606   * @exception MalformedURIException if p_base is null and p_uriSpec
607   *                                  is not an absolute URI or if
608   *                                  p_uriSpec violates syntax rules
609   */
610   private void initialize(URI p_base, String p_uriSpec)
611                          throws MalformedURIException {
612 
613     String uriSpec = p_uriSpec;
614     int uriSpecLen = (uriSpec != null) ? uriSpec.length() : 0;
615 
616     if (p_base == null && uriSpecLen == 0) {
617       throw new MalformedURIException(
618                   "Cannot initialize URI with empty parameters.");
619     }
620 
621     // just make a copy of the base if spec is empty
622     if (uriSpecLen == 0) {
623       initialize(p_base);
624       return;
625     }
626 
627     int index = 0;
628 
629     // Check for scheme, which must be before '/', '?' or '#'.
630     int colonIdx = uriSpec.indexOf(':');
631     if (colonIdx != -1) {
632         final int searchFrom = colonIdx - 1;
633         // search backwards starting from character before ':'.
634         int slashIdx = uriSpec.lastIndexOf('/', searchFrom);
635         int queryIdx = uriSpec.lastIndexOf('?', searchFrom);
636         int fragmentIdx = uriSpec.lastIndexOf('#', searchFrom);
637 
638         if (colonIdx == 0 || slashIdx != -1 ||
639             queryIdx != -1 || fragmentIdx != -1) {
640             // A standalone base is a valid URI according to spec
641             if (colonIdx == 0 || (p_base == null && fragmentIdx != 0)) {
642                 throw new MalformedURIException("No scheme found in URI.");
643             }
644         }
645         else {
646             initializeScheme(uriSpec);
647             index = m_scheme.length()+1;
648 
649             // Neither 'scheme:' or 'scheme:#fragment' are valid URIs.
650             if (colonIdx == uriSpecLen - 1 || uriSpec.charAt(colonIdx+1) == '#') {
651                 throw new MalformedURIException("Scheme specific part cannot be empty.");
652             }
653         }
654     }
655     else if (p_base == null && uriSpec.indexOf('#') != 0) {
656         throw new MalformedURIException("No scheme found in URI.");
657     }
658 
659     // Two slashes means we may have authority, but definitely means we're either
660     // matching net_path or abs_path. These two productions are ambiguous in that
661     // every net_path (except those containing an IPv6Reference) is an abs_path.
662     // RFC 2396 resolves this ambiguity by applying a greedy left most matching rule.
663     // Try matching net_path first, and if that fails we don't have authority so
664     // then attempt to match abs_path.
665     //
666     // net_path = "//" authority [ abs_path ]
667     // abs_path = "/"  path_segments
668     if (((index+1) < uriSpecLen) &&
669         (uriSpec.charAt(index) == '/' && uriSpec.charAt(index+1) == '/')) {
670       index += 2;
671       int startPos = index;
672 
673       // Authority will be everything up to path, query or fragment
674       char testChar = '\0';
675       while (index < uriSpecLen) {
676         testChar = uriSpec.charAt(index);
677         if (testChar == '/' || testChar == '?' || testChar == '#') {
678           break;
679         }
680         index++;
681       }
682 
683       // Attempt to parse authority. If the section is an empty string
684       // this is a valid server based authority, so set the host to this
685       // value.
686       if (index > startPos) {
687         // If we didn't find authority we need to back up. Attempt to
688         // match against abs_path next.
689         if (!initializeAuthority(uriSpec.substring(startPos, index))) {
690           index = startPos - 2;
691         }
692       } else if (index < uriSpecLen) {
693         //Same as java.net.URI:
694         // DEVIATION: Allow empty authority prior to non-empty
695         // path, query component or fragment identifier
696         m_host = "";
697       } else {
698         throw new MalformedURIException("Expected authority.");
699       }
700     }
701 
702     initializePath(uriSpec, index);
703 
704     // Resolve relative URI to base URI - see RFC 2396 Section 5.2
705     // In some cases, it might make more sense to throw an exception
706     // (when scheme is specified is the string spec and the base URI
707     // is also specified, for example), but we're just following the
708     // RFC specifications
709     if (p_base != null) {
710         absolutize(p_base);
711     }
712   }
713 
714   /**
715    * Absolutize URI with given base URI.
716    *
717    * @param p_base base URI for absolutization
718    */
719   public void absolutize(URI p_base) {
720 
721       // check to see if this is the current doc - RFC 2396 5.2 #2
722       // note that this is slightly different from the RFC spec in that
723       // we don't include the check for query string being null
724       // - this handles cases where the urispec is just a query
725       // string or a fragment (e.g. "?y" or "#s") -
726       // see <http://www.ics.uci.edu/~fielding/url/test1.html> which
727       // identified this as a bug in the RFC
728       if (m_path.length() == 0 && m_scheme == null &&
729           m_host == null && m_regAuthority == null) {
730           m_scheme = p_base.getScheme();
731           m_userinfo = p_base.getUserinfo();
732           m_host = p_base.getHost();
733           m_port = p_base.getPort();
734           m_regAuthority = p_base.getRegBasedAuthority();
735           m_path = p_base.getPath();
736 
737           if (m_queryString == null) {
738               m_queryString = p_base.getQueryString();
739 
740               if (m_fragment == null) {
741                   m_fragment = p_base.getFragment();
742               }
743           }
744           return;
745       }
746 
747       // check for scheme - RFC 2396 5.2 #3
748       // if we found a scheme, it means absolute URI, so we're done
749       if (m_scheme == null) {
750           m_scheme = p_base.getScheme();
751       }
752       else {
753           return;
754       }
755 
756       // check for authority - RFC 2396 5.2 #4
757       // if we found a host, then we've got a network path, so we're done
758       if (m_host == null && m_regAuthority == null) {
759           m_userinfo = p_base.getUserinfo();
760           m_host = p_base.getHost();
761           m_port = p_base.getPort();
762           m_regAuthority = p_base.getRegBasedAuthority();
763       }
764       else {
765           return;
766       }
767 
768       // check for absolute path - RFC 2396 5.2 #5
769       if (m_path.length() > 0 &&
770               m_path.startsWith("/")) {
771           return;
772       }
773 
774       // if we get to this point, we need to resolve relative path
775       // RFC 2396 5.2 #6
776       String path = "";
777       String basePath = p_base.getPath();
778 
779       // 6a - get all but the last segment of the base URI path
780       if (basePath != null && basePath.length() > 0) {
781           int lastSlash = basePath.lastIndexOf('/');
782           if (lastSlash != -1) {
783               path = basePath.substring(0, lastSlash+1);
784           }
785       }
786       else if (m_path.length() > 0) {
787           path = "/";
788       }
789 
790       // 6b - append the relative URI path
791       path = path.concat(m_path);
792 
793       // 6c - remove all "./" where "." is a complete path segment
794       int index = -1;
795       while ((index = path.indexOf("/./")) != -1) {
796           path = path.substring(0, index+1).concat(path.substring(index+3));
797       }
798 
799       // 6d - remove "." if path ends with "." as a complete path segment
800       if (path.endsWith("/.")) {
801           path = path.substring(0, path.length()-1);
802       }
803 
804       // 6e - remove all "<segment>/../" where "<segment>" is a complete
805       // path segment not equal to ".."
806       index = 1;
807       int segIndex = -1;
808       String tempString = null;
809 
810       while ((index = path.indexOf("/../", index)) > 0) {
811           tempString = path.substring(0, path.indexOf("/../"));
812           segIndex = tempString.lastIndexOf('/');
813           if (segIndex != -1) {
814               if (!tempString.substring(segIndex).equals("..")) {
815                   path = path.substring(0, segIndex+1).concat(path.substring(index+4));
816                   index = segIndex;
817               }
818               else {
819                   index += 4;
820               }
821           }
822           else {
823               index += 4;
824           }
825       }
826 
827       // 6f - remove ending "<segment>/.." where "<segment>" is a
828       // complete path segment
829       if (path.endsWith("/..")) {
830           tempString = path.substring(0, path.length()-3);
831           segIndex = tempString.lastIndexOf('/');
832           if (segIndex != -1) {
833               path = path.substring(0, segIndex+1);
834           }
835       }
836       m_path = path;
837   }
838 
839  /**
840   * Initialize the scheme for this URI from a URI string spec.
841   *
842   * @param p_uriSpec the URI specification (cannot be null)
843   *
844   * @exception MalformedURIException if URI does not have a conformant
845   *                                  scheme
846   */
847   private void initializeScheme(String p_uriSpec)
848                  throws MalformedURIException {
849     int uriSpecLen = p_uriSpec.length();
850     int index = 0;
851     String scheme = null;
852     char testChar = '\0';
853 
854     while (index < uriSpecLen) {
855       testChar = p_uriSpec.charAt(index);
856       if (testChar == ':' || testChar == '/' ||
857           testChar == '?' || testChar == '#') {
858         break;
859       }
860       index++;
861     }
862     scheme = p_uriSpec.substring(0, index);
863 
864     if (scheme.length() == 0) {
865       throw new MalformedURIException("No scheme found in URI.");
866     }
867     else {
868       setScheme(scheme);
869     }
870   }
871 
872  /**
873   * Initialize the authority (either server or registry based)
874   * for this URI from a URI string spec.
875   *
876   * @param p_uriSpec the URI specification (cannot be null)
877   *
878   * @return true if the given string matched server or registry
879   * based authority
880   */
881   private boolean initializeAuthority(String p_uriSpec) {
882 
883     int index = 0;
884     int start = 0;
885     int end = p_uriSpec.length();
886 
887     char testChar = '\0';
888     String userinfo = null;
889 
890     // userinfo is everything up to @
891     if (p_uriSpec.indexOf('@', start) != -1) {
892       while (index < end) {
893         testChar = p_uriSpec.charAt(index);
894         if (testChar == '@') {
895           break;
896         }
897         index++;
898       }
899       userinfo = p_uriSpec.substring(start, index);
900       index++;
901     }
902 
903     // host is everything up to last ':', or up to
904     // and including ']' if followed by ':'.
905     String host = null;
906     start = index;
907     boolean hasPort = false;
908     if (index < end) {
909       if (p_uriSpec.charAt(start) == '[') {
910         int bracketIndex = p_uriSpec.indexOf(']', start);
911         index = (bracketIndex != -1) ? bracketIndex : end;
912         if (index+1 < end && p_uriSpec.charAt(index+1) == ':') {
913           ++index;
914           hasPort = true;
915         }
916         else {
917           index = end;
918         }
919       }
920       else {
921         int colonIndex = p_uriSpec.lastIndexOf(':', end);
922         index = (colonIndex > start) ? colonIndex : end;
923         hasPort = (index != end);
924       }
925     }
926     host = p_uriSpec.substring(start, index);
927     int port = -1;
928     if (host.length() > 0) {
929       // port
930       if (hasPort) {
931         index++;
932         start = index;
933         while (index < end) {
934           index++;
935         }
936         String portStr = p_uriSpec.substring(start, index);
937         if (portStr.length() > 0) {
938           // REVISIT: Remove this code.
939           /** for (int i = 0; i < portStr.length(); i++) {
940             if (!isDigit(portStr.charAt(i))) {
941               throw new MalformedURIException(
942                    portStr +
943                    " is invalid. Port should only contain digits!");
944             }
945           }**/
946           // REVISIT: Remove this code.
947           // Store port value as string instead of integer.
948           try {
949             port = Integer.parseInt(portStr);
950             if (port == -1) --port;
951           }
952           catch (NumberFormatException nfe) {
953             port = -2;
954           }
955         }
956       }
957     }
958 
959     if (isValidServerBasedAuthority(host, port, userinfo)) {
960       m_host = host;
961       m_port = port;
962       m_userinfo = userinfo;
963       return true;
964     }
965     // Note: Registry based authority is being removed from a
966     // new spec for URI which would obsolete RFC 2396. If the
967     // spec is added to XML errata, processing of reg_name
968     // needs to be removed. - mrglavas.
969     else if (isValidRegistryBasedAuthority(p_uriSpec)) {
970       m_regAuthority = p_uriSpec;
971       return true;
972     }
973     return false;
974   }
975 
976   /**
977    * Determines whether the components host, port, and user info
978    * are valid as a server authority.
979    *
980    * @param host the host component of authority
981    * @param port the port number component of authority
982    * @param userinfo the user info component of authority
983    *
984    * @return true if the given host, port, and userinfo compose
985    * a valid server authority
986    */
987   private boolean isValidServerBasedAuthority(String host, int port, String userinfo) {
988 
989     // Check if the host is well formed.
990     if (!isWellFormedAddress(host)) {
991       return false;
992     }
993 
994     // Check that port is well formed if it exists.
995     // REVISIT: There's no restriction on port value ranges, but
996     // perform the same check as in setPort to be consistent. Pass
997     // in a string to this method instead of an integer.
998     if (port < -1 || port > 65535) {
999       return false;
1000     }
1001 
1002     // Check that userinfo is well formed if it exists.
1003     if (userinfo != null) {
1004       // Userinfo can contain alphanumerics, mark characters, escaped
1005       // and ';',':','&','=','+','$',','
1006       int index = 0;
1007       int end = userinfo.length();
1008       char testChar = '\0';
1009       while (index < end) {
1010         testChar = userinfo.charAt(index);
1011         if (testChar == '%') {
1012           if (index+2 >= end ||
1013             !isHex(userinfo.charAt(index+1)) ||
1014             !isHex(userinfo.charAt(index+2))) {
1015             return false;
1016           }
1017           index += 2;
1018         }
1019         else if (!isUserinfoCharacter(testChar)) {
1020           return false;
1021         }
1022         ++index;
1023       }
1024     }
1025     return true;
1026   }
1027 
1028   /**
1029    * Determines whether the given string is a registry based authority.
1030    *
1031    * @param authority the authority component of a URI
1032    *
1033    * @return true if the given string is a registry based authority
1034    */
1035   private boolean isValidRegistryBasedAuthority(String authority) {
1036     int index = 0;
1037     int end = authority.length();
1038     char testChar;
1039 
1040     while (index < end) {
1041       testChar = authority.charAt(index);
1042 
1043       // check for valid escape sequence
1044       if (testChar == '%') {
1045         if (index+2 >= end ||
1046             !isHex(authority.charAt(index+1)) ||
1047             !isHex(authority.charAt(index+2))) {
1048             return false;
1049         }
1050         index += 2;
1051       }
1052       // can check against path characters because the set
1053       // is the same except for '/' which we've already excluded.
1054       else if (!isPathCharacter(testChar)) {
1055         return false;
1056       }
1057       ++index;
1058     }
1059     return true;
1060   }
1061 
1062  /**
1063   * Initialize the path for this URI from a URI string spec.
1064   *
1065   * @param p_uriSpec the URI specification (cannot be null)
1066   * @param p_nStartIndex the index to begin scanning from
1067   *
1068   * @exception MalformedURIException if p_uriSpec violates syntax rules
1069   */
1070   private void initializePath(String p_uriSpec, int p_nStartIndex)
1071                  throws MalformedURIException {
1072     if (p_uriSpec == null) {
1073       throw new MalformedURIException(
1074                 "Cannot initialize path from null string!");
1075     }
1076 
1077     int index = p_nStartIndex;
1078     int start = p_nStartIndex;
1079     int end = p_uriSpec.length();
1080     char testChar = '\0';
1081 
1082     // path - everything up to query string or fragment
1083     if (start < end) {
1084         // RFC 2732 only allows '[' and ']' to appear in the opaque part.
1085         if (getScheme() == null || p_uriSpec.charAt(start) == '/') {
1086 
1087             // Scan path.
1088             // abs_path = "/"  path_segments
1089             // rel_path = rel_segment [ abs_path ]
1090             while (index < end) {
1091                 testChar = p_uriSpec.charAt(index);
1092 
1093                 // check for valid escape sequence
1094                 if (testChar == '%') {
1095                     if (index+2 >= end ||
1096                     !isHex(p_uriSpec.charAt(index+1)) ||
1097                     !isHex(p_uriSpec.charAt(index+2))) {
1098                         throw new MalformedURIException(
1099                             "Path contains invalid escape sequence!");
1100                     }
1101                     index += 2;
1102                 }
1103                 // Path segments cannot contain '[' or ']' since pchar
1104                 // production was not changed by RFC 2732.
1105                 else if (!isPathCharacter(testChar)) {
1106                     if (testChar == '?' || testChar == '#') {
1107                         break;
1108                     }
1109                     throw new MalformedURIException(
1110                         "Path contains invalid character: " + testChar);
1111                 }
1112                 ++index;
1113             }
1114         }
1115         else {
1116 
1117             // Scan opaque part.
1118             // opaque_part = uric_no_slash *uric
1119             while (index < end) {
1120                 testChar = p_uriSpec.charAt(index);
1121 
1122                 if (testChar == '?' || testChar == '#') {
1123                     break;
1124                 }
1125 
1126                 // check for valid escape sequence
1127                 if (testChar == '%') {
1128                     if (index+2 >= end ||
1129                     !isHex(p_uriSpec.charAt(index+1)) ||
1130                     !isHex(p_uriSpec.charAt(index+2))) {
1131                         throw new MalformedURIException(
1132                             "Opaque part contains invalid escape sequence!");
1133                     }
1134                     index += 2;
1135                 }
1136                 // If the scheme specific part is opaque, it can contain '['
1137                 // and ']'. uric_no_slash wasn't modified by RFC 2732, which
1138                 // I've interpreted as an error in the spec, since the
1139                 // production should be equivalent to (uric - '/'), and uric
1140                 // contains '[' and ']'. - mrglavas
1141                 else if (!isURICharacter(testChar)) {
1142                     throw new MalformedURIException(
1143                         "Opaque part contains invalid character: " + testChar);
1144                 }
1145                 ++index;
1146             }
1147         }
1148     }
1149     m_path = p_uriSpec.substring(start, index);
1150 
1151     // query - starts with ? and up to fragment or end
1152     if (testChar == '?') {
1153       index++;
1154       start = index;
1155       while (index < end) {
1156         testChar = p_uriSpec.charAt(index);
1157         if (testChar == '#') {
1158           break;
1159         }
1160         if (testChar == '%') {
1161            if (index+2 >= end ||
1162               !isHex(p_uriSpec.charAt(index+1)) ||
1163               !isHex(p_uriSpec.charAt(index+2))) {
1164             throw new MalformedURIException(
1165                     "Query string contains invalid escape sequence!");
1166            }
1167            index += 2;
1168         }
1169         else if (!isURICharacter(testChar)) {
1170           throw new MalformedURIException(
1171                 "Query string contains invalid character: " + testChar);
1172         }
1173         index++;
1174       }
1175       m_queryString = p_uriSpec.substring(start, index);
1176     }
1177 
1178     // fragment - starts with #
1179     if (testChar == '#') {
1180       index++;
1181       start = index;
1182       while (index < end) {
1183         testChar = p_uriSpec.charAt(index);
1184 
1185         if (testChar == '%') {
1186            if (index+2 >= end ||
1187               !isHex(p_uriSpec.charAt(index+1)) ||
1188               !isHex(p_uriSpec.charAt(index+2))) {
1189             throw new MalformedURIException(
1190                     "Fragment contains invalid escape sequence!");
1191            }
1192            index += 2;
1193         }
1194         else if (!isURICharacter(testChar)) {
1195           throw new MalformedURIException(
1196                 "Fragment contains invalid character: "+testChar);
1197         }
1198         index++;
1199       }
1200       m_fragment = p_uriSpec.substring(start, index);
1201     }
1202   }
1203 
1204  /**
1205   * Get the scheme for this URI.
1206   *
1207   * @return the scheme for this URI
1208   */
1209   public String getScheme() {
1210     return m_scheme;
1211   }
1212 
1213  /**
1214   * Get the scheme-specific part for this URI (everything following the
1215   * scheme and the first colon). See RFC 2396 Section 5.2 for spec.
1216   *
1217   * @return the scheme-specific part for this URI
1218   */
1219   public String getSchemeSpecificPart() {
1220     final StringBuilder schemespec = new StringBuilder();
1221 
1222     if (m_host != null || m_regAuthority != null) {
1223       schemespec.append("//");
1224 
1225       // Server based authority.
1226       if (m_host != null) {
1227 
1228         if (m_userinfo != null) {
1229           schemespec.append(m_userinfo);
1230           schemespec.append('@');
1231         }
1232 
1233         schemespec.append(m_host);
1234 
1235         if (m_port != -1) {
1236           schemespec.append(':');
1237           schemespec.append(m_port);
1238         }
1239       }
1240       // Registry based authority.
1241       else {
1242         schemespec.append(m_regAuthority);
1243       }
1244     }
1245 
1246     if (m_path != null) {
1247       schemespec.append((m_path));
1248     }
1249 
1250     if (m_queryString != null) {
1251       schemespec.append('?');
1252       schemespec.append(m_queryString);
1253     }
1254 
1255     if (m_fragment != null) {
1256       schemespec.append('#');
1257       schemespec.append(m_fragment);
1258     }
1259 
1260     return schemespec.toString();
1261   }
1262 
1263  /**
1264   * Get the userinfo for this URI.
1265   *
1266   * @return the userinfo for this URI (null if not specified).
1267   */
1268   public String getUserinfo() {
1269     return m_userinfo;
1270   }
1271 
1272   /**
1273   * Get the host for this URI.
1274   *
1275   * @return the host for this URI (null if not specified).
1276   */
1277   public String getHost() {
1278     return m_host;
1279   }
1280 
1281  /**
1282   * Get the port for this URI.
1283   *
1284   * @return the port for this URI (-1 if not specified).
1285   */
1286   public int getPort() {
1287     return m_port;
1288   }
1289 
1290   /**
1291    * Get the registry based authority for this URI.
1292    *
1293    * @return the registry based authority (null if not specified).
1294    */
1295   public String getRegBasedAuthority() {
1296     return m_regAuthority;
1297   }
1298 
1299   /**
1300    * Get the authority for this URI.
1301    *
1302    * @return the authority
1303    */
1304   public String getAuthority() {
1305       final StringBuilder authority = new StringBuilder();
1306       if (m_host != null || m_regAuthority != null) {
1307           authority.append("//");
1308 
1309           // Server based authority.
1310           if (m_host != null) {
1311 
1312               if (m_userinfo != null) {
1313                   authority.append(m_userinfo);
1314                   authority.append('@');
1315               }
1316 
1317               authority.append(m_host);
1318 
1319               if (m_port != -1) {
1320                   authority.append(':');
1321                   authority.append(m_port);
1322               }
1323           }
1324           // Registry based authority.
1325           else {
1326               authority.append(m_regAuthority);
1327           }
1328       }
1329       return authority.toString();
1330   }
1331 
1332  /**
1333   * Get the path for this URI (optionally with the query string and
1334   * fragment).
1335   *
1336   * @param p_includeQueryString if true (and query string is not null),
1337   *                             then a "?" followed by the query string
1338   *                             will be appended
1339   * @param p_includeFragment if true (and fragment is not null),
1340   *                             then a "#" followed by the fragment
1341   *                             will be appended
1342   *
1343   * @return the path for this URI possibly including the query string
1344   *         and fragment
1345   */
1346   public String getPath(boolean p_includeQueryString,
1347                         boolean p_includeFragment) {
1348     final StringBuilder pathString = new StringBuilder(m_path);
1349 
1350     if (p_includeQueryString && m_queryString != null) {
1351       pathString.append('?');
1352       pathString.append(m_queryString);
1353     }
1354 
1355     if (p_includeFragment && m_fragment != null) {
1356       pathString.append('#');
1357       pathString.append(m_fragment);
1358     }
1359     return pathString.toString();
1360   }
1361 
1362  /**
1363   * Get the path for this URI. Note that the value returned is the path
1364   * only and does not include the query string or fragment.
1365   *
1366   * @return the path for this URI.
1367   */
1368   public String getPath() {
1369     return m_path;
1370   }
1371 
1372  /**
1373   * Get the query string for this URI.
1374   *
1375   * @return the query string for this URI. Null is returned if there
1376   *         was no "?" in the URI spec, empty string if there was a
1377   *         "?" but no query string following it.
1378   */
1379   public String getQueryString() {
1380     return m_queryString;
1381   }
1382 
1383  /**
1384   * Get the fragment for this URI.
1385   *
1386   * @return the fragment for this URI. Null is returned if there
1387   *         was no "#" in the URI spec, empty string if there was a
1388   *         "#" but no fragment following it.
1389   */
1390   public String getFragment() {
1391     return m_fragment;
1392   }
1393 
1394  /**
1395   * Set the scheme for this URI. The scheme is converted to lowercase
1396   * before it is set.
1397   *
1398   * @param p_scheme the scheme for this URI (cannot be null)
1399   *
1400   * @exception MalformedURIException if p_scheme is not a conformant
1401   *                                  scheme name
1402   */
1403   public void setScheme(String p_scheme) throws MalformedURIException {
1404     if (p_scheme == null) {
1405       throw new MalformedURIException(
1406                 "Cannot set scheme from null string!");
1407     }
1408     if (!isConformantSchemeName(p_scheme)) {
1409       throw new MalformedURIException("The scheme is not conformant.");
1410     }
1411 
1412     m_scheme = p_scheme.toLowerCase();
1413   }
1414 
1415  /**
1416   * Set the userinfo for this URI. If a non-null value is passed in and
1417   * the host value is null, then an exception is thrown.
1418   *
1419   * @param p_userinfo the userinfo for this URI
1420   *
1421   * @exception MalformedURIException if p_userinfo contains invalid
1422   *                                  characters
1423   */
1424   public void setUserinfo(String p_userinfo) throws MalformedURIException {
1425     if (p_userinfo == null) {
1426       m_userinfo = null;
1427       return;
1428     }
1429     else {
1430       if (m_host == null) {
1431         throw new MalformedURIException(
1432                      "Userinfo cannot be set when host is null!");
1433       }
1434 
1435       // userinfo can contain alphanumerics, mark characters, escaped
1436       // and ';',':','&','=','+','$',','
1437       int index = 0;
1438       int end = p_userinfo.length();
1439       char testChar = '\0';
1440       while (index < end) {
1441         testChar = p_userinfo.charAt(index);
1442         if (testChar == '%') {
1443           if (index+2 >= end ||
1444               !isHex(p_userinfo.charAt(index+1)) ||
1445               !isHex(p_userinfo.charAt(index+2))) {
1446             throw new MalformedURIException(
1447                   "Userinfo contains invalid escape sequence!");
1448           }
1449         }
1450         else if (!isUserinfoCharacter(testChar)) {
1451           throw new MalformedURIException(
1452                   "Userinfo contains invalid character:"+testChar);
1453         }
1454         index++;
1455       }
1456     }
1457     m_userinfo = p_userinfo;
1458   }
1459 
1460  /**
1461   * <p>Set the host for this URI. If null is passed in, the userinfo
1462   * field is also set to null and the port is set to -1.</p>
1463   *
1464   * <p>Note: This method overwrites registry based authority if it
1465   * previously existed in this URI.</p>
1466   *
1467   * @param p_host the host for this URI
1468   *
1469   * @exception MalformedURIException if p_host is not a valid IP
1470   *                                  address or DNS hostname.
1471   */
1472   public void setHost(String p_host) throws MalformedURIException {
1473     if (p_host == null || p_host.length() == 0) {
1474       if (p_host != null) {
1475         m_regAuthority = null;
1476       }
1477       m_host = p_host;
1478       m_userinfo = null;
1479       m_port = -1;
1480       return;
1481     }
1482     else if (!isWellFormedAddress(p_host)) {
1483       throw new MalformedURIException("Host is not a well formed address!");
1484     }
1485     m_host = p_host;
1486     m_regAuthority = null;
1487   }
1488 
1489  /**
1490   * Set the port for this URI. -1 is used to indicate that the port is
1491   * not specified, otherwise valid port numbers are  between 0 and 65535.
1492   * If a valid port number is passed in and the host field is null,
1493   * an exception is thrown.
1494   *
1495   * @param p_port the port number for this URI
1496   *
1497   * @exception MalformedURIException if p_port is not -1 and not a
1498   *                                  valid port number
1499   */
1500   public void setPort(int p_port) throws MalformedURIException {
1501     if (p_port >= 0 && p_port <= 65535) {
1502       if (m_host == null) {
1503         throw new MalformedURIException(
1504                       "Port cannot be set when host is null!");
1505       }
1506     }
1507     else if (p_port != -1) {
1508       throw new MalformedURIException("Invalid port number!");
1509     }
1510     m_port = p_port;
1511   }
1512 
1513   /**
1514    * <p>Sets the registry based authority for this URI.</p>
1515    *
1516    * <p>Note: This method overwrites server based authority
1517    * if it previously existed in this URI.</p>
1518    *
1519    * @param authority the registry based authority for this URI
1520    *
1521    * @exception MalformedURIException it authority is not a
1522    * well formed registry based authority
1523    */
1524   public void setRegBasedAuthority(String authority)
1525     throws MalformedURIException {
1526 
1527         if (authority == null) {
1528           m_regAuthority = null;
1529           return;
1530         }
1531         // reg_name = 1*( unreserved | escaped | "$" | "," |
1532         //            ";" | ":" | "@" | "&" | "=" | "+" )
1533         else if (authority.length() < 1 ||
1534           !isValidRegistryBasedAuthority(authority) ||
1535           authority.indexOf('/') != -1) {
1536       throw new MalformedURIException("Registry based authority is not well formed.");
1537         }
1538         m_regAuthority = authority;
1539         m_host = null;
1540         m_userinfo = null;
1541         m_port = -1;
1542   }
1543 
1544  /**
1545   * Set the path for this URI. If the supplied path is null, then the
1546   * query string and fragment are set to null as well. If the supplied
1547   * path includes a query string and/or fragment, these fields will be
1548   * parsed and set as well. Note that, for URIs following the "generic
1549   * URI" syntax, the path specified should start with a slash.
1550   * For URIs that do not follow the generic URI syntax, this method
1551   * sets the scheme-specific part.
1552   *
1553   * @param p_path the path for this URI (may be null)
1554   *
1555   * @exception MalformedURIException if p_path contains invalid
1556   *                                  characters
1557   */
1558   public void setPath(String p_path) throws MalformedURIException {
1559     if (p_path == null) {
1560       m_path = null;
1561       m_queryString = null;
1562       m_fragment = null;
1563     }
1564     else {
1565       initializePath(p_path, 0);
1566     }
1567   }
1568 
1569  /**
1570   * Append to the end of the path of this URI. If the current path does
1571   * not end in a slash and the path to be appended does not begin with
1572   * a slash, a slash will be appended to the current path before the
1573   * new segment is added. Also, if the current path ends in a slash
1574   * and the new segment begins with a slash, the extra slash will be
1575   * removed before the new segment is appended.
1576   *
1577   * @param p_addToPath the new segment to be added to the current path
1578   *
1579   * @exception MalformedURIException if p_addToPath contains syntax
1580   *                                  errors
1581   */
1582   public void appendPath(String p_addToPath)
1583                          throws MalformedURIException {
1584     if (p_addToPath == null || p_addToPath.trim().length() == 0) {
1585       return;
1586     }
1587 
1588     if (!isURIString(p_addToPath)) {
1589       throw new MalformedURIException(
1590               "Path contains invalid character!");
1591     }
1592 
1593     if (m_path == null || m_path.trim().length() == 0) {
1594       if (p_addToPath.startsWith("/")) {
1595         m_path = p_addToPath;
1596       }
1597       else {
1598         m_path = "/" + p_addToPath;
1599       }
1600     }
1601     else if (m_path.endsWith("/")) {
1602       if (p_addToPath.startsWith("/")) {
1603         m_path = m_path.concat(p_addToPath.substring(1));
1604       }
1605       else {
1606         m_path = m_path.concat(p_addToPath);
1607       }
1608     }
1609     else {
1610       if (p_addToPath.startsWith("/")) {
1611         m_path = m_path.concat(p_addToPath);
1612       }
1613       else {
1614         m_path = m_path.concat("/" + p_addToPath);
1615       }
1616     }
1617   }
1618 
1619  /**
1620   * Set the query string for this URI. A non-null value is valid only
1621   * if this is an URI conforming to the generic URI syntax and
1622   * the path value is not null.
1623   *
1624   * @param p_queryString the query string for this URI
1625   *
1626   * @exception MalformedURIException if p_queryString is not null and this
1627   *                                  URI does not conform to the generic
1628   *                                  URI syntax or if the path is null
1629   */
1630   public void setQueryString(String p_queryString) throws MalformedURIException {
1631     if (p_queryString == null) {
1632       m_queryString = null;
1633     }
1634     else if (!isGenericURI()) {
1635       throw new MalformedURIException(
1636               "Query string can only be set for a generic URI!");
1637     }
1638     else if (getPath() == null) {
1639       throw new MalformedURIException(
1640               "Query string cannot be set when path is null!");
1641     }
1642     else if (!isURIString(p_queryString)) {
1643       throw new MalformedURIException(
1644               "Query string contains invalid character!");
1645     }
1646     else {
1647       m_queryString = p_queryString;
1648     }
1649   }
1650 
1651  /**
1652   * Set the fragment for this URI. A non-null value is valid only
1653   * if this is a URI conforming to the generic URI syntax and
1654   * the path value is not null.
1655   *
1656   * @param p_fragment the fragment for this URI
1657   *
1658   * @exception MalformedURIException if p_fragment is not null and this
1659   *                                  URI does not conform to the generic
1660   *                                  URI syntax or if the path is null
1661   */
1662   public void setFragment(String p_fragment) throws MalformedURIException {
1663     if (p_fragment == null) {
1664       m_fragment = null;
1665     }
1666     else if (!isGenericURI()) {
1667       throw new MalformedURIException(
1668          "Fragment can only be set for a generic URI!");
1669     }
1670     else if (getPath() == null) {
1671       throw new MalformedURIException(
1672               "Fragment cannot be set when path is null!");
1673     }
1674     else if (!isURIString(p_fragment)) {
1675       throw new MalformedURIException(
1676               "Fragment contains invalid character!");
1677     }
1678     else {
1679       m_fragment = p_fragment;
1680     }
1681   }
1682 
1683  /**
1684   * Determines if the passed-in Object is equivalent to this URI.
1685   *
1686   * @param p_test the Object to test for equality.
1687   *
1688   * @return true if p_test is a URI with all values equal to this
1689   *         URI, false otherwise
1690   */
1691   @Override
1692   public boolean equals(Object p_test) {
1693     if (p_test instanceof URI) {
1694       URI testURI = (URI) p_test;
1695       if (((m_scheme == null && testURI.m_scheme == null) ||
1696            (m_scheme != null && testURI.m_scheme != null &&
1697             m_scheme.equals(testURI.m_scheme))) &&
1698           ((m_userinfo == null && testURI.m_userinfo == null) ||
1699            (m_userinfo != null && testURI.m_userinfo != null &&
1700             m_userinfo.equals(testURI.m_userinfo))) &&
1701           ((m_host == null && testURI.m_host == null) ||
1702            (m_host != null && testURI.m_host != null &&
1703             m_host.equals(testURI.m_host))) &&
1704             m_port == testURI.m_port &&
1705           ((m_path == null && testURI.m_path == null) ||
1706            (m_path != null && testURI.m_path != null &&
1707             m_path.equals(testURI.m_path))) &&
1708           ((m_queryString == null && testURI.m_queryString == null) ||
1709            (m_queryString != null && testURI.m_queryString != null &&
1710             m_queryString.equals(testURI.m_queryString))) &&
1711           ((m_fragment == null && testURI.m_fragment == null) ||
1712            (m_fragment != null && testURI.m_fragment != null &&
1713             m_fragment.equals(testURI.m_fragment)))) {
1714         return true;
1715       }
1716     }
1717     return false;
1718   }
1719 
1720     @Override
1721     public int hashCode() {
1722         int hash = 5;
1723         hash = 47 * hash + Objects.hashCode(this.m_scheme);
1724         hash = 47 * hash + Objects.hashCode(this.m_userinfo);
1725         hash = 47 * hash + Objects.hashCode(this.m_host);
1726         hash = 47 * hash + this.m_port;
1727         hash = 47 * hash + Objects.hashCode(this.m_path);
1728         hash = 47 * hash + Objects.hashCode(this.m_queryString);
1729         hash = 47 * hash + Objects.hashCode(this.m_fragment);
1730         return hash;
1731     }
1732 
1733  /**
1734   * Get the URI as a string specification. See RFC 2396 Section 5.2.
1735   *
1736   * @return the URI string specification
1737   */
1738   @Override
1739   public String toString() {
1740     final StringBuilder uriSpecString = new StringBuilder();
1741 
1742     if (m_scheme != null) {
1743       uriSpecString.append(m_scheme);
1744       uriSpecString.append(':');
1745     }
1746     uriSpecString.append(getSchemeSpecificPart());
1747     return uriSpecString.toString();
1748   }
1749 
1750  /**
1751   * Get the indicator as to whether this URI uses the "generic URI"
1752   * syntax.
1753   *
1754   * @return true if this URI uses the "generic URI" syntax, false
1755   *         otherwise
1756   */
1757   public boolean isGenericURI() {
1758     // presence of the host (whether valid or empty) means
1759     // double-slashes which means generic uri
1760     return (m_host != null);
1761   }
1762 
1763   /**
1764    * Returns whether this URI represents an absolute URI.
1765    *
1766    * @return true if this URI represents an absolute URI, false
1767    *         otherwise
1768    */
1769   public boolean isAbsoluteURI() {
1770       // presence of the scheme means absolute uri
1771       return (m_scheme != null);
1772   }
1773 
1774  /**
1775   * Determine whether a scheme conforms to the rules for a scheme name.
1776   * A scheme is conformant if it starts with an alphanumeric, and
1777   * contains only alphanumerics, '+','-' and '.'.
1778   *
1779   * @return true if the scheme is conformant, false otherwise
1780   */
1781   public static boolean isConformantSchemeName(String p_scheme) {
1782     if (p_scheme == null || p_scheme.trim().length() == 0) {
1783       return false;
1784     }
1785 
1786     if (!isAlpha(p_scheme.charAt(0))) {
1787       return false;
1788     }
1789 
1790     char testChar;
1791     int schemeLength = p_scheme.length();
1792     for (int i = 1; i < schemeLength; ++i) {
1793       testChar = p_scheme.charAt(i);
1794       if (!isSchemeCharacter(testChar)) {
1795         return false;
1796       }
1797     }
1798 
1799     return true;
1800   }
1801 
1802  /**
1803   * Determine whether a string is syntactically capable of representing
1804   * a valid IPv4 address, IPv6 reference or the domain name of a network host.
1805   * A valid IPv4 address consists of four decimal digit groups separated by a
1806   * '.'. Each group must consist of one to three digits. See RFC 2732 Section 3,
1807   * and RFC 2373 Section 2.2, for the definition of IPv6 references. A hostname
1808   * consists of domain labels (each of which must begin and end with an alphanumeric
1809   * but may contain '-') separated & by a '.'. See RFC 2396 Section 3.2.2.
1810   *
1811   * @return true if the string is a syntactically valid IPv4 address,
1812   * IPv6 reference or hostname
1813   */
1814   public static boolean isWellFormedAddress(String address) {
1815     if (address == null) {
1816       return false;
1817     }
1818 
1819     int addrLength = address.length();
1820     if (addrLength == 0) {
1821       return false;
1822     }
1823 
1824     // Check if the host is a valid IPv6reference.
1825     if (address.startsWith("[")) {
1826       return isWellFormedIPv6Reference(address);
1827     }
1828 
1829     // Cannot start with a '.', '-', or end with a '-'.
1830     if (address.startsWith(".") ||
1831         address.startsWith("-") ||
1832         address.endsWith("-")) {
1833       return false;
1834     }
1835 
1836     // rightmost domain label starting with digit indicates IP address
1837     // since top level domain label can only start with an alpha
1838     // see RFC 2396 Section 3.2.2
1839     int index = address.lastIndexOf('.');
1840     if (address.endsWith(".")) {
1841       index = address.substring(0, index).lastIndexOf('.');
1842     }
1843 
1844     if (index+1 < addrLength && isDigit(address.charAt(index+1))) {
1845       return isWellFormedIPv4Address(address);
1846     }
1847     else {
1848       // hostname      = *( domainlabel "." ) toplabel [ "." ]
1849       // domainlabel   = alphanum | alphanum *( alphanum | "-" ) alphanum
1850       // toplabel      = alpha | alpha *( alphanum | "-" ) alphanum
1851 
1852       // RFC 2396 states that hostnames take the form described in
1853       // RFC 1034 (Section 3) and RFC 1123 (Section 2.1). According
1854       // to RFC 1034, hostnames are limited to 255 characters.
1855       if (addrLength > 255) {
1856         return false;
1857       }
1858 
1859       // domain labels can contain alphanumerics and '-"
1860       // but must start and end with an alphanumeric
1861       char testChar;
1862       int labelCharCount = 0;
1863 
1864       for (int i = 0; i < addrLength; i++) {
1865         testChar = address.charAt(i);
1866         if (testChar == '.') {
1867           if (!isAlphanum(address.charAt(i-1))) {
1868             return false;
1869           }
1870           if (i+1 < addrLength && !isAlphanum(address.charAt(i+1))) {
1871             return false;
1872           }
1873           labelCharCount = 0;
1874         }
1875         else if (!isAlphanum(testChar) && testChar != '-') {
1876           return false;
1877         }
1878         // RFC 1034: Labels must be 63 characters or less.
1879         else if (++labelCharCount > 63) {
1880           return false;
1881         }
1882       }
1883     }
1884     return true;
1885   }
1886 
1887   /**
1888    * <p>Determines whether a string is an IPv4 address as defined by
1889    * RFC 2373, and under the further constraint that it must be a 32-bit
1890    * address. Though not expressed in the grammar, in order to satisfy
1891    * the 32-bit address constraint, each segment of the address cannot
1892    * be greater than 255 (8 bits of information).</p>
1893    *
1894    * <p><code>IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT</code></p>
1895    *
1896    * @return true if the string is a syntactically valid IPv4 address
1897    */
1898   public static boolean isWellFormedIPv4Address(String address) {
1899 
1900       int addrLength = address.length();
1901       char testChar;
1902       int numDots = 0;
1903       int numDigits = 0;
1904 
1905       // make sure that 1) we see only digits and dot separators, 2) that
1906       // any dot separator is preceded and followed by a digit and
1907       // 3) that we find 3 dots
1908       //
1909       // RFC 2732 amended RFC 2396 by replacing the definition
1910       // of IPv4address with the one defined by RFC 2373. - mrglavas
1911       //
1912       // IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT
1913       //
1914       // One to three digits must be in each segment.
1915       for (int i = 0; i < addrLength; i++) {
1916         testChar = address.charAt(i);
1917         if (testChar == '.') {
1918           if ((i > 0 && !isDigit(address.charAt(i-1))) ||
1919               (i+1 < addrLength && !isDigit(address.charAt(i+1)))) {
1920             return false;
1921           }
1922           numDigits = 0;
1923           if (++numDots > 3) {
1924             return false;
1925           }
1926         }
1927         else if (!isDigit(testChar)) {
1928           return false;
1929         }
1930         // Check that that there are no more than three digits
1931         // in this segment.
1932         else if (++numDigits > 3) {
1933           return false;
1934         }
1935         // Check that this segment is not greater than 255.
1936         else if (numDigits == 3) {
1937           char first = address.charAt(i-2);
1938           char second = address.charAt(i-1);
1939           if (!(first < '2' ||
1940                (first == '2' &&
1941                (second < '5' ||
1942                (second == '5' && testChar <= '5'))))) {
1943             return false;
1944           }
1945         }
1946       }
1947       return (numDots == 3);
1948   }
1949 
1950   /**
1951    * <p>Determines whether a string is an IPv6 reference as defined
1952    * by RFC 2732, where IPv6address is defined in RFC 2373. The
1953    * IPv6 address is parsed according to Section 2.2 of RFC 2373,
1954    * with the additional constraint that the address be composed of
1955    * 128 bits of information.</p>
1956    *
1957    * <p><code>IPv6reference = "[" IPv6address "]"</code></p>
1958    *
1959    * <p>Note: The BNF expressed in RFC 2373 Appendix B does not
1960    * accurately describe section 2.2, and was in fact removed from
1961    * RFC 3513, the successor of RFC 2373.</p>
1962    *
1963    * @return true if the string is a syntactically valid IPv6 reference
1964    */
1965   public static boolean isWellFormedIPv6Reference(String address) {
1966 
1967       int addrLength = address.length();
1968       int index = 1;
1969       int end = addrLength-1;
1970 
1971       // Check if string is a potential match for IPv6reference.
1972       if (!(addrLength > 2 && address.charAt(0) == '['
1973           && address.charAt(end) == ']')) {
1974           return false;
1975       }
1976 
1977       // Counter for the number of 16-bit sections read in the address.
1978       int [] counter = new int[1];
1979 
1980       // Scan hex sequence before possible '::' or IPv4 address.
1981       index = scanHexSequence(address, index, end, counter);
1982       if (index == -1) {
1983           return false;
1984       }
1985       // Address must contain 128-bits of information.
1986       else if (index == end) {
1987           return (counter[0] == 8);
1988       }
1989 
1990       if (index+1 < end && address.charAt(index) == ':') {
1991           if (address.charAt(index+1) == ':') {
1992               // '::' represents at least one 16-bit group of zeros.
1993               if (++counter[0] > 8) {
1994                   return false;
1995               }
1996               index += 2;
1997               // Trailing zeros will fill out the rest of the address.
1998               if (index == end) {
1999                  return true;
2000               }
2001           }
2002           // If the second character wasn't ':', in order to be valid,
2003           // the remainder of the string must match IPv4Address,
2004           // and we must have read exactly 6 16-bit groups.
2005           else {
2006               return (counter[0] == 6) &&
2007                   isWellFormedIPv4Address(address.substring(index+1, end));
2008           }
2009       }
2010       else {
2011           return false;
2012       }
2013 
2014       // 3. Scan hex sequence after '::'.
2015       int prevCount = counter[0];
2016       index = scanHexSequence(address, index, end, counter);
2017 
2018       // We've either reached the end of the string, the address ends in
2019       // an IPv4 address, or it is invalid. scanHexSequence has already
2020       // made sure that we have the right number of bits.
2021       return (index == end) ||
2022           (index != -1 && isWellFormedIPv4Address(
2023           address.substring((counter[0] > prevCount) ? index+1 : index, end)));
2024   }
2025 
2026   /**
2027    * Helper method for isWellFormedIPv6Reference which scans the
2028    * hex sequences of an IPv6 address. It returns the index of the
2029    * next character to scan in the address, or -1 if the string
2030    * cannot match a valid IPv6 address.
2031    *
2032    * @param address the string to be scanned
2033    * @param index the beginning index (inclusive)
2034    * @param end the ending index (exclusive)
2035    * @param counter a counter for the number of 16-bit sections read
2036    * in the address
2037    *
2038    * @return the index of the next character to scan, or -1 if the
2039    * string cannot match a valid IPv6 address
2040    */
2041   private static int scanHexSequence (String address, int index, int end, int [] counter) {
2042 
2043       char testChar;
2044       int numDigits = 0;
2045       int start = index;
2046 
2047       // Trying to match the following productions:
2048       // hexseq = hex4 *( ":" hex4)
2049       // hex4   = 1*4HEXDIG
2050       for (; index < end; ++index) {
2051         testChar = address.charAt(index);
2052         if (testChar == ':') {
2053             // IPv6 addresses are 128-bit, so there can be at most eight sections.
2054             if (numDigits > 0 && ++counter[0] > 8) {
2055                 return -1;
2056             }
2057             // This could be '::'.
2058             if (numDigits == 0 || ((index+1 < end) && address.charAt(index+1) == ':')) {
2059                 return index;
2060             }
2061             numDigits = 0;
2062         }
2063         // This might be invalid or an IPv4address. If it's potentially an IPv4address,
2064         // backup to just after the last valid character that matches hexseq.
2065         else if (!isHex(testChar)) {
2066             if (testChar == '.' && numDigits < 4 && numDigits > 0 && counter[0] <= 6) {
2067                 int back = index - numDigits - 1;
2068                 return (back >= start) ? back : (back+1);
2069             }
2070             return -1;
2071         }
2072         // There can be at most 4 hex digits per group.
2073         else if (++numDigits > 4) {
2074             return -1;
2075         }
2076       }
2077       return (numDigits > 0 && ++counter[0] <= 8) ? end : -1;
2078   }
2079 
2080 
2081  /**
2082   * Determine whether a char is a digit.
2083   *
2084   * @return true if the char is betweeen '0' and '9', false otherwise
2085   */
2086   private static boolean isDigit(char p_char) {
2087     return p_char >= '0' && p_char <= '9';
2088   }
2089 
2090  /**
2091   * Determine whether a character is a hexadecimal character.
2092   *
2093   * @return true if the char is betweeen '0' and '9', 'a' and 'f'
2094   *         or 'A' and 'F', false otherwise
2095   */
2096   private static boolean isHex(char p_char) {
2097     return (p_char <= 'f' && (fgLookupTable[p_char] & ASCII_HEX_CHARACTERS) != 0);
2098   }
2099 
2100  /**
2101   * Determine whether a char is an alphabetic character: a-z or A-Z
2102   *
2103   * @return true if the char is alphabetic, false otherwise
2104   */
2105   private static boolean isAlpha(char p_char) {
2106       return ((p_char >= 'a' && p_char <= 'z') || (p_char >= 'A' && p_char <= 'Z' ));
2107   }
2108 
2109  /**
2110   * Determine whether a char is an alphanumeric: 0-9, a-z or A-Z
2111   *
2112   * @return true if the char is alphanumeric, false otherwise
2113   */
2114   private static boolean isAlphanum(char p_char) {
2115      return (p_char <= 'z' && (fgLookupTable[p_char] & MASK_ALPHA_NUMERIC) != 0);
2116   }
2117 
2118  /**
2119   * Determine whether a character is a reserved character:
2120   * ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '[', or ']'
2121   *
2122   * @return true if the string contains any reserved characters
2123   */
2124   private static boolean isReservedCharacter(char p_char) {
2125      return (p_char <= ']' && (fgLookupTable[p_char] & RESERVED_CHARACTERS) != 0);
2126   }
2127 
2128  /**
2129   * Determine whether a char is an unreserved character.
2130   *
2131   * @return true if the char is unreserved, false otherwise
2132   */
2133   private static boolean isUnreservedCharacter(char p_char) {
2134      return (p_char <= '~' && (fgLookupTable[p_char] & MASK_UNRESERVED_MASK) != 0);
2135   }
2136 
2137  /**
2138   * Determine whether a char is a URI character (reserved or
2139   * unreserved, not including '%' for escaped octets).
2140   *
2141   * @return true if the char is a URI character, false otherwise
2142   */
2143   private static boolean isURICharacter (char p_char) {
2144       return (p_char <= '~' && (fgLookupTable[p_char] & MASK_URI_CHARACTER) != 0);
2145   }
2146 
2147  /**
2148   * Determine whether a char is a scheme character.
2149   *
2150   * @return true if the char is a scheme character, false otherwise
2151   */
2152   private static boolean isSchemeCharacter (char p_char) {
2153       return (p_char <= 'z' && (fgLookupTable[p_char] & MASK_SCHEME_CHARACTER) != 0);
2154   }
2155 
2156  /**
2157   * Determine whether a char is a userinfo character.
2158   *
2159   * @return true if the char is a userinfo character, false otherwise
2160   */
2161   private static boolean isUserinfoCharacter (char p_char) {
2162       return (p_char <= 'z' && (fgLookupTable[p_char] & MASK_USERINFO_CHARACTER) != 0);
2163   }
2164 
2165  /**
2166   * Determine whether a char is a path character.
2167   *
2168   * @return true if the char is a path character, false otherwise
2169   */
2170   private static boolean isPathCharacter (char p_char) {
2171       return (p_char <= '~' && (fgLookupTable[p_char] & MASK_PATH_CHARACTER) != 0);
2172   }
2173 
2174 
2175  /**
2176   * Determine whether a given string contains only URI characters (also
2177   * called "uric" in RFC 2396). uric consist of all reserved
2178   * characters, unreserved characters and escaped characters.
2179   *
2180   * @return true if the string is comprised of uric, false otherwise
2181   */
2182   private static boolean isURIString(String p_uric) {
2183     if (p_uric == null) {
2184       return false;
2185     }
2186     int end = p_uric.length();
2187     char testChar = '\0';
2188     for (int i = 0; i < end; i++) {
2189       testChar = p_uric.charAt(i);
2190       if (testChar == '%') {
2191         if (i+2 >= end ||
2192             !isHex(p_uric.charAt(i+1)) ||
2193             !isHex(p_uric.charAt(i+2))) {
2194           return false;
2195         }
2196         else {
2197           i += 2;
2198           continue;
2199         }
2200       }
2201       if (isURICharacter(testChar)) {
2202           continue;
2203       }
2204       else {
2205         return false;
2206       }
2207     }
2208     return true;
2209   }
2210 }