0001: /*
0002: * Licensed to the Apache Software Foundation (ASF) under one
0003: * or more contributor license agreements. See the NOTICE file
0004: * distributed with this work for additional information
0005: * regarding copyright ownership. The ASF licenses this file
0006: * to you under the Apache License, Version 2.0 (the
0007: * "License"); you may not use this file except in compliance
0008: * with the License. You may obtain a copy of the License at
0009: *
0010: * http://www.apache.org/licenses/LICENSE-2.0
0011: *
0012: * Unless required by applicable law or agreed to in writing,
0013: * software distributed under the License is distributed on an
0014: * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
0015: * KIND, either express or implied. See the License for the
0016: * specific language governing permissions and limitations
0017: * under the License.
0018: */
0019:
0020: package org.apache.axis2.databinding.types;
0021:
0022: import java.io.IOException;
0023: import java.io.Serializable;
0024:
0025: /**
0026: * ******************************************************************* <i>Axis Note: This class was
0027: * 'borrowed' from Xerces 2.0.2</i>
0028: * <p/>
0029: * A class to represent a Uniform Resource Identifier (URI). This class is designed to handle the
0030: * parsing of URIs and provide access to the various components (scheme, host, port, userinfo,
0031: * path, query string and fragment) that may constitute a URI.
0032: * <p/>
0033: * Parsing of a URI specification is done according to the URI syntax described in <a
0034: * href="http://www.ietf.org/rfc/rfc2396.txt?number=2396">RFC 2396</a>, and amended by <a
0035: * href="http://www.ietf.org/rfc/rfc2732.txt?number=2732">RFC 2732</a>.
0036: * <p/>
0037: * Every absolute URI consists of a scheme, followed by a colon (':'), followed by a
0038: * scheme-specific part. For URIs that follow the "generic URI" syntax, the scheme-specific part
0039: * begins with two slashes ("//") and may be followed by an authority segment (comprised of user
0040: * information, host, and port), path segment, query segment and fragment. Note that RFC 2396 no
0041: * longer specifies the use of the parameters segment and excludes the "user:password" syntax as
0042: * part of the authority segment. If "user:password" appears in a URI, the entire user/password
0043: * string is stored as userinfo.
0044: * <p/>
0045: * For URIs that do not follow the "generic URI" syntax (e.g. mailto), the entire scheme-specific
0046: * part is treated as the "path" portion of the URI.
0047: * <p/>
0048: * Note that, unlike the java.net.URL class, this class does not provide any built-in network
0049: * access functionality nor does it provide any scheme-specific functionality (for example, it does
0050: * not know a default port for a specific scheme). Rather, it only knows the grammar and basic set
0051: * of operations that can be applied to a URI.
0052: * <p/>
0053: * ********************************************************************
0054: */
0055: public class URI implements Serializable {
0056:
0057: private static final long serialVersionUID = 2172306044361227627L;
0058:
0059: /**
0060: * **************************************************************** MalformedURIExceptions are
0061: * thrown in the process of building a URI or setting fields on a URI when an operation would
0062: * result in an invalid URI specification.
0063: * <p/>
0064: * ******************************************************************
0065: */
0066: public static class MalformedURIException extends IOException {
0067:
0068: private static final long serialVersionUID = -8488692760975768757L;
0069:
0070: /**
0071: * *************************************************************** Constructs a
0072: * <code>MalformedURIException</code> with no specified detail message.
0073: * ****************************************************************
0074: */
0075: public MalformedURIException() {
0076: super ();
0077: }
0078:
0079: /**
0080: * ************************************************************** Constructs a
0081: * <code>MalformedURIException</code> with the specified detail message.
0082: *
0083: * @param p_msg the detail message. ****************************************************************
0084: */
0085: public MalformedURIException(String p_msg) {
0086: super (p_msg);
0087: }
0088: }
0089:
0090: private static final byte[] fgLookupTable = new byte[128];
0091:
0092: /**
0093: * Character Classes
0094: */
0095:
0096: /** reserved characters ;/?:@&=+$,[] */
0097: //RFC 2732 added '[' and ']' as reserved characters
0098: private static final int RESERVED_CHARACTERS = 0x01;
0099:
0100: /**
0101: * URI punctuation mark characters: -_.!~*'() - these, combined with alphanumerics, constitute the
0102: * "unreserved" characters
0103: */
0104: private static final int MARK_CHARACTERS = 0x02;
0105:
0106: /** scheme can be composed of alphanumerics and these characters: +-. */
0107: private static final int SCHEME_CHARACTERS = 0x04;
0108:
0109: /** userinfo can be composed of unreserved, escaped and these characters: ;:&=+$, */
0110: private static final int USERINFO_CHARACTERS = 0x08;
0111:
0112: /** ASCII letter characters */
0113: private static final int ASCII_ALPHA_CHARACTERS = 0x10;
0114:
0115: /** ASCII digit characters */
0116: private static final int ASCII_DIGIT_CHARACTERS = 0x20;
0117:
0118: /** ASCII hex characters */
0119: private static final int ASCII_HEX_CHARACTERS = 0x40;
0120:
0121: /** Path characters */
0122: private static final int PATH_CHARACTERS = 0x80;
0123:
0124: /** Mask for alpha-numeric characters */
0125: private static final int MASK_ALPHA_NUMERIC = ASCII_ALPHA_CHARACTERS
0126: | ASCII_DIGIT_CHARACTERS;
0127:
0128: /** Mask for unreserved characters */
0129: private static final int MASK_UNRESERVED_MASK = MASK_ALPHA_NUMERIC
0130: | MARK_CHARACTERS;
0131:
0132: /** Mask for URI allowable characters except for % */
0133: private static final int MASK_URI_CHARACTER = MASK_UNRESERVED_MASK
0134: | RESERVED_CHARACTERS;
0135:
0136: /** Mask for scheme characters */
0137: private static final int MASK_SCHEME_CHARACTER = MASK_ALPHA_NUMERIC
0138: | SCHEME_CHARACTERS;
0139:
0140: /** Mask for userinfo characters */
0141: private static final int MASK_USERINFO_CHARACTER = MASK_UNRESERVED_MASK
0142: | USERINFO_CHARACTERS;
0143:
0144: /** Mask for path characters */
0145: private static final int MASK_PATH_CHARACTER = MASK_UNRESERVED_MASK
0146: | PATH_CHARACTERS;
0147:
0148: static {
0149: // Add ASCII Digits and ASCII Hex Numbers
0150: for (int i = '0'; i <= '9'; ++i) {
0151: fgLookupTable[i] |= ASCII_DIGIT_CHARACTERS
0152: | ASCII_HEX_CHARACTERS;
0153: }
0154:
0155: // Add ASCII Letters and ASCII Hex Numbers
0156: for (int i = 'A'; i <= 'F'; ++i) {
0157: fgLookupTable[i] |= ASCII_ALPHA_CHARACTERS
0158: | ASCII_HEX_CHARACTERS;
0159: fgLookupTable[i + 0x00000020] |= ASCII_ALPHA_CHARACTERS
0160: | ASCII_HEX_CHARACTERS;
0161: }
0162:
0163: // Add ASCII Letters
0164: for (int i = 'G'; i <= 'Z'; ++i) {
0165: fgLookupTable[i] |= ASCII_ALPHA_CHARACTERS;
0166: fgLookupTable[i + 0x00000020] |= ASCII_ALPHA_CHARACTERS;
0167: }
0168:
0169: // Add Reserved Characters
0170: fgLookupTable[';'] |= RESERVED_CHARACTERS;
0171: fgLookupTable['/'] |= RESERVED_CHARACTERS;
0172: fgLookupTable['?'] |= RESERVED_CHARACTERS;
0173: fgLookupTable[':'] |= RESERVED_CHARACTERS;
0174: fgLookupTable['@'] |= RESERVED_CHARACTERS;
0175: fgLookupTable['&'] |= RESERVED_CHARACTERS;
0176: fgLookupTable['='] |= RESERVED_CHARACTERS;
0177: fgLookupTable['+'] |= RESERVED_CHARACTERS;
0178: fgLookupTable['$'] |= RESERVED_CHARACTERS;
0179: fgLookupTable[','] |= RESERVED_CHARACTERS;
0180: fgLookupTable['['] |= RESERVED_CHARACTERS;
0181: fgLookupTable[']'] |= RESERVED_CHARACTERS;
0182:
0183: // Add Mark Characters
0184: fgLookupTable['-'] |= MARK_CHARACTERS;
0185: fgLookupTable['_'] |= MARK_CHARACTERS;
0186: fgLookupTable['.'] |= MARK_CHARACTERS;
0187: fgLookupTable['!'] |= MARK_CHARACTERS;
0188: fgLookupTable['~'] |= MARK_CHARACTERS;
0189: fgLookupTable['*'] |= MARK_CHARACTERS;
0190: fgLookupTable['\''] |= MARK_CHARACTERS;
0191: fgLookupTable['('] |= MARK_CHARACTERS;
0192: fgLookupTable[')'] |= MARK_CHARACTERS;
0193:
0194: // Add Scheme Characters
0195: fgLookupTable['+'] |= SCHEME_CHARACTERS;
0196: fgLookupTable['-'] |= SCHEME_CHARACTERS;
0197: fgLookupTable['.'] |= SCHEME_CHARACTERS;
0198:
0199: // Add Userinfo Characters
0200: fgLookupTable[';'] |= USERINFO_CHARACTERS;
0201: fgLookupTable[':'] |= USERINFO_CHARACTERS;
0202: fgLookupTable['&'] |= USERINFO_CHARACTERS;
0203: fgLookupTable['='] |= USERINFO_CHARACTERS;
0204: fgLookupTable['+'] |= USERINFO_CHARACTERS;
0205: fgLookupTable['$'] |= USERINFO_CHARACTERS;
0206: fgLookupTable[','] |= USERINFO_CHARACTERS;
0207:
0208: // Add Path Characters
0209: fgLookupTable[';'] |= PATH_CHARACTERS;
0210: fgLookupTable['/'] |= PATH_CHARACTERS;
0211: fgLookupTable[':'] |= PATH_CHARACTERS;
0212: fgLookupTable['@'] |= PATH_CHARACTERS;
0213: fgLookupTable['&'] |= PATH_CHARACTERS;
0214: fgLookupTable['='] |= PATH_CHARACTERS;
0215: fgLookupTable['+'] |= PATH_CHARACTERS;
0216: fgLookupTable['$'] |= PATH_CHARACTERS;
0217: fgLookupTable[','] |= PATH_CHARACTERS;
0218: }
0219:
0220: /** Stores the scheme (usually the protocol) for this URI. */
0221: private String m_scheme = null;
0222:
0223: /** If specified, stores the userinfo for this URI; otherwise null */
0224: private String m_userinfo = null;
0225:
0226: /** If specified, stores the host for this URI; otherwise null */
0227: private String m_host = null;
0228:
0229: /** If specified, stores the port for this URI; otherwise -1 */
0230: private int m_port = -1;
0231:
0232: /** If specified, stores the registry based authority for this URI; otherwise -1 */
0233: private String m_regAuthority = null;
0234:
0235: /** If specified, stores the path for this URI; otherwise null */
0236: private String m_path = null;
0237:
0238: /** If specified, stores the query string for this URI; otherwise null. */
0239: private String m_queryString = null;
0240:
0241: /** If specified, stores the fragment for this URI; otherwise null */
0242: private String m_fragment;
0243:
0244: /** Construct a new and uninitialized URI. */
0245: public URI() {
0246: }
0247:
0248: /**
0249: * Construct a new URI from another URI. All fields for this URI are set equal to the fields of
0250: * the URI passed in.
0251: *
0252: * @param p_other the URI to copy (cannot be null)
0253: */
0254: public URI(URI p_other) {
0255: initialize(p_other);
0256: }
0257:
0258: /**
0259: * Construct a new URI from a URI specification string. If the specification follows the "generic
0260: * URI" syntax, (two slashes following the first colon), the specification will be parsed
0261: * accordingly - setting the scheme, userinfo, host,port, path, query string and fragment fields
0262: * as necessary. If the specification does not follow the "generic URI" syntax, the specification
0263: * is parsed into a scheme and scheme-specific part (stored as the path) only.
0264: *
0265: * @param p_uriSpec the URI specification string (cannot be null or empty)
0266: * @throws MalformedURIException if p_uriSpec violates any syntax rules
0267: */
0268: public URI(String p_uriSpec) throws MalformedURIException {
0269: this ((URI) null, p_uriSpec);
0270: }
0271:
0272: /**
0273: * Construct a new URI from a base URI and a URI specification string. The URI specification
0274: * string may be a relative URI.
0275: *
0276: * @param p_base the base URI (cannot be null if p_uriSpec is null or empty)
0277: * @param p_uriSpec the URI specification string (cannot be null or empty if p_base is null)
0278: * @throws MalformedURIException if p_uriSpec violates any syntax rules
0279: */
0280: public URI(URI p_base, String p_uriSpec)
0281: throws MalformedURIException {
0282: initialize(p_base, p_uriSpec);
0283: }
0284:
0285: /**
0286: * Construct a new URI that does not follow the generic URI syntax. Only the scheme and
0287: * scheme-specific part (stored as the path) are initialized.
0288: *
0289: * @param p_scheme the URI scheme (cannot be null or empty)
0290: * @param p_schemeSpecificPart the scheme-specific part (cannot be null or empty)
0291: * @throws MalformedURIException if p_scheme violates any syntax rules
0292: */
0293: public URI(String p_scheme, String p_schemeSpecificPart)
0294: throws MalformedURIException {
0295: if (p_scheme == null || p_scheme.trim().length() == 0) {
0296: throw new MalformedURIException(
0297: "Cannot construct URI with null/empty scheme!");
0298: }
0299: if (p_schemeSpecificPart == null
0300: || p_schemeSpecificPart.trim().length() == 0) {
0301: throw new MalformedURIException(
0302: "Cannot construct URI with null/empty scheme-specific part!");
0303: }
0304: setScheme(p_scheme);
0305: setPath(p_schemeSpecificPart);
0306: }
0307:
0308: /**
0309: * Construct a new URI that follows the generic URI syntax from its component parts. Each
0310: * component is validated for syntax and some basic semantic checks are performed as well. See
0311: * the individual setter methods for specifics.
0312: *
0313: * @param p_scheme the URI scheme (cannot be null or empty)
0314: * @param p_host the hostname, IPv4 address or IPv6 reference for the URI
0315: * @param p_path the URI path - if the path contains '?' or '#', then the query string
0316: * and/or fragment will be set from the path; however, if the query and
0317: * fragment are specified both in the path and as separate parameters, an
0318: * exception is thrown
0319: * @param p_queryString the URI query string (cannot be specified if path is null)
0320: * @param p_fragment the URI fragment (cannot be specified if path is null)
0321: * @throws MalformedURIException if any of the parameters violates syntax rules or semantic rules
0322: */
0323: public URI(String p_scheme, String p_host, String p_path,
0324: String p_queryString, String p_fragment)
0325: throws MalformedURIException {
0326: this (p_scheme, null, p_host, -1, p_path, p_queryString,
0327: p_fragment);
0328: }
0329:
0330: /**
0331: * Construct a new URI that follows the generic URI syntax from its component parts. Each
0332: * component is validated for syntax and some basic semantic checks are performed as well. See
0333: * the individual setter methods for specifics.
0334: *
0335: * @param p_scheme the URI scheme (cannot be null or empty)
0336: * @param p_userinfo the URI userinfo (cannot be specified if host is null)
0337: * @param p_host the hostname, IPv4 address or IPv6 reference for the URI
0338: * @param p_port the URI port (may be -1 for "unspecified"; cannot be specified if host is
0339: * null)
0340: * @param p_path the URI path - if the path contains '?' or '#', then the query string
0341: * and/or fragment will be set from the path; however, if the query and
0342: * fragment are specified both in the path and as separate parameters, an
0343: * exception is thrown
0344: * @param p_queryString the URI query string (cannot be specified if path is null)
0345: * @param p_fragment the URI fragment (cannot be specified if path is null)
0346: * @throws MalformedURIException if any of the parameters violates syntax rules or semantic rules
0347: */
0348: public URI(String p_scheme, String p_userinfo, String p_host,
0349: int p_port, String p_path, String p_queryString,
0350: String p_fragment) throws MalformedURIException {
0351: if (p_scheme == null || p_scheme.trim().length() == 0) {
0352: throw new MalformedURIException("Scheme is required!");
0353: }
0354:
0355: if (p_host == null) {
0356: if (p_userinfo != null) {
0357: throw new MalformedURIException(
0358: "Userinfo may not be specified if host is not specified!");
0359: }
0360: if (p_port != -1) {
0361: throw new MalformedURIException(
0362: "Port may not be specified if host is not specified!");
0363: }
0364: }
0365:
0366: if (p_path != null) {
0367: if (p_path.indexOf('?') != -1 && p_queryString != null) {
0368: throw new MalformedURIException(
0369: "Query string cannot be specified in path and query string!");
0370: }
0371:
0372: if (p_path.indexOf('#') != -1 && p_fragment != null) {
0373: throw new MalformedURIException(
0374: "Fragment cannot be specified in both the path and fragment!");
0375: }
0376: }
0377:
0378: setScheme(p_scheme);
0379: setHost(p_host);
0380: setPort(p_port);
0381: setUserinfo(p_userinfo);
0382: setPath(p_path);
0383: setQueryString(p_queryString);
0384: setFragment(p_fragment);
0385: }
0386:
0387: /**
0388: * Initialize all fields of this URI from another URI.
0389: *
0390: * @param p_other the URI to copy (cannot be null)
0391: */
0392: private void initialize(URI p_other) {
0393: m_scheme = p_other.getScheme();
0394: m_userinfo = p_other.getUserinfo();
0395: m_host = p_other.getHost();
0396: m_port = p_other.getPort();
0397: m_regAuthority = p_other.getRegBasedAuthority();
0398: m_path = p_other.getPath();
0399: m_queryString = p_other.getQueryString();
0400: m_fragment = p_other.getFragment();
0401: }
0402:
0403: /**
0404: * Initializes this URI from a base URI and a URI specification string. See RFC 2396 Section 4 and
0405: * Appendix B for specifications on parsing the URI and Section 5 for specifications on resolving
0406: * relative URIs and relative paths.
0407: *
0408: * @param p_base the base URI (may be null if p_uriSpec is an absolute URI)
0409: * @param p_uriSpec the URI spec string which may be an absolute or relative URI (can only be
0410: * null/empty if p_base is not null)
0411: * @throws MalformedURIException if p_base is null and p_uriSpec is not an absolute URI or if
0412: * p_uriSpec violates syntax rules
0413: */
0414: private void initialize(URI p_base, String p_uriSpec)
0415: throws MalformedURIException {
0416:
0417: String uriSpec = p_uriSpec;
0418: int uriSpecLen = (uriSpec != null) ? uriSpec.length() : 0;
0419:
0420: if (p_base == null && uriSpecLen == 0) {
0421: throw new MalformedURIException(
0422: "Cannot initialize URI with empty parameters.");
0423: }
0424:
0425: // just make a copy of the base if spec is empty
0426: if (uriSpecLen == 0) {
0427: initialize(p_base);
0428: return;
0429: }
0430:
0431: int index = 0;
0432:
0433: // Check for scheme, which must be before '/', '?' or '#'. Also handle
0434: // names with DOS drive letters ('D:'), so 1-character schemes are not
0435: // allowed.
0436: int colonIdx = uriSpec.indexOf(':');
0437: if (colonIdx != -1) {
0438: final int searchFrom = colonIdx - 1;
0439: // search backwards starting from character before ':'.
0440: int slashIdx = uriSpec.lastIndexOf('/', searchFrom);
0441: int queryIdx = uriSpec.lastIndexOf('?', searchFrom);
0442: int fragmentIdx = uriSpec.lastIndexOf('#', searchFrom);
0443:
0444: if (colonIdx < 2 || slashIdx != -1 || queryIdx != -1
0445: || fragmentIdx != -1) {
0446: // A standalone base is a valid URI according to spec
0447: if (colonIdx == 0
0448: || (p_base == null && fragmentIdx != 0)) {
0449: throw new MalformedURIException(
0450: "No scheme found in URI.");
0451: }
0452: } else {
0453: initializeScheme(uriSpec);
0454: index = m_scheme.length() + 1;
0455:
0456: // Neither 'scheme:' or 'scheme:#fragment' are valid URIs.
0457: if (colonIdx == uriSpecLen - 1
0458: || uriSpec.charAt(colonIdx + 1) == '#') {
0459: throw new MalformedURIException(
0460: "Scheme specific part cannot be empty.");
0461: }
0462: }
0463: }
0464: // Two slashes means we may have authority, but definitely means we're either
0465: // matching net_path or abs_path. These two productions are ambiguous in that
0466: // every net_path (except those containing an IPv6Reference) is an abs_path.
0467: // RFC 2396 resolves this ambiguity by applying a greedy left most matching rule.
0468: // Try matching net_path first, and if that fails we don't have authority so
0469: // then attempt to match abs_path.
0470: //
0471: // net_path = "//" authority [ abs_path ]
0472: // abs_path = "/" path_segments
0473: if (((index + 1) < uriSpecLen)
0474: && (uriSpec.charAt(index) == '/' && uriSpec
0475: .charAt(index + 1) == '/')) {
0476: index += 2;
0477: int startPos = index;
0478:
0479: // Authority will be everything up to path, query or fragment
0480: char testChar = '\0';
0481: while (index < uriSpecLen) {
0482: testChar = uriSpec.charAt(index);
0483: if (testChar == '/' || testChar == '?'
0484: || testChar == '#') {
0485: break;
0486: }
0487: index++;
0488: }
0489:
0490: // Attempt to parse authority. If the section is an empty string
0491: // this is a valid server based authority, so set the host to this
0492: // value.
0493: if (index > startPos) {
0494: // If we didn't find authority we need to back up. Attempt to
0495: // match against abs_path next.
0496: if (!initializeAuthority(uriSpec.substring(startPos,
0497: index))) {
0498: index = startPos - 2;
0499: }
0500: } else {
0501: m_host = "";
0502: }
0503: }
0504:
0505: initializePath(uriSpec, index);
0506:
0507: // Resolve relative URI to base URI - see RFC 2396 Section 5.2
0508: // In some cases, it might make more sense to throw an exception
0509: // (when scheme is specified is the string spec and the base URI
0510: // is also specified, for example), but we're just following the
0511: // RFC specifications
0512: if (p_base != null) {
0513:
0514: // check to see if this is the current doc - RFC 2396 5.2 #2
0515: // note that this is slightly different from the RFC spec in that
0516: // we don't include the check for query string being null
0517: // - this handles cases where the urispec is just a query
0518: // string or a fragment (e.g. "?y" or "#s") -
0519: // see <http://www.ics.uci.edu/~fielding/url/test1.html> which
0520: // identified this as a bug in the RFC
0521: if (m_path.length() == 0 && m_scheme == null
0522: && m_host == null && m_regAuthority == null) {
0523: m_scheme = p_base.getScheme();
0524: m_userinfo = p_base.getUserinfo();
0525: m_host = p_base.getHost();
0526: m_port = p_base.getPort();
0527: m_regAuthority = p_base.getRegBasedAuthority();
0528: m_path = p_base.getPath();
0529:
0530: if (m_queryString == null) {
0531: m_queryString = p_base.getQueryString();
0532: }
0533: return;
0534: }
0535:
0536: // check for scheme - RFC 2396 5.2 #3
0537: // if we found a scheme, it means absolute URI, so we're done
0538: if (m_scheme == null) {
0539: m_scheme = p_base.getScheme();
0540: } else {
0541: return;
0542: }
0543:
0544: // check for authority - RFC 2396 5.2 #4
0545: // if we found a host, then we've got a network path, so we're done
0546: if (m_host == null && m_regAuthority == null) {
0547: m_userinfo = p_base.getUserinfo();
0548: m_host = p_base.getHost();
0549: m_port = p_base.getPort();
0550: m_regAuthority = p_base.getRegBasedAuthority();
0551: } else {
0552: return;
0553: }
0554:
0555: // check for absolute path - RFC 2396 5.2 #5
0556: if (m_path.length() > 0 && m_path.startsWith("/")) {
0557: return;
0558: }
0559:
0560: // if we get to this point, we need to resolve relative path
0561: // RFC 2396 5.2 #6
0562: String path = "";
0563: String basePath = p_base.getPath();
0564:
0565: // 6a - get all but the last segment of the base URI path
0566: if (basePath != null && basePath.length() > 0) {
0567: int lastSlash = basePath.lastIndexOf('/');
0568: if (lastSlash != -1) {
0569: path = basePath.substring(0, lastSlash + 1);
0570: }
0571: } else if (m_path.length() > 0) {
0572: path = "/";
0573: }
0574:
0575: // 6b - append the relative URI path
0576: path = path.concat(m_path);
0577:
0578: // 6c - remove all "./" where "." is a complete path segment
0579: index = -1;
0580: while ((index = path.indexOf("/./")) != -1) {
0581: path = path.substring(0, index + 1).concat(
0582: path.substring(index + 3));
0583: }
0584:
0585: // 6d - remove "." if path ends with "." as a complete path segment
0586: if (path.endsWith("/.")) {
0587: path = path.substring(0, path.length() - 1);
0588: }
0589:
0590: // 6e - remove all "<segment>/../" where "<segment>" is a complete
0591: // path segment not equal to ".."
0592: index = 1;
0593: int segIndex = -1;
0594: String tempString = null;
0595:
0596: while ((index = path.indexOf("/../", index)) > 0) {
0597: tempString = path.substring(0, path.indexOf("/../"));
0598: segIndex = tempString.lastIndexOf('/');
0599: if (segIndex != -1) {
0600: if (!tempString.substring(segIndex).equals("..")) {
0601: path = path.substring(0, segIndex + 1).concat(
0602: path.substring(index + 4));
0603: index = segIndex;
0604: } else
0605: index += 4;
0606: } else
0607: index += 4;
0608: }
0609:
0610: // 6f - remove ending "<segment>/.." where "<segment>" is a
0611: // complete path segment
0612: if (path.endsWith("/..")) {
0613: tempString = path.substring(0, path.length() - 3);
0614: segIndex = tempString.lastIndexOf('/');
0615: if (segIndex != -1) {
0616: path = path.substring(0, segIndex + 1);
0617: }
0618: }
0619: m_path = path;
0620: }
0621: }
0622:
0623: /**
0624: * Initialize the scheme for this URI from a URI string spec.
0625: *
0626: * @param p_uriSpec the URI specification (cannot be null)
0627: * @throws MalformedURIException if URI does not have a conformant scheme
0628: */
0629: private void initializeScheme(String p_uriSpec)
0630: throws MalformedURIException {
0631: int uriSpecLen = p_uriSpec.length();
0632: int index = 0;
0633: String scheme = null;
0634: char testChar = '\0';
0635:
0636: while (index < uriSpecLen) {
0637: testChar = p_uriSpec.charAt(index);
0638: if (testChar == ':' || testChar == '/' || testChar == '?'
0639: || testChar == '#') {
0640: break;
0641: }
0642: index++;
0643: }
0644: scheme = p_uriSpec.substring(0, index);
0645:
0646: if (scheme.length() == 0) {
0647: throw new MalformedURIException("No scheme found in URI.");
0648: } else {
0649: setScheme(scheme);
0650: }
0651: }
0652:
0653: /**
0654: * Initialize the authority (either server or registry based) for this URI from a URI string
0655: * spec.
0656: *
0657: * @param p_uriSpec the URI specification (cannot be null)
0658: * @return true if the given string matched server or registry based authority
0659: */
0660: private boolean initializeAuthority(String p_uriSpec) {
0661:
0662: int index = 0;
0663: int start = 0;
0664: int end = p_uriSpec.length();
0665:
0666: char testChar = '\0';
0667: String userinfo = null;
0668:
0669: // userinfo is everything up to @
0670: if (p_uriSpec.indexOf('@', start) != -1) {
0671: while (index < end) {
0672: testChar = p_uriSpec.charAt(index);
0673: if (testChar == '@') {
0674: break;
0675: }
0676: index++;
0677: }
0678: userinfo = p_uriSpec.substring(start, index);
0679: index++;
0680: }
0681:
0682: // host is everything up to last ':', or up to
0683: // and including ']' if followed by ':'.
0684: String host = null;
0685: start = index;
0686: boolean hasPort = false;
0687: if (index < end) {
0688: if (p_uriSpec.charAt(start) == '[') {
0689: int bracketIndex = p_uriSpec.indexOf(']', start);
0690: index = (bracketIndex != -1) ? bracketIndex : end;
0691: if (index + 1 < end
0692: && p_uriSpec.charAt(index + 1) == ':') {
0693: ++index;
0694: hasPort = true;
0695: } else {
0696: index = end;
0697: }
0698: } else {
0699: int colonIndex = p_uriSpec.lastIndexOf(':', end);
0700: index = (colonIndex > start) ? colonIndex : end;
0701: hasPort = (index != end);
0702: }
0703: }
0704: host = p_uriSpec.substring(start, index);
0705: int port = -1;
0706: if (host.length() > 0) {
0707: // port
0708: if (hasPort) {
0709: index++;
0710: start = index;
0711: while (index < end) {
0712: index++;
0713: }
0714: String portStr = p_uriSpec.substring(start, index);
0715: if (portStr.length() > 0) {
0716: // REVISIT: Remove this code.
0717: /** for (int i = 0; i < portStr.length(); i++) {
0718: if (!isDigit(portStr.charAt(i))) {
0719: throw new MalformedURIException(
0720: portStr +
0721: " is invalid. Port should only contain digits!");
0722: }
0723: }**/
0724: // REVISIT: Remove this code.
0725: // Store port value as string instead of integer.
0726: try {
0727: port = Integer.parseInt(portStr);
0728: if (port == -1)
0729: --port;
0730: } catch (NumberFormatException nfe) {
0731: port = -2;
0732: }
0733: }
0734: }
0735: }
0736:
0737: if (isValidServerBasedAuthority(host, port, userinfo)) {
0738: m_host = host;
0739: m_port = port;
0740: m_userinfo = userinfo;
0741: return true;
0742: }
0743: // Note: Registry based authority is being removed from a
0744: // new spec for URI which would obsolete RFC 2396. If the
0745: // spec is added to XML errata, processing of reg_name
0746: // needs to be removed. - mrglavas.
0747: else if (isValidRegistryBasedAuthority(p_uriSpec)) {
0748: m_regAuthority = p_uriSpec;
0749: return true;
0750: }
0751: return false;
0752: }
0753:
0754: /**
0755: * Determines whether the components host, port, and user info are valid as a server authority.
0756: *
0757: * @param host the host component of authority
0758: * @param port the port number component of authority
0759: * @param userinfo the user info component of authority
0760: * @return true if the given host, port, and userinfo compose a valid server authority
0761: */
0762: private boolean isValidServerBasedAuthority(String host, int port,
0763: String userinfo) {
0764:
0765: // Check if the host is well formed.
0766: if (!isWellFormedAddress(host)) {
0767: return false;
0768: }
0769:
0770: // Check that port is well formed if it exists.
0771: // REVISIT: There's no restriction on port value ranges, but
0772: // perform the same check as in setPort to be consistent. Pass
0773: // in a string to this method instead of an integer.
0774: if (port < -1 || port > 65535) {
0775: return false;
0776: }
0777:
0778: // Check that userinfo is well formed if it exists.
0779: if (userinfo != null) {
0780: // Userinfo can contain alphanumerics, mark characters, escaped
0781: // and ';',':','&','=','+','$',','
0782: int index = 0;
0783: int end = userinfo.length();
0784: char testChar = '\0';
0785: while (index < end) {
0786: testChar = userinfo.charAt(index);
0787: if (testChar == '%') {
0788: if (index + 2 >= end
0789: || !isHex(userinfo.charAt(index + 1))
0790: || !isHex(userinfo.charAt(index + 2))) {
0791: return false;
0792: }
0793: index += 2;
0794: } else if (!isUserinfoCharacter(testChar)) {
0795: return false;
0796: }
0797: ++index;
0798: }
0799: }
0800: return true;
0801: }
0802:
0803: /**
0804: * Determines whether the given string is a registry based authority.
0805: *
0806: * @param authority the authority component of a URI
0807: * @return true if the given string is a registry based authority
0808: */
0809: private boolean isValidRegistryBasedAuthority(String authority) {
0810: int index = 0;
0811: int end = authority.length();
0812: char testChar;
0813:
0814: while (index < end) {
0815: testChar = authority.charAt(index);
0816:
0817: // check for valid escape sequence
0818: if (testChar == '%') {
0819: if (index + 2 >= end
0820: || !isHex(authority.charAt(index + 1))
0821: || !isHex(authority.charAt(index + 2))) {
0822: return false;
0823: }
0824: index += 2;
0825: }
0826: // can check against path characters because the set
0827: // is the same except for '/' which we've already excluded.
0828: else if (!isPathCharacter(testChar)) {
0829: return false;
0830: }
0831: ++index;
0832: }
0833: return true;
0834: }
0835:
0836: /**
0837: * Initialize the path for this URI from a URI string spec.
0838: *
0839: * @param p_uriSpec the URI specification (cannot be null)
0840: * @param p_nStartIndex the index to begin scanning from
0841: * @throws MalformedURIException if p_uriSpec violates syntax rules
0842: */
0843: private void initializePath(String p_uriSpec, int p_nStartIndex)
0844: throws MalformedURIException {
0845: if (p_uriSpec == null) {
0846: throw new MalformedURIException(
0847: "Cannot initialize path from null string!");
0848: }
0849:
0850: int index = p_nStartIndex;
0851: int start = p_nStartIndex;
0852: int end = p_uriSpec.length();
0853: char testChar = '\0';
0854:
0855: // path - everything up to query string or fragment
0856: if (start < end) {
0857: // RFC 2732 only allows '[' and ']' to appear in the opaque part.
0858: if (getScheme() == null || p_uriSpec.charAt(start) == '/') {
0859:
0860: // Scan path.
0861: // abs_path = "/" path_segments
0862: // rel_path = rel_segment [ abs_path ]
0863: while (index < end) {
0864: testChar = p_uriSpec.charAt(index);
0865:
0866: // check for valid escape sequence
0867: if (testChar == '%') {
0868: if (index + 2 >= end
0869: || !isHex(p_uriSpec.charAt(index + 1))
0870: || !isHex(p_uriSpec.charAt(index + 2))) {
0871: throw new MalformedURIException(
0872: "Path contains invalid escape sequence!");
0873: }
0874: index += 2;
0875: }
0876: // Path segments cannot contain '[' or ']' since pchar
0877: // production was not changed by RFC 2732.
0878: else if (!isPathCharacter(testChar)) {
0879: if (testChar == '?' || testChar == '#') {
0880: break;
0881: }
0882: throw new MalformedURIException(
0883: "Path contains invalid character: "
0884: + testChar);
0885: }
0886: ++index;
0887: }
0888: } else {
0889:
0890: // Scan opaque part.
0891: // opaque_part = uric_no_slash *uric
0892: while (index < end) {
0893: testChar = p_uriSpec.charAt(index);
0894:
0895: if (testChar == '?' || testChar == '#') {
0896: break;
0897: }
0898:
0899: // check for valid escape sequence
0900: if (testChar == '%') {
0901: if (index + 2 >= end
0902: || !isHex(p_uriSpec.charAt(index + 1))
0903: || !isHex(p_uriSpec.charAt(index + 2))) {
0904: throw new MalformedURIException(
0905: "Opaque part contains invalid escape sequence!");
0906: }
0907: index += 2;
0908: }
0909: // If the scheme specific part is opaque, it can contain '['
0910: // and ']'. uric_no_slash wasn't modified by RFC 2732, which
0911: // I've interpreted as an error in the spec, since the
0912: // production should be equivalent to (uric - '/'), and uric
0913: // contains '[' and ']'. - mrglavas
0914: else if (!isURICharacter(testChar)) {
0915: throw new MalformedURIException(
0916: "Opaque part contains invalid character: "
0917: + testChar);
0918: }
0919: ++index;
0920: }
0921: }
0922: }
0923: m_path = p_uriSpec.substring(start, index);
0924:
0925: // query - starts with ? and up to fragment or end
0926: if (testChar == '?') {
0927: index++;
0928: start = index;
0929: while (index < end) {
0930: testChar = p_uriSpec.charAt(index);
0931: if (testChar == '#') {
0932: break;
0933: }
0934: if (testChar == '%') {
0935: if (index + 2 >= end
0936: || !isHex(p_uriSpec.charAt(index + 1))
0937: || !isHex(p_uriSpec.charAt(index + 2))) {
0938: throw new MalformedURIException(
0939: "Query string contains invalid escape sequence!");
0940: }
0941: index += 2;
0942: } else if (!isURICharacter(testChar)) {
0943: throw new MalformedURIException(
0944: "Query string contains invalid character: "
0945: + testChar);
0946: }
0947: index++;
0948: }
0949: m_queryString = p_uriSpec.substring(start, index);
0950: }
0951:
0952: // fragment - starts with #
0953: if (testChar == '#') {
0954: index++;
0955: start = index;
0956: while (index < end) {
0957: testChar = p_uriSpec.charAt(index);
0958:
0959: if (testChar == '%') {
0960: if (index + 2 >= end
0961: || !isHex(p_uriSpec.charAt(index + 1))
0962: || !isHex(p_uriSpec.charAt(index + 2))) {
0963: throw new MalformedURIException(
0964: "Fragment contains invalid escape sequence!");
0965: }
0966: index += 2;
0967: } else if (!isURICharacter(testChar)) {
0968: throw new MalformedURIException(
0969: "Fragment contains invalid character: "
0970: + testChar);
0971: }
0972: index++;
0973: }
0974: m_fragment = p_uriSpec.substring(start, index);
0975: }
0976: }
0977:
0978: /**
0979: * Get the scheme for this URI.
0980: *
0981: * @return the scheme for this URI
0982: */
0983: public String getScheme() {
0984: return m_scheme;
0985: }
0986:
0987: /**
0988: * Get the scheme-specific part for this URI (everything following the scheme and the first
0989: * colon). See RFC 2396 Section 5.2 for spec.
0990: *
0991: * @return the scheme-specific part for this URI
0992: */
0993: public String getSchemeSpecificPart() {
0994: StringBuffer schemespec = new StringBuffer();
0995:
0996: if (m_host != null || m_regAuthority != null) {
0997: schemespec.append("//");
0998:
0999: // Server based authority.
1000: if (m_host != null) {
1001:
1002: if (m_userinfo != null) {
1003: schemespec.append(m_userinfo);
1004: schemespec.append('@');
1005: }
1006:
1007: schemespec.append(m_host);
1008:
1009: if (m_port != -1) {
1010: schemespec.append(':');
1011: schemespec.append(m_port);
1012: }
1013: }
1014: // Registry based authority.
1015: else {
1016: schemespec.append(m_regAuthority);
1017: }
1018: }
1019:
1020: if (m_path != null) {
1021: schemespec.append((m_path));
1022: }
1023:
1024: if (m_queryString != null) {
1025: schemespec.append('?');
1026: schemespec.append(m_queryString);
1027: }
1028:
1029: if (m_fragment != null) {
1030: schemespec.append('#');
1031: schemespec.append(m_fragment);
1032: }
1033:
1034: return schemespec.toString();
1035: }
1036:
1037: /**
1038: * Get the userinfo for this URI.
1039: *
1040: * @return the userinfo for this URI (null if not specified).
1041: */
1042: public String getUserinfo() {
1043: return m_userinfo;
1044: }
1045:
1046: /**
1047: * Get the host for this URI.
1048: *
1049: * @return the host for this URI (null if not specified).
1050: */
1051: public String getHost() {
1052: return m_host;
1053: }
1054:
1055: /**
1056: * Get the port for this URI.
1057: *
1058: * @return the port for this URI (-1 if not specified).
1059: */
1060: public int getPort() {
1061: return m_port;
1062: }
1063:
1064: /**
1065: * Get the registry based authority for this URI.
1066: *
1067: * @return the registry based authority (null if not specified).
1068: */
1069: public String getRegBasedAuthority() {
1070: return m_regAuthority;
1071: }
1072:
1073: /**
1074: * Get the path for this URI (optionally with the query string and fragment).
1075: *
1076: * @param p_includeQueryString if true (and query string is not null), then a "?" followed by the
1077: * query string will be appended
1078: * @param p_includeFragment if true (and fragment is not null), then a "#" followed by the
1079: * fragment will be appended
1080: * @return the path for this URI possibly including the query string and fragment
1081: */
1082: public String getPath(boolean p_includeQueryString,
1083: boolean p_includeFragment) {
1084: StringBuffer pathString = new StringBuffer(m_path);
1085:
1086: if (p_includeQueryString && m_queryString != null) {
1087: pathString.append('?');
1088: pathString.append(m_queryString);
1089: }
1090:
1091: if (p_includeFragment && m_fragment != null) {
1092: pathString.append('#');
1093: pathString.append(m_fragment);
1094: }
1095: return pathString.toString();
1096: }
1097:
1098: /**
1099: * Get the path for this URI. Note that the value returned is the path only and does not include
1100: * the query string or fragment.
1101: *
1102: * @return the path for this URI.
1103: */
1104: public String getPath() {
1105: return m_path;
1106: }
1107:
1108: /**
1109: * Get the query string for this URI.
1110: *
1111: * @return the query string for this URI. Null is returned if there was no "?" in the URI spec,
1112: * empty string if there was a "?" but no query string following it.
1113: */
1114: public String getQueryString() {
1115: return m_queryString;
1116: }
1117:
1118: /**
1119: * Get the fragment for this URI.
1120: *
1121: * @return the fragment for this URI. Null is returned if there was no "#" in the URI spec, empty
1122: * string if there was a "#" but no fragment following it.
1123: */
1124: public String getFragment() {
1125: return m_fragment;
1126: }
1127:
1128: /**
1129: * Set the scheme for this URI. The scheme is converted to lowercase before it is set.
1130: *
1131: * @param p_scheme the scheme for this URI (cannot be null)
1132: * @throws MalformedURIException if p_scheme is not a conformant scheme name
1133: */
1134: public void setScheme(String p_scheme) throws MalformedURIException {
1135: if (p_scheme == null) {
1136: throw new MalformedURIException(
1137: "Cannot set scheme from null string!");
1138: }
1139: if (!isConformantSchemeName(p_scheme)) {
1140: throw new MalformedURIException(
1141: "The scheme is not conformant.");
1142: }
1143:
1144: m_scheme = p_scheme.toLowerCase();
1145: }
1146:
1147: /**
1148: * Set the userinfo for this URI. If a non-null value is passed in and the host value is null,
1149: * then an exception is thrown.
1150: *
1151: * @param p_userinfo the userinfo for this URI
1152: * @throws MalformedURIException if p_userinfo contains invalid characters
1153: */
1154: public void setUserinfo(String p_userinfo)
1155: throws MalformedURIException {
1156: if (p_userinfo == null) {
1157: m_userinfo = null;
1158: return;
1159: } else {
1160: if (m_host == null) {
1161: throw new MalformedURIException(
1162: "Userinfo cannot be set when host is null!");
1163: }
1164:
1165: // userinfo can contain alphanumerics, mark characters, escaped
1166: // and ';',':','&','=','+','$',','
1167: int index = 0;
1168: int end = p_userinfo.length();
1169: char testChar = '\0';
1170: while (index < end) {
1171: testChar = p_userinfo.charAt(index);
1172: if (testChar == '%') {
1173: if (index + 2 >= end
1174: || !isHex(p_userinfo.charAt(index + 1))
1175: || !isHex(p_userinfo.charAt(index + 2))) {
1176: throw new MalformedURIException(
1177: "Userinfo contains invalid escape sequence!");
1178: }
1179: } else if (!isUserinfoCharacter(testChar)) {
1180: throw new MalformedURIException(
1181: "Userinfo contains invalid character:"
1182: + testChar);
1183: }
1184: index++;
1185: }
1186: }
1187: m_userinfo = p_userinfo;
1188: }
1189:
1190: /**
1191: * <p>Set the host for this URI. If null is passed in, the userinfo field is also set to null and
1192: * the port is set to -1.</p>
1193: * <p/>
1194: * <p>Note: This method overwrites registry based authority if it previously existed in this
1195: * URI.</p>
1196: *
1197: * @param p_host the host for this URI
1198: * @throws MalformedURIException if p_host is not a valid IP address or DNS hostname.
1199: */
1200: public void setHost(String p_host) throws MalformedURIException {
1201: if (p_host == null || p_host.length() == 0) {
1202: if (p_host != null) {
1203: m_regAuthority = null;
1204: }
1205: m_host = p_host;
1206: m_userinfo = null;
1207: m_port = -1;
1208: return;
1209: } else if (!isWellFormedAddress(p_host)) {
1210: throw new MalformedURIException(
1211: "Host is not a well formed address!");
1212: }
1213: m_host = p_host;
1214: m_regAuthority = null;
1215: }
1216:
1217: /**
1218: * Set the port for this URI. -1 is used to indicate that the port is not specified, otherwise
1219: * valid port numbers are between 0 and 65535. If a valid port number is passed in and the host
1220: * field is null, an exception is thrown.
1221: *
1222: * @param p_port the port number for this URI
1223: * @throws MalformedURIException if p_port is not -1 and not a valid port number
1224: */
1225: public void setPort(int p_port) throws MalformedURIException {
1226: if (p_port >= 0 && p_port <= 65535) {
1227: if (m_host == null) {
1228: throw new MalformedURIException(
1229: "Port cannot be set when host is null!");
1230: }
1231: } else if (p_port != -1) {
1232: throw new MalformedURIException("Invalid port number!");
1233: }
1234: m_port = p_port;
1235: }
1236:
1237: /**
1238: * <p>Sets the registry based authority for this URI.</p>
1239: * <p/>
1240: * <p>Note: This method overwrites server based authority if it previously existed in this
1241: * URI.</p>
1242: *
1243: * @param authority the registry based authority for this URI
1244: * @throws MalformedURIException it authority is not a well formed registry based authority
1245: */
1246: public void setRegBasedAuthority(String authority)
1247: throws MalformedURIException {
1248:
1249: if (authority == null) {
1250: m_regAuthority = null;
1251: return;
1252: }
1253: // reg_name = 1*( unreserved | escaped | "$" | "," |
1254: // ";" | ":" | "@" | "&" | "=" | "+" )
1255: else if (authority.length() < 1
1256: || !isValidRegistryBasedAuthority(authority)
1257: || authority.indexOf('/') != -1) {
1258: throw new MalformedURIException(
1259: "Registry based authority is not well formed.");
1260: }
1261: m_regAuthority = authority;
1262: m_host = null;
1263: m_userinfo = null;
1264: m_port = -1;
1265: }
1266:
1267: /**
1268: * Set the path for this URI. If the supplied path is null, then the query string and fragment are
1269: * set to null as well. If the supplied path includes a query string and/or fragment, these fields
1270: * will be parsed and set as well. Note that, for URIs following the "generic URI" syntax, the
1271: * path specified should start with a slash. For URIs that do not follow the generic URI syntax,
1272: * this method sets the scheme-specific part.
1273: *
1274: * @param p_path the path for this URI (may be null)
1275: * @throws MalformedURIException if p_path contains invalid characters
1276: */
1277: public void setPath(String p_path) throws MalformedURIException {
1278: if (p_path == null) {
1279: m_path = null;
1280: m_queryString = null;
1281: m_fragment = null;
1282: } else {
1283: initializePath(p_path, 0);
1284: }
1285: }
1286:
1287: /**
1288: * Append to the end of the path of this URI. If the current path does not end in a slash and the
1289: * path to be appended does not begin with a slash, a slash will be appended to the current path
1290: * before the new segment is added. Also, if the current path ends in a slash and the new segment
1291: * begins with a slash, the extra slash will be removed before the new segment is appended.
1292: *
1293: * @param p_addToPath the new segment to be added to the current path
1294: * @throws MalformedURIException if p_addToPath contains syntax errors
1295: */
1296: public void appendPath(String p_addToPath)
1297: throws MalformedURIException {
1298: if (p_addToPath == null || p_addToPath.trim().length() == 0) {
1299: return;
1300: }
1301:
1302: if (!isURIString(p_addToPath)) {
1303: throw new MalformedURIException(
1304: "Path contains invalid character!");
1305: }
1306:
1307: if (m_path == null || m_path.trim().length() == 0) {
1308: if (p_addToPath.startsWith("/")) {
1309: m_path = p_addToPath;
1310: } else {
1311: m_path = "/" + p_addToPath;
1312: }
1313: } else if (m_path.endsWith("/")) {
1314: if (p_addToPath.startsWith("/")) {
1315: m_path = m_path.concat(p_addToPath.substring(1));
1316: } else {
1317: m_path = m_path.concat(p_addToPath);
1318: }
1319: } else {
1320: if (p_addToPath.startsWith("/")) {
1321: m_path = m_path.concat(p_addToPath);
1322: } else {
1323: m_path = m_path.concat("/" + p_addToPath);
1324: }
1325: }
1326: }
1327:
1328: /**
1329: * Set the query string for this URI. A non-null value is valid only if this is an URI conforming
1330: * to the generic URI syntax and the path value is not null.
1331: *
1332: * @param p_queryString the query string for this URI
1333: * @throws MalformedURIException if p_queryString is not null and this URI does not conform to the
1334: * generic URI syntax or if the path is null
1335: */
1336: public void setQueryString(String p_queryString)
1337: throws MalformedURIException {
1338: if (p_queryString == null) {
1339: m_queryString = null;
1340: } else if (!isGenericURI()) {
1341: throw new MalformedURIException(
1342: "Query string can only be set for a generic URI!");
1343: } else if (this .m_path == null) {
1344: throw new MalformedURIException(
1345: "Query string cannot be set when path is null!");
1346: } else if (!isURIString(p_queryString)) {
1347: throw new MalformedURIException(
1348: "Query string contains invalid character!");
1349: } else {
1350: m_queryString = p_queryString;
1351: }
1352: }
1353:
1354: /**
1355: * Set the fragment for this URI. A non-null value is valid only if this is a URI conforming to
1356: * the generic URI syntax and the path value is not null.
1357: *
1358: * @param p_fragment the fragment for this URI
1359: * @throws MalformedURIException if p_fragment is not null and this URI does not conform to the
1360: * generic URI syntax or if the path is null
1361: */
1362: public void setFragment(String p_fragment)
1363: throws MalformedURIException {
1364: if (p_fragment == null) {
1365: m_fragment = null;
1366: } else if (!isGenericURI()) {
1367: throw new MalformedURIException(
1368: "Fragment can only be set for a generic URI!");
1369: } else if (getPath() == null) {
1370: throw new MalformedURIException(
1371: "Fragment cannot be set when path is null!");
1372: } else if (!isURIString(p_fragment)) {
1373: throw new MalformedURIException(
1374: "Fragment contains invalid character!");
1375: } else {
1376: m_fragment = p_fragment;
1377: }
1378: }
1379:
1380: /**
1381: * Determines if the passed-in Object is equivalent to this URI.
1382: *
1383: * @param p_test the Object to test for equality.
1384: * @return true if p_test is a URI with all values equal to this URI, false otherwise
1385: */
1386: public boolean equals(Object p_test) {
1387: if (p_test instanceof URI) {
1388: URI testURI = (URI) p_test;
1389: if (((m_scheme == null && testURI.m_scheme == null) || (m_scheme != null
1390: && testURI.m_scheme != null && m_scheme
1391: .equals(testURI.m_scheme)))
1392: && ((m_userinfo == null && testURI.m_userinfo == null) || (m_userinfo != null
1393: && testURI.m_userinfo != null && m_userinfo
1394: .equals(testURI.m_userinfo)))
1395: && ((m_host == null && testURI.m_host == null) || (m_host != null
1396: && testURI.m_host != null && m_host
1397: .equals(testURI.m_host)))
1398: && m_port == testURI.m_port
1399: && ((m_path == null && testURI.m_path == null) || (m_path != null
1400: && testURI.m_path != null && m_path
1401: .equals(testURI.m_path)))
1402: && ((m_queryString == null && testURI.m_queryString == null) || (m_queryString != null
1403: && testURI.m_queryString != null && m_queryString
1404: .equals(testURI.m_queryString)))
1405: && ((m_fragment == null && testURI.m_fragment == null) || (m_fragment != null
1406: && testURI.m_fragment != null && m_fragment
1407: .equals(testURI.m_fragment)))) {
1408: return true;
1409: }
1410: }
1411: return false;
1412: }
1413:
1414: /**
1415: * Returns a hash-code value for this URI. The hash code is based upon all of the URI's
1416: * components, and satisfies the general contract of the {@link Object#hashCode()
1417: * Object.hashCode} method. </p>
1418: *
1419: * @return A hash-code value for this URI
1420: */
1421: public int hashCode() {
1422: return toString().hashCode();
1423: }
1424:
1425: /**
1426: * Get the URI as a string specification. See RFC 2396 Section 5.2.
1427: *
1428: * @return the URI string specification
1429: */
1430: public String toString() {
1431: StringBuffer uriSpecString = new StringBuffer();
1432:
1433: if (m_scheme != null) {
1434: uriSpecString.append(m_scheme);
1435: uriSpecString.append(':');
1436: }
1437: uriSpecString.append(getSchemeSpecificPart());
1438: return uriSpecString.toString();
1439: }
1440:
1441: /**
1442: * Get the indicator as to whether this URI uses the "generic URI" syntax.
1443: *
1444: * @return true if this URI uses the "generic URI" syntax, false otherwise
1445: */
1446: public boolean isGenericURI() {
1447: // presence of the host (whether valid or empty) means
1448: // double-slashes which means generic uri
1449: return (m_host != null);
1450: }
1451:
1452: /**
1453: * Determine whether a scheme conforms to the rules for a scheme name. A scheme is conformant if
1454: * it starts with an alphanumeric, and contains only alphanumerics, '+','-' and '.'.
1455: *
1456: * @return true if the scheme is conformant, false otherwise
1457: */
1458: public static boolean isConformantSchemeName(String p_scheme) {
1459: if (p_scheme == null || p_scheme.trim().length() == 0) {
1460: return false;
1461: }
1462:
1463: if (!isAlpha(p_scheme.charAt(0))) {
1464: return false;
1465: }
1466:
1467: char testChar;
1468: int schemeLength = p_scheme.length();
1469: for (int i = 1; i < schemeLength; ++i) {
1470: testChar = p_scheme.charAt(i);
1471: if (!isSchemeCharacter(testChar)) {
1472: return false;
1473: }
1474: }
1475:
1476: return true;
1477: }
1478:
1479: /**
1480: * Determine whether a string is syntactically capable of representing a valid IPv4 address, IPv6
1481: * reference or the domain name of a network host. A valid IPv4 address consists of four decimal
1482: * digit groups separated by a '.'. Each group must consist of one to three digits. See RFC 2732
1483: * Section 3, and RFC 2373 Section 2.2, for the definition of IPv6 references. A hostname consists
1484: * of domain labels (each of which must begin and end with an alphanumeric but may contain '-')
1485: * separated & by a '.'. See RFC 2396 Section 3.2.2.
1486: *
1487: * @return true if the string is a syntactically valid IPv4 address, IPv6 reference or hostname
1488: */
1489: public static boolean isWellFormedAddress(String address) {
1490: if (address == null) {
1491: return false;
1492: }
1493:
1494: int addrLength = address.length();
1495: if (addrLength == 0) {
1496: return false;
1497: }
1498:
1499: // Check if the host is a valid IPv6reference.
1500: if (address.startsWith("[")) {
1501: return isWellFormedIPv6Reference(address);
1502: }
1503:
1504: // Cannot start with a '.', '-', or end with a '-'.
1505: if (address.startsWith(".") || address.startsWith("-")
1506: || address.endsWith("-")) {
1507: return false;
1508: }
1509:
1510: // rightmost domain label starting with digit indicates IP address
1511: // since top level domain label can only start with an alpha
1512: // see RFC 2396 Section 3.2.2
1513: int index = address.lastIndexOf('.');
1514: if (address.endsWith(".")) {
1515: index = address.substring(0, index).lastIndexOf('.');
1516: }
1517:
1518: if (index + 1 < addrLength
1519: && isDigit(address.charAt(index + 1))) {
1520: return isWellFormedIPv4Address(address);
1521: } else {
1522: // hostname = *( domainlabel "." ) toplabel [ "." ]
1523: // domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum
1524: // toplabel = alpha | alpha *( alphanum | "-" ) alphanum
1525:
1526: // RFC 2396 states that hostnames take the form described in
1527: // RFC 1034 (Section 3) and RFC 1123 (Section 2.1). According
1528: // to RFC 1034, hostnames are limited to 255 characters.
1529: if (addrLength > 255) {
1530: return false;
1531: }
1532:
1533: // domain labels can contain alphanumerics and '-"
1534: // but must start and end with an alphanumeric
1535: char testChar;
1536: int labelCharCount = 0;
1537:
1538: for (int i = 0; i < addrLength; i++) {
1539: testChar = address.charAt(i);
1540: if (testChar == '.') {
1541: if (!isAlphanum(address.charAt(i - 1))) {
1542: return false;
1543: }
1544: if (i + 1 < addrLength
1545: && !isAlphanum(address.charAt(i + 1))) {
1546: return false;
1547: }
1548: labelCharCount = 0;
1549: } else if (!isAlphanum(testChar) && testChar != '-') {
1550: return false;
1551: }
1552: // RFC 1034: Labels must be 63 characters or less.
1553: else if (++labelCharCount > 63) {
1554: return false;
1555: }
1556: }
1557: }
1558: return true;
1559: }
1560:
1561: /**
1562: * <p>Determines whether a string is an IPv4 address as defined by RFC 2373, and under the further
1563: * constraint that it must be a 32-bit address. Though not expressed in the grammar, in order to
1564: * satisfy the 32-bit address constraint, each segment of the address cannot be greater than 255
1565: * (8 bits of information).</p>
1566: * <p/>
1567: * <p><code>IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT</code></p>
1568: *
1569: * @return true if the string is a syntactically valid IPv4 address
1570: */
1571: public static boolean isWellFormedIPv4Address(String address) {
1572:
1573: int addrLength = address.length();
1574: char testChar;
1575: int numDots = 0;
1576: int numDigits = 0;
1577:
1578: // make sure that 1) we see only digits and dot separators, 2) that
1579: // any dot separator is preceded and followed by a digit and
1580: // 3) that we find 3 dots
1581: //
1582: // RFC 2732 amended RFC 2396 by replacing the definition
1583: // of IPv4address with the one defined by RFC 2373. - mrglavas
1584: //
1585: // IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT
1586: //
1587: // One to three digits must be in each segment.
1588: for (int i = 0; i < addrLength; i++) {
1589: testChar = address.charAt(i);
1590: if (testChar == '.') {
1591: if ((i > 0 && !isDigit(address.charAt(i - 1)))
1592: || (i + 1 < addrLength && !isDigit(address
1593: .charAt(i + 1)))) {
1594: return false;
1595: }
1596: numDigits = 0;
1597: if (++numDots > 3) {
1598: return false;
1599: }
1600: } else if (!isDigit(testChar)) {
1601: return false;
1602: }
1603: // Check that that there are no more than three digits
1604: // in this segment.
1605: else if (++numDigits > 3) {
1606: return false;
1607: }
1608: // Check that this segment is not greater than 255.
1609: else if (numDigits == 3) {
1610: char first = address.charAt(i - 2);
1611: char second = address.charAt(i - 1);
1612: if (!(first < '2' || (first == '2' && (second < '5' || (second == '5' && testChar <= '5'))))) {
1613: return false;
1614: }
1615: }
1616: }
1617: return (numDots == 3);
1618: }
1619:
1620: /**
1621: * <p>Determines whether a string is an IPv6 reference as defined by RFC 2732, where IPv6address
1622: * is defined in RFC 2373. The IPv6 address is parsed according to Section 2.2 of RFC 2373, with
1623: * the additional constraint that the address be composed of 128 bits of information.</p>
1624: * <p/>
1625: * <p><code>IPv6reference = "[" IPv6address "]"</code></p>
1626: * <p/>
1627: * <p>Note: The BNF expressed in RFC 2373 Appendix B does not accurately describe section 2.2, and
1628: * was in fact removed from RFC 3513, the successor of RFC 2373.</p>
1629: *
1630: * @return true if the string is a syntactically valid IPv6 reference
1631: */
1632: public static boolean isWellFormedIPv6Reference(String address) {
1633:
1634: int addrLength = address.length();
1635: int index = 1;
1636: int end = addrLength - 1;
1637:
1638: // Check if string is a potential match for IPv6reference.
1639: if (!(addrLength > 2 && address.charAt(0) == '[' && address
1640: .charAt(end) == ']')) {
1641: return false;
1642: }
1643:
1644: // Counter for the number of 16-bit sections read in the address.
1645: int[] counter = new int[1];
1646:
1647: // Scan hex sequence before possible '::' or IPv4 address.
1648: index = scanHexSequence(address, index, end, counter);
1649: if (index == -1) {
1650: return false;
1651: }
1652: // Address must contain 128-bits of information.
1653: else if (index == end) {
1654: return (counter[0] == 8);
1655: }
1656:
1657: if (index + 1 < end && address.charAt(index) == ':') {
1658: if (address.charAt(index + 1) == ':') {
1659: // '::' represents at least one 16-bit group of zeros.
1660: if (++counter[0] > 8) {
1661: return false;
1662: }
1663: index += 2;
1664: // Trailing zeros will fill out the rest of the address.
1665: if (index == end) {
1666: return true;
1667: }
1668: }
1669: // If the second character wasn't ':', in order to be valid,
1670: // the remainder of the string must match IPv4Address,
1671: // and we must have read exactly 6 16-bit groups.
1672: else {
1673: return (counter[0] == 6)
1674: && isWellFormedIPv4Address(address.substring(
1675: index + 1, end));
1676: }
1677: } else {
1678: return false;
1679: }
1680:
1681: // 3. Scan hex sequence after '::'.
1682: int prevCount = counter[0];
1683: index = scanHexSequence(address, index, end, counter);
1684:
1685: // We've either reached the end of the string, the address ends in
1686: // an IPv4 address, or it is invalid. scanHexSequence has already
1687: // made sure that we have the right number of bits.
1688: return (index == end)
1689: || (index != -1 && isWellFormedIPv4Address(address
1690: .substring((counter[0] > prevCount) ? index + 1
1691: : index, end)));
1692: }
1693:
1694: /**
1695: * Helper method for isWellFormedIPv6Reference which scans the hex sequences of an IPv6 address.
1696: * It returns the index of the next character to scan in the address, or -1 if the string cannot
1697: * match a valid IPv6 address.
1698: *
1699: * @param address the string to be scanned
1700: * @param index the beginning index (inclusive)
1701: * @param end the ending index (exclusive)
1702: * @param counter a counter for the number of 16-bit sections read in the address
1703: * @return the index of the next character to scan, or -1 if the string cannot match a valid IPv6
1704: * address
1705: */
1706: private static int scanHexSequence(String address, int index,
1707: int end, int[] counter) {
1708:
1709: char testChar;
1710: int numDigits = 0;
1711: int start = index;
1712:
1713: // Trying to match the following productions:
1714: // hexseq = hex4 *( ":" hex4)
1715: // hex4 = 1*4HEXDIG
1716: for (; index < end; ++index) {
1717: testChar = address.charAt(index);
1718: if (testChar == ':') {
1719: // IPv6 addresses are 128-bit, so there can be at most eight sections.
1720: if (numDigits > 0 && ++counter[0] > 8) {
1721: return -1;
1722: }
1723: // This could be '::'.
1724: if (numDigits == 0
1725: || ((index + 1 < end) && address
1726: .charAt(index + 1) == ':')) {
1727: return index;
1728: }
1729: numDigits = 0;
1730: }
1731: // This might be invalid or an IPv4address. If it's potentially an IPv4address,
1732: // backup to just after the last valid character that matches hexseq.
1733: else if (!isHex(testChar)) {
1734: if (testChar == '.' && numDigits < 4 && numDigits > 0
1735: && counter[0] <= 6) {
1736: int back = index - numDigits - 1;
1737: return (back >= start) ? back : (back + 1);
1738: }
1739: return -1;
1740: }
1741: // There can be at most 4 hex digits per group.
1742: else if (++numDigits > 4) {
1743: return -1;
1744: }
1745: }
1746: return (numDigits > 0 && ++counter[0] <= 8) ? end : -1;
1747: }
1748:
1749: /**
1750: * Determine whether a char is a digit.
1751: *
1752: * @return true if the char is betweeen '0' and '9', false otherwise
1753: */
1754: private static boolean isDigit(char p_char) {
1755: return p_char >= '0' && p_char <= '9';
1756: }
1757:
1758: /**
1759: * Determine whether a character is a hexadecimal character.
1760: *
1761: * @return true if the char is betweeen '0' and '9', 'a' and 'f' or 'A' and 'F', false otherwise
1762: */
1763: private static boolean isHex(char p_char) {
1764: return (p_char <= 'f' && (fgLookupTable[p_char] & ASCII_HEX_CHARACTERS) != 0);
1765: }
1766:
1767: /**
1768: * Determine whether a char is an alphabetic character: a-z or A-Z
1769: *
1770: * @return true if the char is alphabetic, false otherwise
1771: */
1772: private static boolean isAlpha(char p_char) {
1773: return ((p_char >= 'a' && p_char <= 'z') || (p_char >= 'A' && p_char <= 'Z'));
1774: }
1775:
1776: /**
1777: * Determine whether a char is an alphanumeric: 0-9, a-z or A-Z
1778: *
1779: * @return true if the char is alphanumeric, false otherwise
1780: */
1781: private static boolean isAlphanum(char p_char) {
1782: return (p_char <= 'z' && (fgLookupTable[p_char] & MASK_ALPHA_NUMERIC) != 0);
1783: }
1784:
1785: /**
1786: * Determine whether a char is a URI character (reserved or unreserved, not including '%' for
1787: * escaped octets).
1788: *
1789: * @return true if the char is a URI character, false otherwise
1790: */
1791: private static boolean isURICharacter(char p_char) {
1792: return (p_char <= '~' && (fgLookupTable[p_char] & MASK_URI_CHARACTER) != 0);
1793: }
1794:
1795: /**
1796: * Determine whether a char is a scheme character.
1797: *
1798: * @return true if the char is a scheme character, false otherwise
1799: */
1800: private static boolean isSchemeCharacter(char p_char) {
1801: return (p_char <= 'z' && (fgLookupTable[p_char] & MASK_SCHEME_CHARACTER) != 0);
1802: }
1803:
1804: /**
1805: * Determine whether a char is a userinfo character.
1806: *
1807: * @return true if the char is a userinfo character, false otherwise
1808: */
1809: private static boolean isUserinfoCharacter(char p_char) {
1810: return (p_char <= 'z' && (fgLookupTable[p_char] & MASK_USERINFO_CHARACTER) != 0);
1811: }
1812:
1813: /**
1814: * Determine whether a char is a path character.
1815: *
1816: * @return true if the char is a path character, false otherwise
1817: */
1818: private static boolean isPathCharacter(char p_char) {
1819: return (p_char <= '~' && (fgLookupTable[p_char] & MASK_PATH_CHARACTER) != 0);
1820: }
1821:
1822: /**
1823: * Determine whether a given string contains only URI characters (also
1824: * called "uric" in RFC 2396). uric consist of all reserved
1825: * characters, unreserved characters and escaped characters.
1826: *
1827: * @return true if the string is comprised of uric, false otherwise
1828: */
1829: private static boolean isURIString(String p_uric) {
1830: if (p_uric == null) {
1831: return false;
1832: }
1833: int end = p_uric.length();
1834: char testChar = '\0';
1835: for (int i = 0; i < end; i++) {
1836: testChar = p_uric.charAt(i);
1837: if (testChar == '%') {
1838: if (i + 2 >= end || !isHex(p_uric.charAt(i + 1))
1839: || !isHex(p_uric.charAt(i + 2))) {
1840: return false;
1841: } else {
1842: i += 2;
1843: continue;
1844: }
1845: }
1846: if (!isURICharacter(testChar)) {
1847: return false;
1848: }
1849: }
1850: return true;
1851: }
1852: }
|