src/share/jaxws_classes/com/sun/xml/internal/messaging/saaj/util/JaxmURI.java

Thu, 31 Aug 2017 15:18:52 +0800

author
aoqi
date
Thu, 31 Aug 2017 15:18:52 +0800
changeset 637
9c07ef4934dd
parent 368
0989ad8c0860
parent 0
373ffda63c9a
permissions
-rw-r--r--

merge

     1 /*
     2  * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.xml.internal.messaging.saaj.util;
    28 // Imported from: org.apache.xerces.util
    29 // Needed to work around differences in JDK1.2 and 1.3 and deal with userInfo
    31 import java.io.IOException;
    32 import java.io.Serializable;
    35 /**********************************************************************
    36 * A class to represent a Uniform Resource Identifier (URI). This class
    37 * is designed to handle the parsing of URIs and provide access to
    38 * the various components (scheme, host, port, userinfo, path, query
    39 * string and fragment) that may constitute a URI.
    40 * <p>
    41 * Parsing of a URI specification is done according to the URI
    42 * syntax described in RFC 2396
    43 * <http://www.ietf.org/rfc/rfc2396.txt?number=2396>. Every URI consists
    44 * of a scheme, followed by a colon (':'), followed by a scheme-specific
    45 * part. For URIs that follow the "generic URI" syntax, the scheme-
    46 * specific part begins with two slashes ("//") and may be followed
    47 * by an authority segment (comprised of user information, host, and
    48 * port), path segment, query segment and fragment. Note that RFC 2396
    49 * no longer specifies the use of the parameters segment and excludes
    50 * the "user:password" syntax as part of the authority segment. If
    51 * "user:password" appears in a URI, the entire user/password string
    52 * is stored as userinfo.
    53 * <p>
    54 * For URIs that do not follow the "generic URI" syntax (e.g. mailto),
    55 * the entire scheme-specific part is treated as the "path" portion
    56 * of the URI.
    57 * <p>
    58 * Note that, unlike the java.net.URL class, this class does not provide
    59 * any built-in network access functionality nor does it provide any
    60 * scheme-specific functionality (for example, it does not know a
    61 * default port for a specific scheme). Rather, it only knows the
    62 * grammar and basic set of operations that can be applied to a URI.
    63 *
    64 * @version
    65 *
    66 **********************************************************************/
    67  public class JaxmURI implements Serializable {
    69   /*******************************************************************
    70   * MalformedURIExceptions are thrown in the process of building a URI
    71   * or setting fields on a URI when an operation would result in an
    72   * invalid URI specification.
    73   *
    74   ********************************************************************/
    75   public static class MalformedURIException extends IOException {
    77    /******************************************************************
    78     * Constructs a <code>MalformedURIException</code> with no specified
    79     * detail message.
    80     ******************************************************************/
    81     public MalformedURIException() {
    82       super();
    83     }
    85     /*****************************************************************
    86     * Constructs a <code>MalformedURIException</code> with the
    87     * specified detail message.
    88     *
    89     * @param p_msg the detail message.
    90     ******************************************************************/
    91     public MalformedURIException(String p_msg) {
    92       super(p_msg);
    93     }
    94   }
    96   /** reserved characters */
    97   private static final String RESERVED_CHARACTERS = ";/?:@&=+$,";
    99   /** URI punctuation mark characters - these, combined with
   100       alphanumerics, constitute the "unreserved" characters */
   101   private static final String MARK_CHARACTERS = "-_.!~*'() ";
   103   /** scheme can be composed of alphanumerics and these characters */
   104   private static final String SCHEME_CHARACTERS = "+-.";
   106   /** userinfo can be composed of unreserved, escaped and these
   107       characters */
   108   private static final String USERINFO_CHARACTERS = ";:&=+$,";
   110   /** Stores the scheme (usually the protocol) for this URI. */
   111   private String m_scheme = null;
   113   /** If specified, stores the userinfo for this URI; otherwise null */
   114   private String m_userinfo = null;
   116   /** If specified, stores the host for this URI; otherwise null */
   117   private String m_host = null;
   119   /** If specified, stores the port for this URI; otherwise -1 */
   120   private int m_port = -1;
   122   /** If specified, stores the path for this URI; otherwise null */
   123   private String m_path = null;
   125   /** If specified, stores the query string for this URI; otherwise
   126       null.  */
   127   private String m_queryString = null;
   129   /** If specified, stores the fragment for this URI; otherwise null */
   130   private String m_fragment = null;
   132   private static boolean DEBUG = false;
   134   /**
   135   * Construct a new and uninitialized URI.
   136   */
   137   public JaxmURI() {
   138   }
   140  /**
   141   * Construct a new URI from another URI. All fields for this URI are
   142   * set equal to the fields of the URI passed in.
   143   *
   144   * @param p_other the URI to copy (cannot be null)
   145   */
   146   public JaxmURI(JaxmURI p_other) {
   147     initialize(p_other);
   148   }
   150  /**
   151   * Construct a new URI from a URI specification string. If the
   152   * specification follows the "generic URI" syntax, (two slashes
   153   * following the first colon), the specification will be parsed
   154   * accordingly - setting the scheme, userinfo, host,port, path, query
   155   * string and fragment fields as necessary. If the specification does
   156   * not follow the "generic URI" syntax, the specification is parsed
   157   * into a scheme and scheme-specific part (stored as the path) only.
   158   *
   159   * @param p_uriSpec the URI specification string (cannot be null or
   160   *                  empty)
   161   *
   162   * @exception MalformedURIException if p_uriSpec violates any syntax
   163   *                                   rules
   164   */
   165   public JaxmURI(String p_uriSpec) throws MalformedURIException {
   166     this((JaxmURI)null, p_uriSpec);
   167   }
   169  /**
   170   * Construct a new URI from a base URI and a URI specification string.
   171   * The URI specification string may be a relative URI.
   172   *
   173   * @param p_base the base URI (cannot be null if p_uriSpec is null or
   174   *               empty)
   175   * @param p_uriSpec the URI specification string (cannot be null or
   176   *                  empty if p_base is null)
   177   *
   178   * @exception MalformedURIException if p_uriSpec violates any syntax
   179   *                                  rules
   180   */
   181   public JaxmURI(JaxmURI p_base, String p_uriSpec) throws MalformedURIException {
   182     initialize(p_base, p_uriSpec);
   183   }
   185  /**
   186   * Construct a new URI that does not follow the generic URI syntax.
   187   * Only the scheme and scheme-specific part (stored as the path) are
   188   * initialized.
   189   *
   190   * @param p_scheme the URI scheme (cannot be null or empty)
   191   * @param p_schemeSpecificPart the scheme-specific part (cannot be
   192   *                             null or empty)
   193   *
   194   * @exception MalformedURIException if p_scheme violates any
   195   *                                  syntax rules
   196   */
   197   public JaxmURI(String p_scheme, String p_schemeSpecificPart)
   198              throws MalformedURIException {
   199     if (p_scheme == null || p_scheme.trim().length() == 0) {
   200       throw new MalformedURIException(
   201             "Cannot construct URI with null/empty scheme!");
   202     }
   203     if (p_schemeSpecificPart == null ||
   204         p_schemeSpecificPart.trim().length() == 0) {
   205       throw new MalformedURIException(
   206           "Cannot construct URI with null/empty scheme-specific part!");
   207     }
   208     setScheme(p_scheme);
   209     setPath(p_schemeSpecificPart);
   210   }
   212  /**
   213   * Construct a new URI that follows the generic URI syntax from its
   214   * component parts. Each component is validated for syntax and some
   215   * basic semantic checks are performed as well.  See the individual
   216   * setter methods for specifics.
   217   *
   218   * @param p_scheme the URI scheme (cannot be null or empty)
   219   * @param p_host the hostname or IPv4 address for the URI
   220   * @param p_path the URI path - if the path contains '?' or '#',
   221   *               then the query string and/or fragment will be
   222   *               set from the path; however, if the query and
   223   *               fragment are specified both in the path and as
   224   *               separate parameters, an exception is thrown
   225   * @param p_queryString the URI query string (cannot be specified
   226   *                      if path is null)
   227   * @param p_fragment the URI fragment (cannot be specified if path
   228   *                   is null)
   229   *
   230   * @exception MalformedURIException if any of the parameters violates
   231   *                                  syntax rules or semantic rules
   232   */
   233   public JaxmURI(String p_scheme, String p_host, String p_path,
   234              String p_queryString, String p_fragment)
   235          throws MalformedURIException {
   236     this(p_scheme, null, p_host, -1, p_path, p_queryString, p_fragment);
   237   }
   239  /**
   240   * Construct a new URI that follows the generic URI syntax from its
   241   * component parts. Each component is validated for syntax and some
   242   * basic semantic checks are performed as well.  See the individual
   243   * setter methods for specifics.
   244   *
   245   * @param p_scheme the URI scheme (cannot be null or empty)
   246   * @param p_userinfo the URI userinfo (cannot be specified if host
   247   *                   is null)
   248   * @param p_host the hostname or IPv4 address for the URI
   249   * @param p_port the URI port (may be -1 for "unspecified"; cannot
   250   *               be specified if host is null)
   251   * @param p_path the URI path - if the path contains '?' or '#',
   252   *               then the query string and/or fragment will be
   253   *               set from the path; however, if the query and
   254   *               fragment are specified both in the path and as
   255   *               separate parameters, an exception is thrown
   256   * @param p_queryString the URI query string (cannot be specified
   257   *                      if path is null)
   258   * @param p_fragment the URI fragment (cannot be specified if path
   259   *                   is null)
   260   *
   261   * @exception MalformedURIException if any of the parameters violates
   262   *                                  syntax rules or semantic rules
   263   */
   264   public JaxmURI(String p_scheme, String p_userinfo,
   265              String p_host, int p_port, String p_path,
   266              String p_queryString, String p_fragment)
   267          throws MalformedURIException {
   268     if (p_scheme == null || p_scheme.trim().length() == 0) {
   269       throw new MalformedURIException("Scheme is required!");
   270     }
   272     if (p_host == null) {
   273       if (p_userinfo != null) {
   274         throw new MalformedURIException(
   275              "Userinfo may not be specified if host is not specified!");
   276       }
   277       if (p_port != -1) {
   278         throw new MalformedURIException(
   279              "Port may not be specified if host is not specified!");
   280       }
   281     }
   283     if (p_path != null) {
   284       if (p_path.indexOf('?') != -1 && p_queryString != null) {
   285         throw new MalformedURIException(
   286           "Query string cannot be specified in path and query string!");
   287       }
   289       if (p_path.indexOf('#') != -1 && p_fragment != null) {
   290         throw new MalformedURIException(
   291           "Fragment cannot be specified in both the path and fragment!");
   292       }
   293     }
   295     setScheme(p_scheme);
   296     setHost(p_host);
   297     setPort(p_port);
   298     setUserinfo(p_userinfo);
   299     setPath(p_path);
   300     setQueryString(p_queryString);
   301     setFragment(p_fragment);
   302   }
   304  /**
   305   * Initialize all fields of this URI from another URI.
   306   *
   307   * @param p_other the URI to copy (cannot be null)
   308   */
   309   private void initialize(JaxmURI p_other) {
   310     m_scheme = p_other.getScheme();
   311     m_userinfo = p_other.getUserinfo();
   312     m_host = p_other.getHost();
   313     m_port = p_other.getPort();
   314     m_path = p_other.getPath();
   315     m_queryString = p_other.getQueryString();
   316     m_fragment = p_other.getFragment();
   317   }
   319  /**
   320   * Initializes this URI from a base URI and a URI specification string.
   321   * See RFC 2396 Section 4 and Appendix B for specifications on parsing
   322   * the URI and Section 5 for specifications on resolving relative URIs
   323   * and relative paths.
   324   *
   325   * @param p_base the base URI (may be null if p_uriSpec is an absolute
   326   *               URI)
   327   * @param p_uriSpec the URI spec string which may be an absolute or
   328   *                  relative URI (can only be null/empty if p_base
   329   *                  is not null)
   330   *
   331   * @exception MalformedURIException if p_base is null and p_uriSpec
   332   *                                  is not an absolute URI or if
   333   *                                  p_uriSpec violates syntax rules
   334   */
   335   private void initialize(JaxmURI p_base, String p_uriSpec)
   336                          throws MalformedURIException {
   337     if (p_base == null &&
   338         (p_uriSpec == null || p_uriSpec.trim().length() == 0)) {
   339       throw new MalformedURIException(
   340                   "Cannot initialize URI with empty parameters.");
   341       }
   343     // just make a copy of the base if spec is empty
   344     if (p_uriSpec == null || p_uriSpec.trim().length() == 0) {
   345       initialize(p_base);
   346       return;
   347     }
   349     String uriSpec = p_uriSpec.trim();
   350     int uriSpecLen = uriSpec.length();
   351     int index = 0;
   353     // Check for scheme, which must be before `/'. Also handle names with
   354     // DOS drive letters ('D:'), so 1-character schemes are not allowed.
   355     int colonIdx = uriSpec.indexOf(':');
   356     int slashIdx = uriSpec.indexOf('/');
   357     if ((colonIdx < 2) || (colonIdx > slashIdx && slashIdx != -1)) {
   358       int fragmentIdx = uriSpec.indexOf('#');
   359       // A standalone base is a valid URI according to spec
   360       if (p_base == null && fragmentIdx != 0 ) {
   361         throw new MalformedURIException("No scheme found in URI.");
   362       }
   363     }
   364     else {
   365       initializeScheme(uriSpec);
   366       index = m_scheme.length()+1;
   367     }
   369     // two slashes means generic URI syntax, so we get the authority
   370     if (((index+1) < uriSpecLen) &&
   371         (uriSpec.substring(index).startsWith("//"))) {
   372       index += 2;
   373       int startPos = index;
   375       // get authority - everything up to path, query or fragment
   376       char testChar = '\0';
   377       while (index < uriSpecLen) {
   378         testChar = uriSpec.charAt(index);
   379         if (testChar == '/' || testChar == '?' || testChar == '#') {
   380           break;
   381         }
   382         index++;
   383       }
   385       // if we found authority, parse it out, otherwise we set the
   386       // host to empty string
   387       if (index > startPos) {
   388         initializeAuthority(uriSpec.substring(startPos, index));
   389       }
   390       else {
   391         m_host = "";
   392       }
   393     }
   395     initializePath(uriSpec.substring(index));
   397     // Resolve relative URI to base URI - see RFC 2396 Section 5.2
   398     // In some cases, it might make more sense to throw an exception
   399     // (when scheme is specified is the string spec and the base URI
   400     // is also specified, for example), but we're just following the
   401     // RFC specifications
   402     if (p_base != null) {
   404       // check to see if this is the current doc - RFC 2396 5.2 #2
   405       // note that this is slightly different from the RFC spec in that
   406       // we don't include the check for query string being null
   407       // - this handles cases where the urispec is just a query
   408       // string or a fragment (e.g. "?y" or "#s") -
   409       // see <http://www.ics.uci.edu/~fielding/url/test1.html> which
   410       // identified this as a bug in the RFC
   411       if (m_path.length() == 0 && m_scheme == null &&
   412           m_host == null) {
   413         m_scheme = p_base.getScheme();
   414         m_userinfo = p_base.getUserinfo();
   415         m_host = p_base.getHost();
   416         m_port = p_base.getPort();
   417         m_path = p_base.getPath();
   419         if (m_queryString == null) {
   420           m_queryString = p_base.getQueryString();
   421         }
   422         return;
   423       }
   425       // check for scheme - RFC 2396 5.2 #3
   426       // if we found a scheme, it means absolute URI, so we're done
   427       if (m_scheme == null) {
   428         m_scheme = p_base.getScheme();
   429       }
   430       else {
   431         return;
   432       }
   434       // check for authority - RFC 2396 5.2 #4
   435       // if we found a host, then we've got a network path, so we're done
   436       if (m_host == null) {
   437         m_userinfo = p_base.getUserinfo();
   438         m_host = p_base.getHost();
   439         m_port = p_base.getPort();
   440       }
   441       else {
   442         return;
   443       }
   445       // check for absolute path - RFC 2396 5.2 #5
   446       if (m_path.length() > 0 &&
   447           m_path.startsWith("/")) {
   448         return;
   449       }
   451       // if we get to this point, we need to resolve relative path
   452       // RFC 2396 5.2 #6
   453       String path = "";
   454       String basePath = p_base.getPath();
   456       // 6a - get all but the last segment of the base URI path
   457       if (basePath != null) {
   458         int lastSlash = basePath.lastIndexOf('/');
   459         if (lastSlash != -1) {
   460           path = basePath.substring(0, lastSlash+1);
   461         }
   462       }
   464       // 6b - append the relative URI path
   465       path = path.concat(m_path);
   467       // 6c - remove all "./" where "." is a complete path segment
   468       index = -1;
   469       while ((index = path.indexOf("/./")) != -1) {
   470         path = path.substring(0, index+1).concat(path.substring(index+3));
   471       }
   473       // 6d - remove "." if path ends with "." as a complete path segment
   474       if (path.endsWith("/.")) {
   475         path = path.substring(0, path.length()-1);
   476       }
   478       // 6e - remove all "<segment>/../" where "<segment>" is a complete
   479       // path segment not equal to ".."
   480       index = 1;
   481       int segIndex = -1;
   482       String tempString = null;
   484       while ((index = path.indexOf("/../", index)) > 0) {
   485         tempString = path.substring(0, path.indexOf("/../"));
   486         segIndex = tempString.lastIndexOf('/');
   487         if (segIndex != -1) {
   488           if (!tempString.substring(segIndex++).equals("..")) {
   489             path = path.substring(0, segIndex).concat(path.substring(index+4));
   490           }
   491           else
   492             index += 4;
   493         }
   494         else
   495           index += 4;
   496       }
   498       // 6f - remove ending "<segment>/.." where "<segment>" is a
   499       // complete path segment
   500       if (path.endsWith("/..")) {
   501         tempString = path.substring(0, path.length()-3);
   502         segIndex = tempString.lastIndexOf('/');
   503         if (segIndex != -1) {
   504           path = path.substring(0, segIndex+1);
   505         }
   506       }
   507       m_path = path;
   508     }
   509   }
   511  /**
   512   * Initialize the scheme for this URI from a URI string spec.
   513   *
   514   * @param p_uriSpec the URI specification (cannot be null)
   515   *
   516   * @exception MalformedURIException if URI does not have a conformant
   517   *                                  scheme
   518   */
   519   private void initializeScheme(String p_uriSpec)
   520                  throws MalformedURIException {
   521     int uriSpecLen = p_uriSpec.length();
   522     int index = 0;
   523     String scheme = null;
   524     char testChar = '\0';
   526     while (index < uriSpecLen) {
   527       testChar = p_uriSpec.charAt(index);
   528       if (testChar == ':' || testChar == '/' ||
   529           testChar == '?' || testChar == '#') {
   530         break;
   531       }
   532       index++;
   533     }
   534     scheme = p_uriSpec.substring(0, index);
   536     if (scheme.length() == 0) {
   537       throw new MalformedURIException("No scheme found in URI.");
   538     }
   539     else {
   540       setScheme(scheme);
   541     }
   542   }
   544  /**
   545   * Initialize the authority (userinfo, host and port) for this
   546   * URI from a URI string spec.
   547   *
   548   * @param p_uriSpec the URI specification (cannot be null)
   549   *
   550   * @exception MalformedURIException if p_uriSpec violates syntax rules
   551   */
   552   private void initializeAuthority(String p_uriSpec)
   553                  throws MalformedURIException {
   554     int index = 0;
   555     int start = 0;
   556     int end = p_uriSpec.length();
   557     char testChar = '\0';
   558     String userinfo = null;
   560     // userinfo is everything up @
   561     if (p_uriSpec.indexOf('@', start) != -1) {
   562       while (index < end) {
   563         testChar = p_uriSpec.charAt(index);
   564         if (testChar == '@') {
   565           break;
   566         }
   567         index++;
   568       }
   569       userinfo = p_uriSpec.substring(start, index);
   570       index++;
   571     }
   573     // host is everything up to ':'
   574     String host = null;
   575     start = index;
   576     while (index < end) {
   577       testChar = p_uriSpec.charAt(index);
   578       if (testChar == ':') {
   579         break;
   580       }
   581       index++;
   582     }
   583     host = p_uriSpec.substring(start, index);
   584     int port = -1;
   585     if (host.length() > 0) {
   586       // port
   587       if (testChar == ':') {
   588         index++;
   589         start = index;
   590         while (index < end) {
   591           index++;
   592         }
   593         String portStr = p_uriSpec.substring(start, index);
   594         if (portStr.length() > 0) {
   595           for (int i = 0; i < portStr.length(); i++) {
   596             if (!isDigit(portStr.charAt(i))) {
   597               throw new MalformedURIException(
   598                    portStr +
   599                    " is invalid. Port should only contain digits!");
   600             }
   601           }
   602           try {
   603             port = Integer.parseInt(portStr);
   604           }
   605           catch (NumberFormatException nfe) {
   606             // can't happen
   607           }
   608         }
   609       }
   610     }
   611     setHost(host);
   612     setPort(port);
   613     setUserinfo(userinfo);
   614   }
   616  /**
   617   * Initialize the path for this URI from a URI string spec.
   618   *
   619   * @param p_uriSpec the URI specification (cannot be null)
   620   *
   621   * @exception MalformedURIException if p_uriSpec violates syntax rules
   622   */
   623   private void initializePath(String p_uriSpec)
   624                  throws MalformedURIException {
   625     if (p_uriSpec == null) {
   626       throw new MalformedURIException(
   627                 "Cannot initialize path from null string!");
   628     }
   630     int index = 0;
   631     int start = 0;
   632     int end = p_uriSpec.length();
   633     char testChar = '\0';
   635     // path - everything up to query string or fragment
   636     while (index < end) {
   637       testChar = p_uriSpec.charAt(index);
   638       if (testChar == '?' || testChar == '#') {
   639         break;
   640       }
   641       // check for valid escape sequence
   642       if (testChar == '%') {
   643          if (index+2 >= end ||
   644             !isHex(p_uriSpec.charAt(index+1)) ||
   645             !isHex(p_uriSpec.charAt(index+2))) {
   646           throw new MalformedURIException(
   647                 "Path contains invalid escape sequence!");
   648          }
   649       }
   650       else if (!isReservedCharacter(testChar) &&
   651                !isUnreservedCharacter(testChar)) {
   652         throw new MalformedURIException(
   653                   "Path contains invalid character: " + testChar);
   654       }
   655       index++;
   656     }
   657     m_path = p_uriSpec.substring(start, index);
   659     // query - starts with ? and up to fragment or end
   660     if (testChar == '?') {
   661       index++;
   662       start = index;
   663       while (index < end) {
   664         testChar = p_uriSpec.charAt(index);
   665         if (testChar == '#') {
   666           break;
   667         }
   668         if (testChar == '%') {
   669            if (index+2 >= end ||
   670               !isHex(p_uriSpec.charAt(index+1)) ||
   671               !isHex(p_uriSpec.charAt(index+2))) {
   672             throw new MalformedURIException(
   673                     "Query string contains invalid escape sequence!");
   674            }
   675         }
   676         else if (!isReservedCharacter(testChar) &&
   677                  !isUnreservedCharacter(testChar)) {
   678           throw new MalformedURIException(
   679                 "Query string contains invalid character:" + testChar);
   680         }
   681         index++;
   682       }
   683       m_queryString = p_uriSpec.substring(start, index);
   684     }
   686     // fragment - starts with #
   687     if (testChar == '#') {
   688       index++;
   689       start = index;
   690       while (index < end) {
   691         testChar = p_uriSpec.charAt(index);
   693         if (testChar == '%') {
   694            if (index+2 >= end ||
   695               !isHex(p_uriSpec.charAt(index+1)) ||
   696               !isHex(p_uriSpec.charAt(index+2))) {
   697             throw new MalformedURIException(
   698                     "Fragment contains invalid escape sequence!");
   699            }
   700         }
   701         else if (!isReservedCharacter(testChar) &&
   702                  !isUnreservedCharacter(testChar)) {
   703           throw new MalformedURIException(
   704                 "Fragment contains invalid character:"+testChar);
   705         }
   706         index++;
   707       }
   708       m_fragment = p_uriSpec.substring(start, index);
   709     }
   710   }
   712  /**
   713   * Get the scheme for this URI.
   714   *
   715   * @return the scheme for this URI
   716   */
   717   public String getScheme() {
   718     return m_scheme;
   719   }
   721  /**
   722   * Get the scheme-specific part for this URI (everything following the
   723   * scheme and the first colon). See RFC 2396 Section 5.2 for spec.
   724   *
   725   * @return the scheme-specific part for this URI
   726   */
   727   public String getSchemeSpecificPart() {
   728     StringBuffer schemespec = new StringBuffer();
   730     if (m_userinfo != null || m_host != null || m_port != -1) {
   731       schemespec.append("//");
   732     }
   734     if (m_userinfo != null) {
   735       schemespec.append(m_userinfo);
   736       schemespec.append('@');
   737     }
   739     if (m_host != null) {
   740       schemespec.append(m_host);
   741     }
   743     if (m_port != -1) {
   744       schemespec.append(':');
   745       schemespec.append(m_port);
   746     }
   748     if (m_path != null) {
   749       schemespec.append((m_path));
   750     }
   752     if (m_queryString != null) {
   753       schemespec.append('?');
   754       schemespec.append(m_queryString);
   755     }
   757     if (m_fragment != null) {
   758       schemespec.append('#');
   759       schemespec.append(m_fragment);
   760     }
   762     return schemespec.toString();
   763   }
   765  /**
   766   * Get the userinfo for this URI.
   767   *
   768   * @return the userinfo for this URI (null if not specified).
   769   */
   770   public String getUserinfo() {
   771     return m_userinfo;
   772   }
   774   /**
   775   * Get the host for this URI.
   776   *
   777   * @return the host for this URI (null if not specified).
   778   */
   779   public String getHost() {
   780     return m_host;
   781   }
   783  /**
   784   * Get the port for this URI.
   785   *
   786   * @return the port for this URI (-1 if not specified).
   787   */
   788   public int getPort() {
   789     return m_port;
   790   }
   792  /**
   793   * Get the path for this URI (optionally with the query string and
   794   * fragment).
   795   *
   796   * @param p_includeQueryString if true (and query string is not null),
   797   *                             then a "?" followed by the query string
   798   *                             will be appended
   799   * @param p_includeFragment if true (and fragment is not null),
   800   *                             then a "#" followed by the fragment
   801   *                             will be appended
   802   *
   803   * @return the path for this URI possibly including the query string
   804   *         and fragment
   805   */
   806   public String getPath(boolean p_includeQueryString,
   807                         boolean p_includeFragment) {
   808     StringBuffer pathString = new StringBuffer(m_path);
   810     if (p_includeQueryString && m_queryString != null) {
   811       pathString.append('?');
   812       pathString.append(m_queryString);
   813     }
   815     if (p_includeFragment && m_fragment != null) {
   816       pathString.append('#');
   817       pathString.append(m_fragment);
   818     }
   819     return pathString.toString();
   820   }
   822  /**
   823   * Get the path for this URI. Note that the value returned is the path
   824   * only and does not include the query string or fragment.
   825   *
   826   * @return the path for this URI.
   827   */
   828   public String getPath() {
   829     return m_path;
   830   }
   832  /**
   833   * Get the query string for this URI.
   834   *
   835   * @return the query string for this URI. Null is returned if there
   836   *         was no "?" in the URI spec, empty string if there was a
   837   *         "?" but no query string following it.
   838   */
   839   public String getQueryString() {
   840     return m_queryString;
   841   }
   843  /**
   844   * Get the fragment for this URI.
   845   *
   846   * @return the fragment for this URI. Null is returned if there
   847   *         was no "#" in the URI spec, empty string if there was a
   848   *         "#" but no fragment following it.
   849   */
   850   public String getFragment() {
   851     return m_fragment;
   852   }
   854  /**
   855   * Set the scheme for this URI. The scheme is converted to lowercase
   856   * before it is set.
   857   *
   858   * @param p_scheme the scheme for this URI (cannot be null)
   859   *
   860   * @exception MalformedURIException if p_scheme is not a conformant
   861   *                                  scheme name
   862   */
   863   public void setScheme(String p_scheme) throws MalformedURIException {
   864     if (p_scheme == null) {
   865       throw new MalformedURIException(
   866                 "Cannot set scheme from null string!");
   867     }
   868     if (!isConformantSchemeName(p_scheme)) {
   869       throw new MalformedURIException("The scheme is not conformant.");
   870     }
   872     m_scheme = p_scheme.toLowerCase();
   873   }
   875  /**
   876   * Set the userinfo for this URI. If a non-null value is passed in and
   877   * the host value is null, then an exception is thrown.
   878   *
   879   * @param p_userinfo the userinfo for this URI
   880   *
   881   * @exception MalformedURIException if p_userinfo contains invalid
   882   *                                  characters
   883   */
   884   public void setUserinfo(String p_userinfo) throws MalformedURIException {
   885     if (p_userinfo == null) {
   886       m_userinfo = null;
   887     }
   888     else {
   889       if (m_host == null) {
   890         throw new MalformedURIException(
   891                      "Userinfo cannot be set when host is null!");
   892       }
   894       // userinfo can contain alphanumerics, mark characters, escaped
   895       // and ';',':','&','=','+','$',','
   896       int index = 0;
   897       int end = p_userinfo.length();
   898       char testChar = '\0';
   899       while (index < end) {
   900         testChar = p_userinfo.charAt(index);
   901         if (testChar == '%') {
   902           if (index+2 >= end ||
   903               !isHex(p_userinfo.charAt(index+1)) ||
   904               !isHex(p_userinfo.charAt(index+2))) {
   905             throw new MalformedURIException(
   906                   "Userinfo contains invalid escape sequence!");
   907           }
   908         }
   909         else if (!isUnreservedCharacter(testChar) &&
   910                  USERINFO_CHARACTERS.indexOf(testChar) == -1) {
   911           throw new MalformedURIException(
   912                   "Userinfo contains invalid character:"+testChar);
   913         }
   914         index++;
   915       }
   916     }
   917     m_userinfo = p_userinfo;
   918   }
   920   /**
   921   * Set the host for this URI. If null is passed in, the userinfo
   922   * field is also set to null and the port is set to -1.
   923   *
   924   * @param p_host the host for this URI
   925   *
   926   * @exception MalformedURIException if p_host is not a valid IP
   927   *                                  address or DNS hostname.
   928   */
   929   public void setHost(String p_host) throws MalformedURIException {
   930     if (p_host == null || p_host.trim().length() == 0) {
   931       m_host = p_host;
   932       m_userinfo = null;
   933       m_port = -1;
   934     }
   935     else if (!isWellFormedAddress(p_host)) {
   936       throw new MalformedURIException("Host is not a well formed address!");
   937     }
   938     m_host = p_host;
   939   }
   941  /**
   942   * Set the port for this URI. -1 is used to indicate that the port is
   943   * not specified, otherwise valid port numbers are  between 0 and 65535.
   944   * If a valid port number is passed in and the host field is null,
   945   * an exception is thrown.
   946   *
   947   * @param p_port the port number for this URI
   948   *
   949   * @exception MalformedURIException if p_port is not -1 and not a
   950   *                                  valid port number
   951   */
   952   public void setPort(int p_port) throws MalformedURIException {
   953     if (p_port >= 0 && p_port <= 65535) {
   954       if (m_host == null) {
   955         throw new MalformedURIException(
   956                       "Port cannot be set when host is null!");
   957       }
   958     }
   959     else if (p_port != -1) {
   960       throw new MalformedURIException("Invalid port number!");
   961     }
   962     m_port = p_port;
   963   }
   965  /**
   966   * Set the path for this URI. If the supplied path is null, then the
   967   * query string and fragment are set to null as well. If the supplied
   968   * path includes a query string and/or fragment, these fields will be
   969   * parsed and set as well. Note that, for URIs following the "generic
   970   * URI" syntax, the path specified should start with a slash.
   971   * For URIs that do not follow the generic URI syntax, this method
   972   * sets the scheme-specific part.
   973   *
   974   * @param p_path the path for this URI (may be null)
   975   *
   976   * @exception MalformedURIException if p_path contains invalid
   977   *                                  characters
   978   */
   979   public void setPath(String p_path) throws MalformedURIException {
   980     if (p_path == null) {
   981       m_path = null;
   982       m_queryString = null;
   983       m_fragment = null;
   984     }
   985     else {
   986       initializePath(p_path);
   987     }
   988   }
   990  /**
   991   * Append to the end of the path of this URI. If the current path does
   992   * not end in a slash and the path to be appended does not begin with
   993   * a slash, a slash will be appended to the current path before the
   994   * new segment is added. Also, if the current path ends in a slash
   995   * and the new segment begins with a slash, the extra slash will be
   996   * removed before the new segment is appended.
   997   *
   998   * @param p_addToPath the new segment to be added to the current path
   999   *
  1000   * @exception MalformedURIException if p_addToPath contains syntax
  1001   *                                  errors
  1002   */
  1003   public void appendPath(String p_addToPath)
  1004                          throws MalformedURIException {
  1005     if (p_addToPath == null || p_addToPath.trim().length() == 0) {
  1006       return;
  1009     if (!isURIString(p_addToPath)) {
  1010       throw new MalformedURIException(
  1011               "Path contains invalid character!");
  1014     if (m_path == null || m_path.trim().length() == 0) {
  1015       if (p_addToPath.startsWith("/")) {
  1016         m_path = p_addToPath;
  1018       else {
  1019         m_path = "/" + p_addToPath;
  1022     else if (m_path.endsWith("/")) {
  1023       if (p_addToPath.startsWith("/")) {
  1024         m_path = m_path.concat(p_addToPath.substring(1));
  1026       else {
  1027         m_path = m_path.concat(p_addToPath);
  1030     else {
  1031       if (p_addToPath.startsWith("/")) {
  1032         m_path = m_path.concat(p_addToPath);
  1034       else {
  1035         m_path = m_path.concat("/" + p_addToPath);
  1040  /**
  1041   * Set the query string for this URI. A non-null value is valid only
  1042   * if this is an URI conforming to the generic URI syntax and
  1043   * the path value is not null.
  1045   * @param p_queryString the query string for this URI
  1047   * @exception MalformedURIException if p_queryString is not null and this
  1048   *                                  URI does not conform to the generic
  1049   *                                  URI syntax or if the path is null
  1050   */
  1051   public void setQueryString(String p_queryString) throws MalformedURIException {
  1052     if (p_queryString == null) {
  1053       m_queryString = null;
  1055     else if (!isGenericURI()) {
  1056       throw new MalformedURIException(
  1057               "Query string can only be set for a generic URI!");
  1059     else if (getPath() == null) {
  1060       throw new MalformedURIException(
  1061               "Query string cannot be set when path is null!");
  1063     else if (!isURIString(p_queryString)) {
  1064       throw new MalformedURIException(
  1065               "Query string contains invalid character!");
  1067     else {
  1068       m_queryString = p_queryString;
  1072  /**
  1073   * Set the fragment for this URI. A non-null value is valid only
  1074   * if this is a URI conforming to the generic URI syntax and
  1075   * the path value is not null.
  1077   * @param p_fragment the fragment for this URI
  1079   * @exception MalformedURIException if p_fragment is not null and this
  1080   *                                  URI does not conform to the generic
  1081   *                                  URI syntax or if the path is null
  1082   */
  1083   public void setFragment(String p_fragment) throws MalformedURIException {
  1084     if (p_fragment == null) {
  1085       m_fragment = null;
  1087     else if (!isGenericURI()) {
  1088       throw new MalformedURIException(
  1089          "Fragment can only be set for a generic URI!");
  1091     else if (getPath() == null) {
  1092       throw new MalformedURIException(
  1093               "Fragment cannot be set when path is null!");
  1095     else if (!isURIString(p_fragment)) {
  1096       throw new MalformedURIException(
  1097               "Fragment contains invalid character!");
  1099     else {
  1100       m_fragment = p_fragment;
  1104  /**
  1105   * Determines if the passed-in Object is equivalent to this URI.
  1107   * @param p_test the Object to test for equality.
  1109   * @return true if p_test is a URI with all values equal to this
  1110   *         URI, false otherwise
  1111   */
  1112   public boolean equals(Object p_test) {
  1113     if (p_test instanceof JaxmURI) {
  1114       JaxmURI testURI = (JaxmURI) p_test;
  1115       if (((m_scheme == null && testURI.m_scheme == null) ||
  1116            (m_scheme != null && testURI.m_scheme != null &&
  1117             m_scheme.equals(testURI.m_scheme))) &&
  1118           ((m_userinfo == null && testURI.m_userinfo == null) ||
  1119            (m_userinfo != null && testURI.m_userinfo != null &&
  1120             m_userinfo.equals(testURI.m_userinfo))) &&
  1121           ((m_host == null && testURI.m_host == null) ||
  1122            (m_host != null && testURI.m_host != null &&
  1123             m_host.equals(testURI.m_host))) &&
  1124             m_port == testURI.m_port &&
  1125           ((m_path == null && testURI.m_path == null) ||
  1126            (m_path != null && testURI.m_path != null &&
  1127             m_path.equals(testURI.m_path))) &&
  1128           ((m_queryString == null && testURI.m_queryString == null) ||
  1129            (m_queryString != null && testURI.m_queryString != null &&
  1130             m_queryString.equals(testURI.m_queryString))) &&
  1131           ((m_fragment == null && testURI.m_fragment == null) ||
  1132            (m_fragment != null && testURI.m_fragment != null &&
  1133             m_fragment.equals(testURI.m_fragment)))) {
  1134         return true;
  1137     return false;
  1140   public int hashCode() {
  1141           // No members safe to use, just default to a constant.
  1142           return 153214;
  1145  /**
  1146   * Get the URI as a string specification. See RFC 2396 Section 5.2.
  1148   * @return the URI string specification
  1149   */
  1150   public String toString() {
  1151     StringBuffer uriSpecString = new StringBuffer();
  1153     if (m_scheme != null) {
  1154       uriSpecString.append(m_scheme);
  1155       uriSpecString.append(':');
  1157     uriSpecString.append(getSchemeSpecificPart());
  1158     return uriSpecString.toString();
  1161  /**
  1162   * Get the indicator as to whether this URI uses the "generic URI"
  1163   * syntax.
  1165   * @return true if this URI uses the "generic URI" syntax, false
  1166   *         otherwise
  1167   */
  1168   public boolean isGenericURI() {
  1169     // presence of the host (whether valid or empty) means
  1170     // double-slashes which means generic uri
  1171     return (m_host != null);
  1174  /**
  1175   * Determine whether a scheme conforms to the rules for a scheme name.
  1176   * A scheme is conformant if it starts with an alphanumeric, and
  1177   * contains only alphanumerics, '+','-' and '.'.
  1179   * @return true if the scheme is conformant, false otherwise
  1180   */
  1181   public static boolean isConformantSchemeName(String p_scheme) {
  1182     if (p_scheme == null || p_scheme.trim().length() == 0) {
  1183       return false;
  1186     if (!isAlpha(p_scheme.charAt(0))) {
  1187       return false;
  1190     char testChar;
  1191     for (int i = 1; i < p_scheme.length(); i++) {
  1192       testChar = p_scheme.charAt(i);
  1193       if (!isAlphanum(testChar) &&
  1194           SCHEME_CHARACTERS.indexOf(testChar) == -1) {
  1195         return false;
  1199     return true;
  1202  /**
  1203   * Determine whether a string is syntactically capable of representing
  1204   * a valid IPv4 address or the domain name of a network host. A valid
  1205   * IPv4 address consists of four decimal digit groups separated by a
  1206   * '.'. A hostname consists of domain labels (each of which must
  1207   * begin and end with an alphanumeric but may contain '-') separated
  1208   & by a '.'. See RFC 2396 Section 3.2.2.
  1210   * @return true if the string is a syntactically valid IPv4 address
  1211   *              or hostname
  1212   */
  1213   public static boolean isWellFormedAddress(String p_address) {
  1214     if (p_address == null) {
  1215       return false;
  1218     String address = p_address.trim();
  1219     int addrLength = address.length();
  1220     if (addrLength == 0 || addrLength > 255) {
  1221       return false;
  1224     if (address.startsWith(".") || address.startsWith("-")) {
  1225       return false;
  1228     // rightmost domain label starting with digit indicates IP address
  1229     // since top level domain label can only start with an alpha
  1230     // see RFC 2396 Section 3.2.2
  1231     int index = address.lastIndexOf('.');
  1232     if (address.endsWith(".")) {
  1233       index = address.substring(0, index).lastIndexOf('.');
  1236     if (index+1 < addrLength && isDigit(p_address.charAt(index+1))) {
  1237       char testChar;
  1238       int numDots = 0;
  1240       // make sure that 1) we see only digits and dot separators, 2) that
  1241       // any dot separator is preceded and followed by a digit and
  1242       // 3) that we find 3 dots
  1243       for (int i = 0; i < addrLength; i++) {
  1244         testChar = address.charAt(i);
  1245         if (testChar == '.') {
  1246           if (!isDigit(address.charAt(i-1)) ||
  1247               (i+1 < addrLength && !isDigit(address.charAt(i+1)))) {
  1248             return false;
  1250           numDots++;
  1252         else if (!isDigit(testChar)) {
  1253           return false;
  1256       if (numDots != 3) {
  1257         return false;
  1260     else {
  1261       // domain labels can contain alphanumerics and '-"
  1262       // but must start and end with an alphanumeric
  1263       char testChar;
  1265       for (int i = 0; i < addrLength; i++) {
  1266         testChar = address.charAt(i);
  1267         if (testChar == '.') {
  1268           if (!isAlphanum(address.charAt(i-1))) {
  1269             return false;
  1271           if (i+1 < addrLength && !isAlphanum(address.charAt(i+1))) {
  1272             return false;
  1275         else if (!isAlphanum(testChar) && testChar != '-') {
  1276           return false;
  1280     return true;
  1284  /**
  1285   * Determine whether a char is a digit.
  1287   * @return true if the char is betweeen '0' and '9', false otherwise
  1288   */
  1289   private static boolean isDigit(char p_char) {
  1290     return p_char >= '0' && p_char <= '9';
  1293  /**
  1294   * Determine whether a character is a hexadecimal character.
  1296   * @return true if the char is betweeen '0' and '9', 'a' and 'f'
  1297   *         or 'A' and 'F', false otherwise
  1298   */
  1299   private static boolean isHex(char p_char) {
  1300     return (isDigit(p_char) ||
  1301             (p_char >= 'a' && p_char <= 'f') ||
  1302             (p_char >= 'A' && p_char <= 'F'));
  1305  /**
  1306   * Determine whether a char is an alphabetic character: a-z or A-Z
  1308   * @return true if the char is alphabetic, false otherwise
  1309   */
  1310   private static boolean isAlpha(char p_char) {
  1311     return ((p_char >= 'a' && p_char <= 'z') ||
  1312             (p_char >= 'A' && p_char <= 'Z' ));
  1315  /**
  1316   * Determine whether a char is an alphanumeric: 0-9, a-z or A-Z
  1318   * @return true if the char is alphanumeric, false otherwise
  1319   */
  1320   private static boolean isAlphanum(char p_char) {
  1321     return (isAlpha(p_char) || isDigit(p_char));
  1324  /**
  1325   * Determine whether a character is a reserved character:
  1326   * ';', '/', '?', ':', '@', '&', '=', '+', '$' or ','
  1328   * @return true if the string contains any reserved characters
  1329   */
  1330   private static boolean isReservedCharacter(char p_char) {
  1331     return RESERVED_CHARACTERS.indexOf(p_char) != -1;
  1334  /**
  1335   * Determine whether a char is an unreserved character.
  1337   * @return true if the char is unreserved, false otherwise
  1338   */
  1339   private static boolean isUnreservedCharacter(char p_char) {
  1340     return (isAlphanum(p_char) ||
  1341             MARK_CHARACTERS.indexOf(p_char) != -1);
  1344  /**
  1345   * Determine whether a given string contains only URI characters (also
  1346   * called "uric" in RFC 2396). uric consist of all reserved
  1347   * characters, unreserved characters and escaped characters.
  1349   * @return true if the string is comprised of uric, false otherwise
  1350   */
  1351   private static boolean isURIString(String p_uric) {
  1352     if (p_uric == null) {
  1353       return false;
  1355     int end = p_uric.length();
  1356     char testChar = '\0';
  1357     for (int i = 0; i < end; i++) {
  1358       testChar = p_uric.charAt(i);
  1359       if (testChar == '%') {
  1360         if (i+2 >= end ||
  1361             !isHex(p_uric.charAt(i+1)) ||
  1362             !isHex(p_uric.charAt(i+2))) {
  1363           return false;
  1365         else {
  1366           i += 2;
  1367           continue;
  1370       if (isReservedCharacter(testChar) ||
  1371           isUnreservedCharacter(testChar)) {
  1372           continue;
  1374       else {
  1375         return false;
  1378     return true;

mercurial