0001: /*
0002: * The contents of this file are subject to the terms
0003: * of the Common Development and Distribution License
0004: * (the "License"). You may not use this file except
0005: * in compliance with the License.
0006: *
0007: * You can obtain a copy of the license at
0008: * https://jwsdp.dev.java.net/CDDLv1.0.html
0009: * See the License for the specific language governing
0010: * permissions and limitations under the License.
0011: *
0012: * When distributing Covered Code, include this CDDL
0013: * HEADER in each file and include the License file at
0014: * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable,
0015: * add the following below this CDDL HEADER, with the
0016: * fields enclosed by brackets "[]" replaced with your
0017: * own identifying information: Portions Copyright [yyyy]
0018: * [name of copyright owner]
0019: */
0020: /*
0021: * $Id: JaxmURI.java,v 1.2 2007/07/16 16:41:25 ofung Exp $
0022: * $Revision: 1.2 $
0023: * $Date: 2007/07/16 16:41:25 $
0024: */
0025:
0026: /*
0027: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
0028: *
0029: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
0030: *
0031: * The contents of this file are subject to the terms of either the GNU
0032: * General Public License Version 2 only ("GPL") or the Common Development
0033: * and Distribution License("CDDL") (collectively, the "License"). You
0034: * may not use this file except in compliance with the License. You can obtain
0035: * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
0036: * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
0037: * language governing permissions and limitations under the License.
0038: *
0039: * When distributing the software, include this License Header Notice in each
0040: * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
0041: * Sun designates this particular file as subject to the "Classpath" exception
0042: * as provided by Sun in the GPL Version 2 section of the License file that
0043: * accompanied this code. If applicable, add the following below the License
0044: * Header, with the fields enclosed by brackets [] replaced by your own
0045: * identifying information: "Portions Copyrighted [year]
0046: * [name of copyright owner]"
0047: *
0048: * Contributor(s):
0049: *
0050: * If you wish your version of this file to be governed by only the CDDL or
0051: * only the GPL Version 2, indicate your decision by adding "[Contributor]
0052: * elects to include this software in this distribution under the [CDDL or GPL
0053: * Version 2] license." If you don't indicate a single choice of license, a
0054: * recipient has the option to distribute your version of this file under
0055: * either the CDDL, the GPL Version 2 or to extend the choice of license to
0056: * its licensees as provided above. However, if you add GPL Version 2 code
0057: * and therefore, elected the GPL Version 2 license, then the option applies
0058: * only if the new code is made subject to such option by the copyright
0059: * holder.
0060: */
0061: package com.sun.xml.messaging.saaj.util;
0062:
0063: // Imported from: org.apache.xerces.util
0064: // Needed to work around differences in JDK1.2 and 1.3 and deal with userInfo
0065:
0066: import java.io.IOException;
0067: import java.io.Serializable;
0068:
0069: /**********************************************************************
0070: * A class to represent a Uniform Resource Identifier (URI). This class
0071: * is designed to handle the parsing of URIs and provide access to
0072: * the various components (scheme, host, port, userinfo, path, query
0073: * string and fragment) that may constitute a URI.
0074: * <p>
0075: * Parsing of a URI specification is done according to the URI
0076: * syntax described in RFC 2396
0077: * <http://www.ietf.org/rfc/rfc2396.txt?number=2396>. Every URI consists
0078: * of a scheme, followed by a colon (':'), followed by a scheme-specific
0079: * part. For URIs that follow the "generic URI" syntax, the scheme-
0080: * specific part begins with two slashes ("//") and may be followed
0081: * by an authority segment (comprised of user information, host, and
0082: * port), path segment, query segment and fragment. Note that RFC 2396
0083: * no longer specifies the use of the parameters segment and excludes
0084: * the "user:password" syntax as part of the authority segment. If
0085: * "user:password" appears in a URI, the entire user/password string
0086: * is stored as userinfo.
0087: * <p>
0088: * For URIs that do not follow the "generic URI" syntax (e.g. mailto),
0089: * the entire scheme-specific part is treated as the "path" portion
0090: * of the URI.
0091: * <p>
0092: * Note that, unlike the java.net.URL class, this class does not provide
0093: * any built-in network access functionality nor does it provide any
0094: * scheme-specific functionality (for example, it does not know a
0095: * default port for a specific scheme). Rather, it only knows the
0096: * grammar and basic set of operations that can be applied to a URI.
0097: *
0098: * @version $Id: JaxmURI.java,v 1.2 2007/07/16 16:41:25 ofung Exp $
0099: *
0100: **********************************************************************/
0101: public class JaxmURI implements Serializable {
0102:
0103: /*******************************************************************
0104: * MalformedURIExceptions are thrown in the process of building a URI
0105: * or setting fields on a URI when an operation would result in an
0106: * invalid URI specification.
0107: *
0108: ********************************************************************/
0109: public static class MalformedURIException extends IOException {
0110:
0111: /******************************************************************
0112: * Constructs a <code>MalformedURIException</code> with no specified
0113: * detail message.
0114: ******************************************************************/
0115: public MalformedURIException() {
0116: super ();
0117: }
0118:
0119: /*****************************************************************
0120: * Constructs a <code>MalformedURIException</code> with the
0121: * specified detail message.
0122: *
0123: * @param p_msg the detail message.
0124: ******************************************************************/
0125: public MalformedURIException(String p_msg) {
0126: super (p_msg);
0127: }
0128: }
0129:
0130: /** reserved characters */
0131: private static final String RESERVED_CHARACTERS = ";/?:@&=+$,";
0132:
0133: /** URI punctuation mark characters - these, combined with
0134: alphanumerics, constitute the "unreserved" characters */
0135: private static final String MARK_CHARACTERS = "-_.!~*'() ";
0136:
0137: /** scheme can be composed of alphanumerics and these characters */
0138: private static final String SCHEME_CHARACTERS = "+-.";
0139:
0140: /** userinfo can be composed of unreserved, escaped and these
0141: characters */
0142: private static final String USERINFO_CHARACTERS = ";:&=+$,";
0143:
0144: /** Stores the scheme (usually the protocol) for this URI. */
0145: private String m_scheme = null;
0146:
0147: /** If specified, stores the userinfo for this URI; otherwise null */
0148: private String m_userinfo = null;
0149:
0150: /** If specified, stores the host for this URI; otherwise null */
0151: private String m_host = null;
0152:
0153: /** If specified, stores the port for this URI; otherwise -1 */
0154: private int m_port = -1;
0155:
0156: /** If specified, stores the path for this URI; otherwise null */
0157: private String m_path = null;
0158:
0159: /** If specified, stores the query string for this URI; otherwise
0160: null. */
0161: private String m_queryString = null;
0162:
0163: /** If specified, stores the fragment for this URI; otherwise null */
0164: private String m_fragment = null;
0165:
0166: private static boolean DEBUG = false;
0167:
0168: /**
0169: * Construct a new and uninitialized URI.
0170: */
0171: public JaxmURI() {
0172: }
0173:
0174: /**
0175: * Construct a new URI from another URI. All fields for this URI are
0176: * set equal to the fields of the URI passed in.
0177: *
0178: * @param p_other the URI to copy (cannot be null)
0179: */
0180: public JaxmURI(JaxmURI p_other) {
0181: initialize(p_other);
0182: }
0183:
0184: /**
0185: * Construct a new URI from a URI specification string. If the
0186: * specification follows the "generic URI" syntax, (two slashes
0187: * following the first colon), the specification will be parsed
0188: * accordingly - setting the scheme, userinfo, host,port, path, query
0189: * string and fragment fields as necessary. If the specification does
0190: * not follow the "generic URI" syntax, the specification is parsed
0191: * into a scheme and scheme-specific part (stored as the path) only.
0192: *
0193: * @param p_uriSpec the URI specification string (cannot be null or
0194: * empty)
0195: *
0196: * @exception MalformedURIException if p_uriSpec violates any syntax
0197: * rules
0198: */
0199: public JaxmURI(String p_uriSpec) throws MalformedURIException {
0200: this ((JaxmURI) null, p_uriSpec);
0201: }
0202:
0203: /**
0204: * Construct a new URI from a base URI and a URI specification string.
0205: * The URI specification string may be a relative URI.
0206: *
0207: * @param p_base the base URI (cannot be null if p_uriSpec is null or
0208: * empty)
0209: * @param p_uriSpec the URI specification string (cannot be null or
0210: * empty if p_base is null)
0211: *
0212: * @exception MalformedURIException if p_uriSpec violates any syntax
0213: * rules
0214: */
0215: public JaxmURI(JaxmURI p_base, String p_uriSpec)
0216: throws MalformedURIException {
0217: initialize(p_base, p_uriSpec);
0218: }
0219:
0220: /**
0221: * Construct a new URI that does not follow the generic URI syntax.
0222: * Only the scheme and scheme-specific part (stored as the path) are
0223: * initialized.
0224: *
0225: * @param p_scheme the URI scheme (cannot be null or empty)
0226: * @param p_schemeSpecificPart the scheme-specific part (cannot be
0227: * null or empty)
0228: *
0229: * @exception MalformedURIException if p_scheme violates any
0230: * syntax rules
0231: */
0232: public JaxmURI(String p_scheme, String p_schemeSpecificPart)
0233: throws MalformedURIException {
0234: if (p_scheme == null || p_scheme.trim().length() == 0) {
0235: throw new MalformedURIException(
0236: "Cannot construct URI with null/empty scheme!");
0237: }
0238: if (p_schemeSpecificPart == null
0239: || p_schemeSpecificPart.trim().length() == 0) {
0240: throw new MalformedURIException(
0241: "Cannot construct URI with null/empty scheme-specific part!");
0242: }
0243: setScheme(p_scheme);
0244: setPath(p_schemeSpecificPart);
0245: }
0246:
0247: /**
0248: * Construct a new URI that follows the generic URI syntax from its
0249: * component parts. Each component is validated for syntax and some
0250: * basic semantic checks are performed as well. See the individual
0251: * setter methods for specifics.
0252: *
0253: * @param p_scheme the URI scheme (cannot be null or empty)
0254: * @param p_host the hostname or IPv4 address for the URI
0255: * @param p_path the URI path - if the path contains '?' or '#',
0256: * then the query string and/or fragment will be
0257: * set from the path; however, if the query and
0258: * fragment are specified both in the path and as
0259: * separate parameters, an exception is thrown
0260: * @param p_queryString the URI query string (cannot be specified
0261: * if path is null)
0262: * @param p_fragment the URI fragment (cannot be specified if path
0263: * is null)
0264: *
0265: * @exception MalformedURIException if any of the parameters violates
0266: * syntax rules or semantic rules
0267: */
0268: public JaxmURI(String p_scheme, String p_host, String p_path,
0269: String p_queryString, String p_fragment)
0270: throws MalformedURIException {
0271: this (p_scheme, null, p_host, -1, p_path, p_queryString,
0272: p_fragment);
0273: }
0274:
0275: /**
0276: * Construct a new URI that follows the generic URI syntax from its
0277: * component parts. Each component is validated for syntax and some
0278: * basic semantic checks are performed as well. See the individual
0279: * setter methods for specifics.
0280: *
0281: * @param p_scheme the URI scheme (cannot be null or empty)
0282: * @param p_userinfo the URI userinfo (cannot be specified if host
0283: * is null)
0284: * @param p_host the hostname or IPv4 address for the URI
0285: * @param p_port the URI port (may be -1 for "unspecified"; cannot
0286: * be specified if host is null)
0287: * @param p_path the URI path - if the path contains '?' or '#',
0288: * then the query string and/or fragment will be
0289: * set from the path; however, if the query and
0290: * fragment are specified both in the path and as
0291: * separate parameters, an exception is thrown
0292: * @param p_queryString the URI query string (cannot be specified
0293: * if path is null)
0294: * @param p_fragment the URI fragment (cannot be specified if path
0295: * is null)
0296: *
0297: * @exception MalformedURIException if any of the parameters violates
0298: * syntax rules or semantic rules
0299: */
0300: public JaxmURI(String p_scheme, String p_userinfo, String p_host,
0301: int p_port, String p_path, String p_queryString,
0302: String p_fragment) throws MalformedURIException {
0303: if (p_scheme == null || p_scheme.trim().length() == 0) {
0304: throw new MalformedURIException("Scheme is required!");
0305: }
0306:
0307: if (p_host == null) {
0308: if (p_userinfo != null) {
0309: throw new MalformedURIException(
0310: "Userinfo may not be specified if host is not specified!");
0311: }
0312: if (p_port != -1) {
0313: throw new MalformedURIException(
0314: "Port may not be specified if host is not specified!");
0315: }
0316: }
0317:
0318: if (p_path != null) {
0319: if (p_path.indexOf('?') != -1 && p_queryString != null) {
0320: throw new MalformedURIException(
0321: "Query string cannot be specified in path and query string!");
0322: }
0323:
0324: if (p_path.indexOf('#') != -1 && p_fragment != null) {
0325: throw new MalformedURIException(
0326: "Fragment cannot be specified in both the path and fragment!");
0327: }
0328: }
0329:
0330: setScheme(p_scheme);
0331: setHost(p_host);
0332: setPort(p_port);
0333: setUserinfo(p_userinfo);
0334: setPath(p_path);
0335: setQueryString(p_queryString);
0336: setFragment(p_fragment);
0337: }
0338:
0339: /**
0340: * Initialize all fields of this URI from another URI.
0341: *
0342: * @param p_other the URI to copy (cannot be null)
0343: */
0344: private void initialize(JaxmURI p_other) {
0345: m_scheme = p_other.getScheme();
0346: m_userinfo = p_other.getUserinfo();
0347: m_host = p_other.getHost();
0348: m_port = p_other.getPort();
0349: m_path = p_other.getPath();
0350: m_queryString = p_other.getQueryString();
0351: m_fragment = p_other.getFragment();
0352: }
0353:
0354: /**
0355: * Initializes this URI from a base URI and a URI specification string.
0356: * See RFC 2396 Section 4 and Appendix B for specifications on parsing
0357: * the URI and Section 5 for specifications on resolving relative URIs
0358: * and relative paths.
0359: *
0360: * @param p_base the base URI (may be null if p_uriSpec is an absolute
0361: * URI)
0362: * @param p_uriSpec the URI spec string which may be an absolute or
0363: * relative URI (can only be null/empty if p_base
0364: * is not null)
0365: *
0366: * @exception MalformedURIException if p_base is null and p_uriSpec
0367: * is not an absolute URI or if
0368: * p_uriSpec violates syntax rules
0369: */
0370: private void initialize(JaxmURI p_base, String p_uriSpec)
0371: throws MalformedURIException {
0372: if (p_base == null
0373: && (p_uriSpec == null || p_uriSpec.trim().length() == 0)) {
0374: throw new MalformedURIException(
0375: "Cannot initialize URI with empty parameters.");
0376: }
0377:
0378: // just make a copy of the base if spec is empty
0379: if (p_uriSpec == null || p_uriSpec.trim().length() == 0) {
0380: initialize(p_base);
0381: return;
0382: }
0383:
0384: String uriSpec = p_uriSpec.trim();
0385: int uriSpecLen = uriSpec.length();
0386: int index = 0;
0387:
0388: // Check for scheme, which must be before `/'. Also handle names with
0389: // DOS drive letters ('D:'), so 1-character schemes are not allowed.
0390: int colonIdx = uriSpec.indexOf(':');
0391: int slashIdx = uriSpec.indexOf('/');
0392: if ((colonIdx < 2) || (colonIdx > slashIdx && slashIdx != -1)) {
0393: int fragmentIdx = uriSpec.indexOf('#');
0394: // A standalone base is a valid URI according to spec
0395: if (p_base == null && fragmentIdx != 0) {
0396: throw new MalformedURIException(
0397: "No scheme found in URI.");
0398: }
0399: } else {
0400: initializeScheme(uriSpec);
0401: index = m_scheme.length() + 1;
0402: }
0403:
0404: // two slashes means generic URI syntax, so we get the authority
0405: if (((index + 1) < uriSpecLen)
0406: && (uriSpec.substring(index).startsWith("//"))) {
0407: index += 2;
0408: int startPos = index;
0409:
0410: // get authority - everything up to path, query or fragment
0411: char testChar = '\0';
0412: while (index < uriSpecLen) {
0413: testChar = uriSpec.charAt(index);
0414: if (testChar == '/' || testChar == '?'
0415: || testChar == '#') {
0416: break;
0417: }
0418: index++;
0419: }
0420:
0421: // if we found authority, parse it out, otherwise we set the
0422: // host to empty string
0423: if (index > startPos) {
0424: initializeAuthority(uriSpec.substring(startPos, index));
0425: } else {
0426: m_host = "";
0427: }
0428: }
0429:
0430: initializePath(uriSpec.substring(index));
0431:
0432: // Resolve relative URI to base URI - see RFC 2396 Section 5.2
0433: // In some cases, it might make more sense to throw an exception
0434: // (when scheme is specified is the string spec and the base URI
0435: // is also specified, for example), but we're just following the
0436: // RFC specifications
0437: if (p_base != null) {
0438:
0439: // check to see if this is the current doc - RFC 2396 5.2 #2
0440: // note that this is slightly different from the RFC spec in that
0441: // we don't include the check for query string being null
0442: // - this handles cases where the urispec is just a query
0443: // string or a fragment (e.g. "?y" or "#s") -
0444: // see <http://www.ics.uci.edu/~fielding/url/test1.html> which
0445: // identified this as a bug in the RFC
0446: if (m_path.length() == 0 && m_scheme == null
0447: && m_host == null) {
0448: m_scheme = p_base.getScheme();
0449: m_userinfo = p_base.getUserinfo();
0450: m_host = p_base.getHost();
0451: m_port = p_base.getPort();
0452: m_path = p_base.getPath();
0453:
0454: if (m_queryString == null) {
0455: m_queryString = p_base.getQueryString();
0456: }
0457: return;
0458: }
0459:
0460: // check for scheme - RFC 2396 5.2 #3
0461: // if we found a scheme, it means absolute URI, so we're done
0462: if (m_scheme == null) {
0463: m_scheme = p_base.getScheme();
0464: } else {
0465: return;
0466: }
0467:
0468: // check for authority - RFC 2396 5.2 #4
0469: // if we found a host, then we've got a network path, so we're done
0470: if (m_host == null) {
0471: m_userinfo = p_base.getUserinfo();
0472: m_host = p_base.getHost();
0473: m_port = p_base.getPort();
0474: } else {
0475: return;
0476: }
0477:
0478: // check for absolute path - RFC 2396 5.2 #5
0479: if (m_path.length() > 0 && m_path.startsWith("/")) {
0480: return;
0481: }
0482:
0483: // if we get to this point, we need to resolve relative path
0484: // RFC 2396 5.2 #6
0485: String path = new String();
0486: String basePath = p_base.getPath();
0487:
0488: // 6a - get all but the last segment of the base URI path
0489: if (basePath != null) {
0490: int lastSlash = basePath.lastIndexOf('/');
0491: if (lastSlash != -1) {
0492: path = basePath.substring(0, lastSlash + 1);
0493: }
0494: }
0495:
0496: // 6b - append the relative URI path
0497: path = path.concat(m_path);
0498:
0499: // 6c - remove all "./" where "." is a complete path segment
0500: index = -1;
0501: while ((index = path.indexOf("/./")) != -1) {
0502: path = path.substring(0, index + 1).concat(
0503: path.substring(index + 3));
0504: }
0505:
0506: // 6d - remove "." if path ends with "." as a complete path segment
0507: if (path.endsWith("/.")) {
0508: path = path.substring(0, path.length() - 1);
0509: }
0510:
0511: // 6e - remove all "<segment>/../" where "<segment>" is a complete
0512: // path segment not equal to ".."
0513: index = 1;
0514: int segIndex = -1;
0515: String tempString = null;
0516:
0517: while ((index = path.indexOf("/../", index)) > 0) {
0518: tempString = path.substring(0, path.indexOf("/../"));
0519: segIndex = tempString.lastIndexOf('/');
0520: if (segIndex != -1) {
0521: if (!tempString.substring(segIndex++).equals("..")) {
0522: path = path.substring(0, segIndex).concat(
0523: path.substring(index + 4));
0524: } else
0525: index += 4;
0526: } else
0527: index += 4;
0528: }
0529:
0530: // 6f - remove ending "<segment>/.." where "<segment>" is a
0531: // complete path segment
0532: if (path.endsWith("/..")) {
0533: tempString = path.substring(0, path.length() - 3);
0534: segIndex = tempString.lastIndexOf('/');
0535: if (segIndex != -1) {
0536: path = path.substring(0, segIndex + 1);
0537: }
0538: }
0539: m_path = path;
0540: }
0541: }
0542:
0543: /**
0544: * Initialize the scheme for this URI from a URI string spec.
0545: *
0546: * @param p_uriSpec the URI specification (cannot be null)
0547: *
0548: * @exception MalformedURIException if URI does not have a conformant
0549: * scheme
0550: */
0551: private void initializeScheme(String p_uriSpec)
0552: throws MalformedURIException {
0553: int uriSpecLen = p_uriSpec.length();
0554: int index = 0;
0555: String scheme = null;
0556: char testChar = '\0';
0557:
0558: while (index < uriSpecLen) {
0559: testChar = p_uriSpec.charAt(index);
0560: if (testChar == ':' || testChar == '/' || testChar == '?'
0561: || testChar == '#') {
0562: break;
0563: }
0564: index++;
0565: }
0566: scheme = p_uriSpec.substring(0, index);
0567:
0568: if (scheme.length() == 0) {
0569: throw new MalformedURIException("No scheme found in URI.");
0570: } else {
0571: setScheme(scheme);
0572: }
0573: }
0574:
0575: /**
0576: * Initialize the authority (userinfo, host and port) for this
0577: * URI from a URI string spec.
0578: *
0579: * @param p_uriSpec the URI specification (cannot be null)
0580: *
0581: * @exception MalformedURIException if p_uriSpec violates syntax rules
0582: */
0583: private void initializeAuthority(String p_uriSpec)
0584: throws MalformedURIException {
0585: int index = 0;
0586: int start = 0;
0587: int end = p_uriSpec.length();
0588: char testChar = '\0';
0589: String userinfo = null;
0590:
0591: // userinfo is everything up @
0592: if (p_uriSpec.indexOf('@', start) != -1) {
0593: while (index < end) {
0594: testChar = p_uriSpec.charAt(index);
0595: if (testChar == '@') {
0596: break;
0597: }
0598: index++;
0599: }
0600: userinfo = p_uriSpec.substring(start, index);
0601: index++;
0602: }
0603:
0604: // host is everything up to ':'
0605: String host = null;
0606: start = index;
0607: while (index < end) {
0608: testChar = p_uriSpec.charAt(index);
0609: if (testChar == ':') {
0610: break;
0611: }
0612: index++;
0613: }
0614: host = p_uriSpec.substring(start, index);
0615: int port = -1;
0616: if (host.length() > 0) {
0617: // port
0618: if (testChar == ':') {
0619: index++;
0620: start = index;
0621: while (index < end) {
0622: index++;
0623: }
0624: String portStr = p_uriSpec.substring(start, index);
0625: if (portStr.length() > 0) {
0626: for (int i = 0; i < portStr.length(); i++) {
0627: if (!isDigit(portStr.charAt(i))) {
0628: throw new MalformedURIException(
0629: portStr
0630: + " is invalid. Port should only contain digits!");
0631: }
0632: }
0633: try {
0634: port = Integer.parseInt(portStr);
0635: } catch (NumberFormatException nfe) {
0636: // can't happen
0637: }
0638: }
0639: }
0640: }
0641: setHost(host);
0642: setPort(port);
0643: setUserinfo(userinfo);
0644: }
0645:
0646: /**
0647: * Initialize the path for this URI from a URI string spec.
0648: *
0649: * @param p_uriSpec the URI specification (cannot be null)
0650: *
0651: * @exception MalformedURIException if p_uriSpec violates syntax rules
0652: */
0653: private void initializePath(String p_uriSpec)
0654: throws MalformedURIException {
0655: if (p_uriSpec == null) {
0656: throw new MalformedURIException(
0657: "Cannot initialize path from null string!");
0658: }
0659:
0660: int index = 0;
0661: int start = 0;
0662: int end = p_uriSpec.length();
0663: char testChar = '\0';
0664:
0665: // path - everything up to query string or fragment
0666: while (index < end) {
0667: testChar = p_uriSpec.charAt(index);
0668: if (testChar == '?' || testChar == '#') {
0669: break;
0670: }
0671: // check for valid escape sequence
0672: if (testChar == '%') {
0673: if (index + 2 >= end
0674: || !isHex(p_uriSpec.charAt(index + 1))
0675: || !isHex(p_uriSpec.charAt(index + 2))) {
0676: throw new MalformedURIException(
0677: "Path contains invalid escape sequence!");
0678: }
0679: } else if (!isReservedCharacter(testChar)
0680: && !isUnreservedCharacter(testChar)) {
0681: throw new MalformedURIException(
0682: "Path contains invalid character: " + testChar);
0683: }
0684: index++;
0685: }
0686: m_path = p_uriSpec.substring(start, index);
0687:
0688: // query - starts with ? and up to fragment or end
0689: if (testChar == '?') {
0690: index++;
0691: start = index;
0692: while (index < end) {
0693: testChar = p_uriSpec.charAt(index);
0694: if (testChar == '#') {
0695: break;
0696: }
0697: if (testChar == '%') {
0698: if (index + 2 >= end
0699: || !isHex(p_uriSpec.charAt(index + 1))
0700: || !isHex(p_uriSpec.charAt(index + 2))) {
0701: throw new MalformedURIException(
0702: "Query string contains invalid escape sequence!");
0703: }
0704: } else if (!isReservedCharacter(testChar)
0705: && !isUnreservedCharacter(testChar)) {
0706: throw new MalformedURIException(
0707: "Query string contains invalid character:"
0708: + testChar);
0709: }
0710: index++;
0711: }
0712: m_queryString = p_uriSpec.substring(start, index);
0713: }
0714:
0715: // fragment - starts with #
0716: if (testChar == '#') {
0717: index++;
0718: start = index;
0719: while (index < end) {
0720: testChar = p_uriSpec.charAt(index);
0721:
0722: if (testChar == '%') {
0723: if (index + 2 >= end
0724: || !isHex(p_uriSpec.charAt(index + 1))
0725: || !isHex(p_uriSpec.charAt(index + 2))) {
0726: throw new MalformedURIException(
0727: "Fragment contains invalid escape sequence!");
0728: }
0729: } else if (!isReservedCharacter(testChar)
0730: && !isUnreservedCharacter(testChar)) {
0731: throw new MalformedURIException(
0732: "Fragment contains invalid character:"
0733: + testChar);
0734: }
0735: index++;
0736: }
0737: m_fragment = p_uriSpec.substring(start, index);
0738: }
0739: }
0740:
0741: /**
0742: * Get the scheme for this URI.
0743: *
0744: * @return the scheme for this URI
0745: */
0746: public String getScheme() {
0747: return m_scheme;
0748: }
0749:
0750: /**
0751: * Get the scheme-specific part for this URI (everything following the
0752: * scheme and the first colon). See RFC 2396 Section 5.2 for spec.
0753: *
0754: * @return the scheme-specific part for this URI
0755: */
0756: public String getSchemeSpecificPart() {
0757: StringBuffer schemespec = new StringBuffer();
0758:
0759: if (m_userinfo != null || m_host != null || m_port != -1) {
0760: schemespec.append("//");
0761: }
0762:
0763: if (m_userinfo != null) {
0764: schemespec.append(m_userinfo);
0765: schemespec.append('@');
0766: }
0767:
0768: if (m_host != null) {
0769: schemespec.append(m_host);
0770: }
0771:
0772: if (m_port != -1) {
0773: schemespec.append(':');
0774: schemespec.append(m_port);
0775: }
0776:
0777: if (m_path != null) {
0778: schemespec.append((m_path));
0779: }
0780:
0781: if (m_queryString != null) {
0782: schemespec.append('?');
0783: schemespec.append(m_queryString);
0784: }
0785:
0786: if (m_fragment != null) {
0787: schemespec.append('#');
0788: schemespec.append(m_fragment);
0789: }
0790:
0791: return schemespec.toString();
0792: }
0793:
0794: /**
0795: * Get the userinfo for this URI.
0796: *
0797: * @return the userinfo for this URI (null if not specified).
0798: */
0799: public String getUserinfo() {
0800: return m_userinfo;
0801: }
0802:
0803: /**
0804: * Get the host for this URI.
0805: *
0806: * @return the host for this URI (null if not specified).
0807: */
0808: public String getHost() {
0809: return m_host;
0810: }
0811:
0812: /**
0813: * Get the port for this URI.
0814: *
0815: * @return the port for this URI (-1 if not specified).
0816: */
0817: public int getPort() {
0818: return m_port;
0819: }
0820:
0821: /**
0822: * Get the path for this URI (optionally with the query string and
0823: * fragment).
0824: *
0825: * @param p_includeQueryString if true (and query string is not null),
0826: * then a "?" followed by the query string
0827: * will be appended
0828: * @param p_includeFragment if true (and fragment is not null),
0829: * then a "#" followed by the fragment
0830: * will be appended
0831: *
0832: * @return the path for this URI possibly including the query string
0833: * and fragment
0834: */
0835: public String getPath(boolean p_includeQueryString,
0836: boolean p_includeFragment) {
0837: StringBuffer pathString = new StringBuffer(m_path);
0838:
0839: if (p_includeQueryString && m_queryString != null) {
0840: pathString.append('?');
0841: pathString.append(m_queryString);
0842: }
0843:
0844: if (p_includeFragment && m_fragment != null) {
0845: pathString.append('#');
0846: pathString.append(m_fragment);
0847: }
0848: return pathString.toString();
0849: }
0850:
0851: /**
0852: * Get the path for this URI. Note that the value returned is the path
0853: * only and does not include the query string or fragment.
0854: *
0855: * @return the path for this URI.
0856: */
0857: public String getPath() {
0858: return m_path;
0859: }
0860:
0861: /**
0862: * Get the query string for this URI.
0863: *
0864: * @return the query string for this URI. Null is returned if there
0865: * was no "?" in the URI spec, empty string if there was a
0866: * "?" but no query string following it.
0867: */
0868: public String getQueryString() {
0869: return m_queryString;
0870: }
0871:
0872: /**
0873: * Get the fragment for this URI.
0874: *
0875: * @return the fragment for this URI. Null is returned if there
0876: * was no "#" in the URI spec, empty string if there was a
0877: * "#" but no fragment following it.
0878: */
0879: public String getFragment() {
0880: return m_fragment;
0881: }
0882:
0883: /**
0884: * Set the scheme for this URI. The scheme is converted to lowercase
0885: * before it is set.
0886: *
0887: * @param p_scheme the scheme for this URI (cannot be null)
0888: *
0889: * @exception MalformedURIException if p_scheme is not a conformant
0890: * scheme name
0891: */
0892: public void setScheme(String p_scheme) throws MalformedURIException {
0893: if (p_scheme == null) {
0894: throw new MalformedURIException(
0895: "Cannot set scheme from null string!");
0896: }
0897: if (!isConformantSchemeName(p_scheme)) {
0898: throw new MalformedURIException(
0899: "The scheme is not conformant.");
0900: }
0901:
0902: m_scheme = p_scheme.toLowerCase();
0903: }
0904:
0905: /**
0906: * Set the userinfo for this URI. If a non-null value is passed in and
0907: * the host value is null, then an exception is thrown.
0908: *
0909: * @param p_userinfo the userinfo for this URI
0910: *
0911: * @exception MalformedURIException if p_userinfo contains invalid
0912: * characters
0913: */
0914: public void setUserinfo(String p_userinfo)
0915: throws MalformedURIException {
0916: if (p_userinfo == null) {
0917: m_userinfo = null;
0918: } else {
0919: if (m_host == null) {
0920: throw new MalformedURIException(
0921: "Userinfo cannot be set when host is null!");
0922: }
0923:
0924: // userinfo can contain alphanumerics, mark characters, escaped
0925: // and ';',':','&','=','+','$',','
0926: int index = 0;
0927: int end = p_userinfo.length();
0928: char testChar = '\0';
0929: while (index < end) {
0930: testChar = p_userinfo.charAt(index);
0931: if (testChar == '%') {
0932: if (index + 2 >= end
0933: || !isHex(p_userinfo.charAt(index + 1))
0934: || !isHex(p_userinfo.charAt(index + 2))) {
0935: throw new MalformedURIException(
0936: "Userinfo contains invalid escape sequence!");
0937: }
0938: } else if (!isUnreservedCharacter(testChar)
0939: && USERINFO_CHARACTERS.indexOf(testChar) == -1) {
0940: throw new MalformedURIException(
0941: "Userinfo contains invalid character:"
0942: + testChar);
0943: }
0944: index++;
0945: }
0946: }
0947: m_userinfo = p_userinfo;
0948: }
0949:
0950: /**
0951: * Set the host for this URI. If null is passed in, the userinfo
0952: * field is also set to null and the port is set to -1.
0953: *
0954: * @param p_host the host for this URI
0955: *
0956: * @exception MalformedURIException if p_host is not a valid IP
0957: * address or DNS hostname.
0958: */
0959: public void setHost(String p_host) throws MalformedURIException {
0960: if (p_host == null || p_host.trim().length() == 0) {
0961: m_host = p_host;
0962: m_userinfo = null;
0963: m_port = -1;
0964: } else if (!isWellFormedAddress(p_host)) {
0965: throw new MalformedURIException(
0966: "Host is not a well formed address!");
0967: }
0968: m_host = p_host;
0969: }
0970:
0971: /**
0972: * Set the port for this URI. -1 is used to indicate that the port is
0973: * not specified, otherwise valid port numbers are between 0 and 65535.
0974: * If a valid port number is passed in and the host field is null,
0975: * an exception is thrown.
0976: *
0977: * @param p_port the port number for this URI
0978: *
0979: * @exception MalformedURIException if p_port is not -1 and not a
0980: * valid port number
0981: */
0982: public void setPort(int p_port) throws MalformedURIException {
0983: if (p_port >= 0 && p_port <= 65535) {
0984: if (m_host == null) {
0985: throw new MalformedURIException(
0986: "Port cannot be set when host is null!");
0987: }
0988: } else if (p_port != -1) {
0989: throw new MalformedURIException("Invalid port number!");
0990: }
0991: m_port = p_port;
0992: }
0993:
0994: /**
0995: * Set the path for this URI. If the supplied path is null, then the
0996: * query string and fragment are set to null as well. If the supplied
0997: * path includes a query string and/or fragment, these fields will be
0998: * parsed and set as well. Note that, for URIs following the "generic
0999: * URI" syntax, the path specified should start with a slash.
1000: * For URIs that do not follow the generic URI syntax, this method
1001: * sets the scheme-specific part.
1002: *
1003: * @param p_path the path for this URI (may be null)
1004: *
1005: * @exception MalformedURIException if p_path contains invalid
1006: * characters
1007: */
1008: public void setPath(String p_path) throws MalformedURIException {
1009: if (p_path == null) {
1010: m_path = null;
1011: m_queryString = null;
1012: m_fragment = null;
1013: } else {
1014: initializePath(p_path);
1015: }
1016: }
1017:
1018: /**
1019: * Append to the end of the path of this URI. If the current path does
1020: * not end in a slash and the path to be appended does not begin with
1021: * a slash, a slash will be appended to the current path before the
1022: * new segment is added. Also, if the current path ends in a slash
1023: * and the new segment begins with a slash, the extra slash will be
1024: * removed before the new segment is appended.
1025: *
1026: * @param p_addToPath the new segment to be added to the current path
1027: *
1028: * @exception MalformedURIException if p_addToPath contains syntax
1029: * errors
1030: */
1031: public void appendPath(String p_addToPath)
1032: throws MalformedURIException {
1033: if (p_addToPath == null || p_addToPath.trim().length() == 0) {
1034: return;
1035: }
1036:
1037: if (!isURIString(p_addToPath)) {
1038: throw new MalformedURIException(
1039: "Path contains invalid character!");
1040: }
1041:
1042: if (m_path == null || m_path.trim().length() == 0) {
1043: if (p_addToPath.startsWith("/")) {
1044: m_path = p_addToPath;
1045: } else {
1046: m_path = "/" + p_addToPath;
1047: }
1048: } else if (m_path.endsWith("/")) {
1049: if (p_addToPath.startsWith("/")) {
1050: m_path = m_path.concat(p_addToPath.substring(1));
1051: } else {
1052: m_path = m_path.concat(p_addToPath);
1053: }
1054: } else {
1055: if (p_addToPath.startsWith("/")) {
1056: m_path = m_path.concat(p_addToPath);
1057: } else {
1058: m_path = m_path.concat("/" + p_addToPath);
1059: }
1060: }
1061: }
1062:
1063: /**
1064: * Set the query string for this URI. A non-null value is valid only
1065: * if this is an URI conforming to the generic URI syntax and
1066: * the path value is not null.
1067: *
1068: * @param p_queryString the query string for this URI
1069: *
1070: * @exception MalformedURIException if p_queryString is not null and this
1071: * URI does not conform to the generic
1072: * URI syntax or if the path is null
1073: */
1074: public void setQueryString(String p_queryString)
1075: throws MalformedURIException {
1076: if (p_queryString == null) {
1077: m_queryString = null;
1078: } else if (!isGenericURI()) {
1079: throw new MalformedURIException(
1080: "Query string can only be set for a generic URI!");
1081: } else if (getPath() == null) {
1082: throw new MalformedURIException(
1083: "Query string cannot be set when path is null!");
1084: } else if (!isURIString(p_queryString)) {
1085: throw new MalformedURIException(
1086: "Query string contains invalid character!");
1087: } else {
1088: m_queryString = p_queryString;
1089: }
1090: }
1091:
1092: /**
1093: * Set the fragment for this URI. A non-null value is valid only
1094: * if this is a URI conforming to the generic URI syntax and
1095: * the path value is not null.
1096: *
1097: * @param p_fragment the fragment for this URI
1098: *
1099: * @exception MalformedURIException if p_fragment is not null and this
1100: * URI does not conform to the generic
1101: * URI syntax or if the path is null
1102: */
1103: public void setFragment(String p_fragment)
1104: throws MalformedURIException {
1105: if (p_fragment == null) {
1106: m_fragment = null;
1107: } else if (!isGenericURI()) {
1108: throw new MalformedURIException(
1109: "Fragment can only be set for a generic URI!");
1110: } else if (getPath() == null) {
1111: throw new MalformedURIException(
1112: "Fragment cannot be set when path is null!");
1113: } else if (!isURIString(p_fragment)) {
1114: throw new MalformedURIException(
1115: "Fragment contains invalid character!");
1116: } else {
1117: m_fragment = p_fragment;
1118: }
1119: }
1120:
1121: /**
1122: * Determines if the passed-in Object is equivalent to this URI.
1123: *
1124: * @param p_test the Object to test for equality.
1125: *
1126: * @return true if p_test is a URI with all values equal to this
1127: * URI, false otherwise
1128: */
1129: public boolean equals(Object p_test) {
1130: if (p_test instanceof JaxmURI) {
1131: JaxmURI testURI = (JaxmURI) p_test;
1132: if (((m_scheme == null && testURI.m_scheme == null) || (m_scheme != null
1133: && testURI.m_scheme != null && m_scheme
1134: .equals(testURI.m_scheme)))
1135: && ((m_userinfo == null && testURI.m_userinfo == null) || (m_userinfo != null
1136: && testURI.m_userinfo != null && m_userinfo
1137: .equals(testURI.m_userinfo)))
1138: && ((m_host == null && testURI.m_host == null) || (m_host != null
1139: && testURI.m_host != null && m_host
1140: .equals(testURI.m_host)))
1141: && m_port == testURI.m_port
1142: && ((m_path == null && testURI.m_path == null) || (m_path != null
1143: && testURI.m_path != null && m_path
1144: .equals(testURI.m_path)))
1145: && ((m_queryString == null && testURI.m_queryString == null) || (m_queryString != null
1146: && testURI.m_queryString != null && m_queryString
1147: .equals(testURI.m_queryString)))
1148: && ((m_fragment == null && testURI.m_fragment == null) || (m_fragment != null
1149: && testURI.m_fragment != null && m_fragment
1150: .equals(testURI.m_fragment)))) {
1151: return true;
1152: }
1153: }
1154: return false;
1155: }
1156:
1157: /**
1158: * Get the URI as a string specification. See RFC 2396 Section 5.2.
1159: *
1160: * @return the URI string specification
1161: */
1162: public String toString() {
1163: StringBuffer uriSpecString = new StringBuffer();
1164:
1165: if (m_scheme != null) {
1166: uriSpecString.append(m_scheme);
1167: uriSpecString.append(':');
1168: }
1169: uriSpecString.append(getSchemeSpecificPart());
1170: return uriSpecString.toString();
1171: }
1172:
1173: /**
1174: * Get the indicator as to whether this URI uses the "generic URI"
1175: * syntax.
1176: *
1177: * @return true if this URI uses the "generic URI" syntax, false
1178: * otherwise
1179: */
1180: public boolean isGenericURI() {
1181: // presence of the host (whether valid or empty) means
1182: // double-slashes which means generic uri
1183: return (m_host != null);
1184: }
1185:
1186: /**
1187: * Determine whether a scheme conforms to the rules for a scheme name.
1188: * A scheme is conformant if it starts with an alphanumeric, and
1189: * contains only alphanumerics, '+','-' and '.'.
1190: *
1191: * @return true if the scheme is conformant, false otherwise
1192: */
1193: public static boolean isConformantSchemeName(String p_scheme) {
1194: if (p_scheme == null || p_scheme.trim().length() == 0) {
1195: return false;
1196: }
1197:
1198: if (!isAlpha(p_scheme.charAt(0))) {
1199: return false;
1200: }
1201:
1202: char testChar;
1203: for (int i = 1; i < p_scheme.length(); i++) {
1204: testChar = p_scheme.charAt(i);
1205: if (!isAlphanum(testChar)
1206: && SCHEME_CHARACTERS.indexOf(testChar) == -1) {
1207: return false;
1208: }
1209: }
1210:
1211: return true;
1212: }
1213:
1214: /**
1215: * Determine whether a string is syntactically capable of representing
1216: * a valid IPv4 address or the domain name of a network host. A valid
1217: * IPv4 address consists of four decimal digit groups separated by a
1218: * '.'. A hostname consists of domain labels (each of which must
1219: * begin and end with an alphanumeric but may contain '-') separated
1220: & by a '.'. See RFC 2396 Section 3.2.2.
1221: *
1222: * @return true if the string is a syntactically valid IPv4 address
1223: * or hostname
1224: */
1225: public static boolean isWellFormedAddress(String p_address) {
1226: if (p_address == null) {
1227: return false;
1228: }
1229:
1230: String address = p_address.trim();
1231: int addrLength = address.length();
1232: if (addrLength == 0 || addrLength > 255) {
1233: return false;
1234: }
1235:
1236: if (address.startsWith(".") || address.startsWith("-")) {
1237: return false;
1238: }
1239:
1240: // rightmost domain label starting with digit indicates IP address
1241: // since top level domain label can only start with an alpha
1242: // see RFC 2396 Section 3.2.2
1243: int index = address.lastIndexOf('.');
1244: if (address.endsWith(".")) {
1245: index = address.substring(0, index).lastIndexOf('.');
1246: }
1247:
1248: if (index + 1 < addrLength
1249: && isDigit(p_address.charAt(index + 1))) {
1250: char testChar;
1251: int numDots = 0;
1252:
1253: // make sure that 1) we see only digits and dot separators, 2) that
1254: // any dot separator is preceded and followed by a digit and
1255: // 3) that we find 3 dots
1256: for (int i = 0; i < addrLength; i++) {
1257: testChar = address.charAt(i);
1258: if (testChar == '.') {
1259: if (!isDigit(address.charAt(i - 1))
1260: || (i + 1 < addrLength && !isDigit(address
1261: .charAt(i + 1)))) {
1262: return false;
1263: }
1264: numDots++;
1265: } else if (!isDigit(testChar)) {
1266: return false;
1267: }
1268: }
1269: if (numDots != 3) {
1270: return false;
1271: }
1272: } else {
1273: // domain labels can contain alphanumerics and '-"
1274: // but must start and end with an alphanumeric
1275: char testChar;
1276:
1277: for (int i = 0; i < addrLength; i++) {
1278: testChar = address.charAt(i);
1279: if (testChar == '.') {
1280: if (!isAlphanum(address.charAt(i - 1))) {
1281: return false;
1282: }
1283: if (i + 1 < addrLength
1284: && !isAlphanum(address.charAt(i + 1))) {
1285: return false;
1286: }
1287: } else if (!isAlphanum(testChar) && testChar != '-') {
1288: return false;
1289: }
1290: }
1291: }
1292: return true;
1293: }
1294:
1295: /**
1296: * Determine whether a char is a digit.
1297: *
1298: * @return true if the char is betweeen '0' and '9', false otherwise
1299: */
1300: private static boolean isDigit(char p_char) {
1301: return p_char >= '0' && p_char <= '9';
1302: }
1303:
1304: /**
1305: * Determine whether a character is a hexadecimal character.
1306: *
1307: * @return true if the char is betweeen '0' and '9', 'a' and 'f'
1308: * or 'A' and 'F', false otherwise
1309: */
1310: private static boolean isHex(char p_char) {
1311: return (isDigit(p_char) || (p_char >= 'a' && p_char <= 'f') || (p_char >= 'A' && p_char <= 'F'));
1312: }
1313:
1314: /**
1315: * Determine whether a char is an alphabetic character: a-z or A-Z
1316: *
1317: * @return true if the char is alphabetic, false otherwise
1318: */
1319: private static boolean isAlpha(char p_char) {
1320: return ((p_char >= 'a' && p_char <= 'z') || (p_char >= 'A' && p_char <= 'Z'));
1321: }
1322:
1323: /**
1324: * Determine whether a char is an alphanumeric: 0-9, a-z or A-Z
1325: *
1326: * @return true if the char is alphanumeric, false otherwise
1327: */
1328: private static boolean isAlphanum(char p_char) {
1329: return (isAlpha(p_char) || isDigit(p_char));
1330: }
1331:
1332: /**
1333: * Determine whether a character is a reserved character:
1334: * ';', '/', '?', ':', '@', '&', '=', '+', '$' or ','
1335: *
1336: * @return true if the string contains any reserved characters
1337: */
1338: private static boolean isReservedCharacter(char p_char) {
1339: return RESERVED_CHARACTERS.indexOf(p_char) != -1;
1340: }
1341:
1342: /**
1343: * Determine whether a char is an unreserved character.
1344: *
1345: * @return true if the char is unreserved, false otherwise
1346: */
1347: private static boolean isUnreservedCharacter(char p_char) {
1348: return (isAlphanum(p_char) || MARK_CHARACTERS.indexOf(p_char) != -1);
1349: }
1350:
1351: /**
1352: * Determine whether a given string contains only URI characters (also
1353: * called "uric" in RFC 2396). uric consist of all reserved
1354: * characters, unreserved characters and escaped characters.
1355: *
1356: * @return true if the string is comprised of uric, false otherwise
1357: */
1358: private static boolean isURIString(String p_uric) {
1359: if (p_uric == null) {
1360: return false;
1361: }
1362: int end = p_uric.length();
1363: char testChar = '\0';
1364: for (int i = 0; i < end; i++) {
1365: testChar = p_uric.charAt(i);
1366: if (testChar == '%') {
1367: if (i + 2 >= end || !isHex(p_uric.charAt(i + 1))
1368: || !isHex(p_uric.charAt(i + 2))) {
1369: return false;
1370: } else {
1371: i += 2;
1372: continue;
1373: }
1374: }
1375: if (isReservedCharacter(testChar)
1376: || isUnreservedCharacter(testChar)) {
1377: continue;
1378: } else {
1379: return false;
1380: }
1381: }
1382: return true;
1383: }
1384: }
|