private int parseVerboseInt(String input) {
 			String loadedString = String.format("%s", input);
 			boolean negative = false;
 			int base = 10;
 			int shift = 3;
 			int retVal = -1;
 			if (input.charAt(0) == '-') {
 				negative = true;
 				input = input.substring(1);
 			}
 			if (input.indexOf("0x") == 0) {
 				base = 16;
 				input = input.substring(2);
 			}
 			if (input.indexOf("b") == input.length() - 1) {
 				shift = 0;
 				input = input.substring(0, input.length() - 1);
 			}
 			try {
 				retVal = Integer.parseInt(input, base);
 			} catch (Exception e) {
 				addGeneralError(loadedString);
 				validComponent = false;
 			}
 			if (validComponent) {
 				retVal <<= shift;
 				if (negative)
 					retVal = 0 - retVal;
 			}
 			return retVal;
 		}
Example #2
0
        /**
         * Canonicalize the path, i.e. remove ".." and "." occurences.
         *
         * @param path the path to be canonicalized
         * @return the canonicalized path
         */
        public static String canonicalizePath(String path)
        {
            int dirIndex;

            while ((dirIndex = path.indexOf("/./")) >= 0)
            { //$NON-NLS-1$
                path = path.substring(0, dirIndex + 1)
                        + path.substring(dirIndex + 3);
            }

            if (path.endsWith("/."))
            { //$NON-NLS-1$
                path = path.substring(0, path.length() - 1);
            }

            while ((dirIndex = path.indexOf("/../")) >= 0)
            { //$NON-NLS-1$
                if (dirIndex != 0)
                {
                    path = path.substring(0, path
                            .lastIndexOf('/', dirIndex - 1))
                            + path.substring(dirIndex + 3);
                }
                else
                {
                    path = path.substring(dirIndex + 3);
                }
            }

            if (path.endsWith("/..") && path.length() > 3)
            { //$NON-NLS-1$
                path = path.substring(0, path.lastIndexOf('/',
                        path.length() - 4) + 1);
            }
            return path;
        }
        internal const String encoding = "utf-8"; //$NON-NLS-1$

        #endregion Fields

        #region Methods

        /**
         * All characters except letters ('a'..'z', 'A'..'Z') and numbers ('0'..'9')
         * and legal characters are converted into their hexidecimal value prepended
         * by '%'.
         * <p>
         * For example: '#' -> %23
         * Other characters, which are unicode chars that are not US-ASCII, and are
         * not ISO Control or are not ISO Space chars, are preserved.
         * <p>
         * Called from {@code URI.quoteComponent()} (for multiple argument
         * constructors)
         *
         * @param s
         *            java.lang.String the string to be converted
         * @param legal
         *            java.lang.String the characters allowed to be preserved in the
         *            string s
         * @return java.lang.String the converted string
         */
        internal static String quoteIllegal(String s, String legal)
        {
            //throws UnsupportedEncodingException {
            StringBuilder buf = new StringBuilder();
            for (int i = 0; i < s.length(); i++) {
                char ch = s.charAt(i);
                if ((ch >= 'a' && ch <= 'z')
                        || (ch >= 'A' && ch <= 'Z')
                        || (ch >= '0' && ch <= '9')
                        || legal.indexOf(ch) > -1
                        || (ch > 127 && !java.lang.Character.isSpaceChar(ch) && !java.lang.Character
                                .isISOControl(ch))) {
                    buf.append(ch);
                } else {
                    byte[] bytes = new String(new char[] { ch }).getBytes(encoding);
                    for (int j = 0; j < bytes.Length; j++) {
                        buf.append('%');
                        buf.append(digits.charAt((bytes[j] & 0xf0) >> 4));
                        buf.append(digits.charAt(bytes[j] & 0xf));
                    }
                }
            }
            return buf.toString();
        }
Example #4
0
 protected internal virtual String convertPattern(String template, String fromChars, String toChars,
         bool check)
 {
     if (!check && fromChars.equals(toChars)) {
         return template;
     }
     bool quote = false;
     StringBuilder output = new StringBuilder();
     int length = template.length();
     for (int i = 0; i < length; i++) {
         int index;
         char next = template.charAt(i);
         if (next == '\'') {
             quote = !quote;
         }
         if (!quote && (index = fromChars.indexOf(next)) != -1) {
             output.append(toChars.charAt(index));
         } else if (check
                 && !quote
                 && ((next >= 'a' && next <= 'z') || (next >= 'A' && next <= 'Z'))) {
             // text.05=Invalid pattern char {0} in {1}
             throw new java.lang.IllegalArgumentException("Invalid pattern char "+next+" in "+ template); //$NON-NLS-1$
         } else {
             output.append(next);
         }
     }
     if (quote) {
         // text.04=Unterminated quote
         throw new java.lang.IllegalArgumentException("Unterminated quote"); //$NON-NLS-1$
     }
     return output.toString();
 }
Example #5
0
        static String getHostFromUrl( String strUrl )
        {
            int nHttp = strUrl.indexOf("://");
            if ( nHttp < 0 )
                nHttp = strUrl.indexOf(":\\\\");

            int nStartSrv = 0;
            if ( nHttp >= 0 )
                nStartSrv = nHttp + 3;

            int nEndSrv = strUrl.indexOf('/', nStartSrv);
            if ( nEndSrv < 0 )
                nEndSrv = strUrl.indexOf('\\', nStartSrv);

            int nSrvLen = nEndSrv >= 0 ? nEndSrv + 1 : strUrl.length();
            return strUrl.substring(nSrvLen);
        }    
Example #6
0
        /**
         * Transform the pattern to the valid file name, replacing any patterns, and
         * applying generation and uniqueID if present
         *
         * @param gen
         *            generation of this file
         * @return transformed filename ready for use
         */
        private String parseFileName(int gen)
        {
            int cur = 0;
            int next = 0;
            bool hasUniqueID = false;
            bool hasGeneration = false;

            // TODO privilege code?
            String homePath = java.lang.SystemJ.getProperty("user.home"); //$NON-NLS-1$
            if (homePath == null) {
            throw new java.lang.NullPointerException();
            }
            bool homePathHasSepEnd = homePath.endsWith(java.io.File.separator);

            String tempPath = java.lang.SystemJ.getProperty("java.io.tmpdir"); //$NON-NLS-1$
            tempPath = tempPath == null ? homePath : tempPath;
            bool tempPathHasSepEnd = tempPath.endsWith(java.io.File.separator);

            java.lang.StringBuilder sb = new java.lang.StringBuilder();
            pattern = pattern.replace('/', java.io.File.separatorChar);

            char[] value = pattern.toCharArray();
            while ((next = pattern.indexOf('%', cur)) >= 0) {
            if (++next < pattern.length()) {
                switch (value[next]) {
                    case 'g':
                        sb.append(value, cur, next - cur - 1).append(gen);
                        hasGeneration = true;
                        break;
                    case 'u':
                        sb.append(value, cur, next - cur - 1).append(uniqueID);
                        hasUniqueID = true;
                        break;
                    case 't':
                        /*
                         * we should probably try to do something cute here like
                         * lookahead for adjacent '/'
                         */
                        sb.append(value, cur, next - cur - 1).append(tempPath);
                        if (!tempPathHasSepEnd) {
                            sb.append(java.io.File.separator);
                        }
                        break;
                    case 'h':
                        sb.append(value, cur, next - cur - 1).append(homePath);
                        if (!homePathHasSepEnd) {
                            sb.append(java.io.File.separator);
                        }
                        break;
                    case '%':
                        sb.append(value, cur, next - cur - 1).append('%');
                        break;
                    default:
                        sb.append(value, cur, next - cur);
                        break;
                }
                cur = ++next;
            } else {
                // fail silently
            }
            }

            sb.append(value, cur, value.Length - cur);

            if (!hasGeneration && count > 1) {
            sb.append(".").append(gen); //$NON-NLS-1$
            }

            if (!hasUniqueID && uniqueID > 0) {
            sb.append(".").append(uniqueID); //$NON-NLS-1$
            }

            return sb.toString();
        }
Example #7
0
        /**
         * Creates a new URI instance using the given arguments. This constructor
         * first creates a temporary URI string from the given components. This
         * string will be parsed later on to create the URI instance.
         * <p/>
         * {@code [scheme:][[email protected]]host[:port][path][?query][#fragment]}
         *
         * @param scheme
         *            the scheme part of the URI.
         * @param userinfo
         *            the user information of the URI for authentication and
         *            authorization.
         * @param host
         *            the host name of the URI.
         * @param port
         *            the port number of the URI.
         * @param path
         *            the path to the resource on the host.
         * @param query
         *            the query part of the URI to specify parameters for the
         *            resource.
         * @param fragment
         *            the fragment part of the URI.
         * @throws URISyntaxException
         *             if the temporary created string doesn't fit to the
         *             specification RFC2396 or could not be parsed correctly.
         */
        public URI(String scheme, String userinfo, String host, int port,
                String path, String query, String fragment)
        {
            //throws URISyntaxException {
            StringBuilder uri = new StringBuilder();
            try {

                if (scheme == null && userinfo == null && host == null && path == null
                        && query == null && fragment == null) {
                delegateInstance = new Uri (uri.ToString());
                    return;
                }

                if (scheme != null && path != null && path.length() > 0
                        && path.charAt(0) != '/') {
                    throw new URISyntaxException(path, "Relative path"); //$NON-NLS-1$
                }

                if (scheme != null) {
                    uri.append(scheme);
                    uri.append(':');
                }

                if (userinfo != null || host != null || port != -1) {
                    uri.append("//"); //$NON-NLS-1$
                }

                if (userinfo != null) {
                    // QUOTE ILLEGAL CHARACTERS in userinfo
                    uri.append(quoteComponent(userinfo, someLegal));
                    uri.append('@');
                }

                if (host != null) {
                    // check for ipv6 addresses that hasn't been enclosed
                    // in square brackets
                    if (host.indexOf(':') != -1 && host.indexOf(']') == -1
                            && host.indexOf('[') == -1) {
                        host = "[" + host + "]"; //$NON-NLS-1$ //$NON-NLS-2$
                    }
                    uri.append(host);
                }

                if (port != -1) {
                    uri.append(':');
                    uri.append(port);
                }

                if (path != null) {
                    // QUOTE ILLEGAL CHARS
                    uri.append(quoteComponent(path, "/@" + someLegal)); //$NON-NLS-1$
                }

                if (query != null) {
                    uri.append('?');
                    // QUOTE ILLEGAL CHARS
                    uri.append(quoteComponent(query, allLegal));
                }

                if (fragment != null) {
                    // QUOTE ILLEGAL CHARS
                    uri.append('#');
                    uri.append(quoteComponent(fragment, allLegal));
                }
                delegateInstance = new Uri (uri.ToString());
            }
            catch (ArgumentNullException ane) {
                throw new java.lang.NullPointerException(ane.getMessage());
            }
            catch (UriFormatException ufe) {
                throw new URISyntaxException (uri.ToString(),ufe.Message);
            }
        }
Example #8
0
 /**
  * Returns the array of providers which meet the user supplied string
  * filter. The specified filter must be supplied in one of two formats:
  * <nl>
  * <li> CRYPTO_SERVICE_NAME.ALGORITHM_OR_TYPE</li>
  * <p/>
  * (for example: "MessageDigest.SHA")
  * <li> CRYPTO_SERVICE_NAME.ALGORITHM_OR_TYPE</li>
  * ATTR_NAME:ATTR_VALUE
  * <p/>
  * (for example: "Signature.MD2withRSA KeySize:512")
  * </nl>
  *
  * @param filter
  *            case-insensitive filter.
  * @return the providers which meet the user supplied string filter {@code
  *         filter}. A {@code null} value signifies that none of the
  *         installed providers meets the filter specification.
  * @throws InvalidParameterException
  *             if an unusable filter is supplied.
  * @throws NullPointerException
  *             if {@code filter} is {@code null}.
  */
 public static Provider[] getProviders(String filter)
 {
     if (filter == null)
     {
         throw new java.lang.NullPointerException("The filter is null"); //$NON-NLS-1$
     }
     if (filter.length() == 0)
     {
         throw new InvalidParameterException("The filter is not in the required format"); //$NON-NLS-1$
     }
     java.util.HashMap<String, String> hm = new java.util.HashMap<String, String>();
     int i = filter.indexOf(':');
     if ((i == filter.length() - 1) || (i == 0))
     {
         throw new InvalidParameterException("The filter is not in the required format"); //$NON-NLS-1$
     }
     if (i < 1)
     {
         hm.put(filter, ""); //$NON-NLS-1$
     }
     else
     {
         hm.put(filter.substring(0, i), filter.substring(i + 1));
     }
     return getProviders(hm);
 }
        /// <summary>
        /// Internal helper method for parsing INFO files line by line.
        /// </summary>
        ///
        private BoostInfoTree parseLine(String line, BoostInfoTree context)
        {
            // Skip blank lines and comments.
            int commentStart = line.indexOf(';');
            if (commentStart >= 0)
                line = line.Substring(0,(commentStart)-(0)).trim();
            if (line.Length == 0)
                return context;

            // Usually we are expecting key and optional value.
            // Use ArrayList without generics so it works with older Java compilers.
            ArrayList<String> strings = new ArrayList<String>();
            shlex_split(line, strings);
            bool isSectionStart = false;
            bool isSectionEnd = false;
            for (int i = 0; i < strings.Count; ++i) {
                isSectionStart = (isSectionStart || "{".equals(strings[i]));
                isSectionEnd = (isSectionEnd || "}".equals(strings[i]));
            }

            if (!isSectionStart && !isSectionEnd) {
                String key = strings[0];
                String val = "";
                if (strings.Count > 1)
                    val = strings[1];

                // If it is an "#include", load the new file instead of inserting keys.
                if ("#include".equals(key)) {
                    TextReader stream = new FileReader(val);
                    // Use "try/finally instead of "try-with-resources" or "using"
                    // which are not supported before Java 7.
                    try {
                        context = read(stream, context);
                    } finally {
                        stream.close();
                    }
                } else
                    context.createSubtree(key, val);

                return context;
            }

            // OK, who is the joker who put a { on the same line as the key name?!
            int sectionStart = line.indexOf('{');
            if (sectionStart > 0) {
                String firstPart = line.Substring(0,(sectionStart)-(0));
                String secondPart = line.Substring(sectionStart);

                BoostInfoTree ctx = parseLine(firstPart, context);
                return parseLine(secondPart, ctx);
            }

            // If we encounter a {, we are beginning a new context.
            // TODO: Error if there was already a subcontext here.
            if (line[0] == '{') {
                context = context.getLastChild();
                return context;
            }

            // If we encounter a }, we are ending a list context.
            if (line[0] == '}') {
                context = context.getParent();
                return context;
            }

            throw new Exception("BoostInfoParser: input line is malformed");
        }
Example #10
0
 /*
  * ----------------------------------------------------------- Constructors
  * -----------------------------------------------------------
  */
 /**
  * Constructs a new {@code AbstractPreferences} instance using the given
  * parent node and node name.
  *
  * @param parent
  *            the parent node of the new node or {@code null} to indicate
  *            that the new node is a root node.
  * @param name
  *            the name of the new node or an empty string to indicate that
  *            this node is called "root".
  * @throws IllegalArgumentException
  *             if the name contains a slash character or is empty if {@code
  *             parent} is not {@code null}.
  */
 protected AbstractPreferences(AbstractPreferences parent, String name)
 {
     if ((null == parent ^ name.length() == 0) || name.indexOf("/") >= 0) { //$NON-NLS-1$
     throw new java.lang.IllegalArgumentException();
     }
     root = null == parent ? this : parent.root;
     nodeChangeListeners = new LinkedList<EventListener>();
     preferenceChangeListeners = new LinkedList<EventListener>();
     isRemovedJ = false;
     cachedNode = new HashMap<String, AbstractPreferences>();
     nodeName = name;
     parentPref = parent;
     lockJ = new Lock();
     userNode = root.userNode;
 }
Example #11
0
        /**
         * Validate a string by checking if it contains any characters other than:
         * 1. letters ('a'..'z', 'A'..'Z') 2. numbers ('0'..'9') 3. characters in
         * the legalset parameter 4. others (unicode characters that are not in
         * US-ASCII set, and are not ISO Control or are not ISO Space characters)
         * <p>
         * called from {@code URI.Helper.parseURI()} to validate each component
         *
         * @param s
         *            {@code java.lang.String} the string to be validated
         * @param legal
         *            {@code java.lang.String} the characters allowed in the String
         *            s
         */
        internal static void validate(String s, String legal)
        {
            // throws URISyntaxException {
            for (int i = 0; i < s.length();) {
                char ch = s.charAt(i);
                if (ch == '%') {
                    do {
                        if (i + 2 >= s.length()) {
                            throw new URISyntaxException(s, "Incomplete % sequence",i);
                        }
                        int d1 = java.lang.Character.digit(s.charAt(i + 1), 16);
                        int d2 = java.lang.Character.digit(s.charAt(i + 2), 16);
                        if (d1 == -1 || d2 == -1) {
                            throw new URISyntaxException(s, "Invalid % sequence ("+s.substring(i, i + 3)+")",i);
                        }

                        i += 3;
                    } while (i < s.length() && s.charAt(i) == '%');

                    continue;
                }
                if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
                        || (ch >= '0' && ch <= '9') || legal.indexOf(ch) > -1 || (ch > 127
                        && !java.lang.Character.isSpaceChar(ch) && !java.lang.Character
                        .isISOControl(ch)))) {
                    throw new URISyntaxException(s, "Illegal character", i); //$NON-NLS-1$
                }
                i++;
            }
        }
Example #12
0
 internal static void validateSimple(String s, String legal)
 {
     //throws URISyntaxException {
     for (int i = 0; i < s.length();) {
         char ch = s.charAt(i);
         if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
                 || (ch >= '0' && ch <= '9') || legal.indexOf(ch) > -1)) {
             throw new URISyntaxException(s, "Illegal character", i); //$NON-NLS-1$
         }
         i++;
     }
 }
Example #13
0
 private String pathFromUrl(String url)
 {
     if (0 == url.IndexOf(REQUEST_URL_SCHEME_PREFIX))
     {
         return url.substring(url.indexOf(":") + 1);
     }
     return url;
 }
Example #14
0
 /**
  * Creates a {@code Date} from a string representation of a date in SQL
  * format.
  *
  * @param dateString
  *            the string representation of a date in SQL format - " {@code
  *            yyyy-mm-dd}".
  * @return the {@code Date} object.
  * @throws IllegalArgumentException
  *             if the format of the supplied string does not match the SQL
  *             format.
  */
 public static Date valueOf(String dateString)
 {
     if (dateString == null)
     {
         throw new java.lang.IllegalArgumentException();
     }
     int firstIndex = dateString.indexOf('-');
     int secondIndex = dateString.indexOf('-', firstIndex + 1);
     // secondIndex == -1 means none or only one separator '-' has been
     // found.
     // The string is separated into three parts by two separator characters,
     // if the first or the third part is null string, we should throw
     // IllegalArgumentException to follow RI
     if (secondIndex == -1 || firstIndex == 0
             || secondIndex + 1 == dateString.length())
     {
         throw new java.lang.IllegalArgumentException();
     }
     // parse each part of the string
     int year = java.lang.Integer.parseInt(dateString.substring(0, firstIndex));
     int month = java.lang.Integer.parseInt(dateString.substring(firstIndex + 1,
             secondIndex));
     int day = java.lang.Integer.parseInt(dateString.substring(secondIndex + 1,
             dateString.length()));
     return new Date(year - 1900, month - 1, day);
 }
Example #15
0
 /**
  * Creates a {@code Time} object from a string holding a time represented in
  * JDBC escape format: {@code hh:mm:ss}.
  * <p/>
  * An exception occurs if the input string does not comply with this format.
  *
  * @param timeString
  *            A String representing the time value in JDBC escape format:
  *            {@code hh:mm:ss}.
  * @return The {@code Time} object set to a time corresponding to the given
  *         time.
  * @throws IllegalArgumentException
  *             if the supplied time string is not in JDBC escape format.
  */
 public static Time valueOf(String timeString)
 {
     if (timeString == null)
     {
         throw new java.lang.IllegalArgumentException();
     }
     int firstIndex = timeString.indexOf(':');
     int secondIndex = timeString.indexOf(':', firstIndex + 1);
     // secondIndex == -1 means none or only one separator '-' has been
     // found.
     // The string is separated into three parts by two separator characters,
     // if the first or the third part is null string, we should throw
     // IllegalArgumentException to follow RI
     if (secondIndex == -1 || firstIndex == 0
             || secondIndex + 1 == timeString.length())
     {
         throw new java.lang.IllegalArgumentException();
     }
     // parse each part of the string
     int hour = java.lang.Integer.parseInt(timeString.substring(0, firstIndex));
     int minute = java.lang.Integer.parseInt(timeString.substring(firstIndex + 1,
             secondIndex));
     int second = java.lang.Integer.parseInt(timeString.substring(secondIndex + 1,
             timeString.length()));
     return new Time(hour, minute, second);
 }
Example #16
0
            public CServerCommand(CHttpServer Parent, CRoute route,
                String method, String uri, IDictionary headers, IDictionary data, int nCommand, String strAjaxContext, int tabIndex)
            {
                m_Parent = Parent;
                m_method = (null != method) ? method.toUpperCase() : "GET";
                m_uri = (0 <= uri.indexOf('?')) ? uri.substring(0, uri.indexOf('?')) : uri;
                m_route = route;
                m_nCommand = nCommand;
                m_strAjaxContext = strAjaxContext;
                m_iTabIndex = tabIndex;

                m_body = "";

                m_headers = new Dictionary<String, String>();
                if (null != headers)
                {
                    foreach (object key in headers.Keys)
                    {
                        m_headers[key.ToString()] = headers[key].ToString();
                    }
                }

                // Query parameters from URL are added first, then data parameters added.
                m_query = (0 <= uri.indexOf('?')) ? uri.substring(uri.indexOf('?') + 1) : "";
                if (null != data)
                {
                    StringBuilder sb = new StringBuilder(m_query);
                    foreach (object key in data.Keys)
                    {
                        if (0 < sb.Length) sb.Append("&");
                        sb.Append(key.ToString() + "=" + (null != data[key] ? data[key].ToString() : ""));
                    }
                    m_query = sb.ToString();
                }
            }
Example #17
0
            /**
             * Process an XML qualified name in this context.
             *
             * @param qName The XML qualified name.
             * @param isAttribute true if this is an attribute name.
             * @return An array of three strings containing the
             *         URI part (or empty string), the local part,
             *         and the raw name, all internalized, or null
             *         if there is an undeclared prefix.
             * @see org.xml.sax.helpers.NamespaceSupport#processName
             */
            internal String[] processName(String qName, bool isAttribute)
            {
                String[] name;
                java.util.Hashtable<Object,Object> table;

                    // detect errors in call sequence
                declsOK = false;

                // Select the appropriate table.
                if (isAttribute) {
                table = attributeNameTable;
                } else {
                table = elementNameTable;
                }

                // Start by looking in the cache, and
                // return immediately if the name
                // is already known in this content
                name = (String[])table.get(qName);
                if (name != null) {
                return name;
                }

                // We haven't seen this name in this
                // context before.  Maybe in the parent
                // context, but we can't assume prefix
                // bindings are the same.
                name = new String[3];
                name[2] = qName.intern();
                int index = qName.indexOf(':');

                // No prefix.
                if (index == -1) {
                if (isAttribute) {
                if (qName == "xmlns" && outer.namespaceDeclUris)
                name[0] = NSDECL;
                else
                name[0] = "";
                } else if (defaultNS == null) {
                name[0] = "";
                } else {
                name[0] = defaultNS;
                }
                name[1] = name[2];
                }

                // Prefix
                else {
                String prefix = qName.substring(0, index);
                String local = qName.substring(index+1);
                String uri;
                if ("".equals(prefix)) {
                uri = defaultNS;
                } else {
                uri = (String)prefixTable.get(prefix);
                }
                if (uri == null
                || (!isAttribute && "xmlns".equals (prefix))) {
                return null;
                }
                name[0] = uri;
                name[1] = local.intern();
                }

                // Save in the cache for future use.
                // (Could be shared with parent context...)
                table.put(name[2], name);
                return name;
            }
Example #18
0
        static String addUniqueParam(String strUrl)
        {
            //Random RND = new Random();
            //RND.Next(10000);
            String strUnique = DateTime.Now.ToFileTime().ToString();

            int nQuest = strUrl.indexOf('?');
            if (nQuest >= 0)
                strUrl += "&";
            else
                strUrl += "?";

            strUrl += "wp7_nocache_param=" + strUnique;

            return strUrl; 
        }
Example #19
0
        /**
         * Creates a new URL to the specified resource {@code spec}. This URL is
         * relative to the given {@code context}. The {@code handler} will be used
         * to parse the URL string representation. If this argument is {@code null}
         * the default {@code URLStreamHandler} will be used. If the protocol of the
         * parsed URL does not match with the protocol of the context URL, then the
         * newly created URL is absolute and bases only on the given URL represented
         * by {@code spec}. Otherwise the protocol is defined by the context URL.
         *
         * @param context
         *            the URL which is used as the context.
         * @param spec
         *            the URL string representation which has to be parsed.
         * @param handler
         *            the specific stream handler to be used by this URL.
         * @throws MalformedURLException
         *             if the given string {@code spec} could not be parsed as a URL
         *             or an invalid protocol has been found.
         */
        public URL(URL context, String spec, URLStreamHandler handler)
        {
            //throws MalformedURLException {
            if (handler != null)
            {
                java.lang.SecurityManager sm = java.lang.SystemJ.getSecurityManager();
                if (sm != null)
                {
                    sm.checkPermission(specifyStreamHandlerPermission);
                }
                strmHandler = handler;
            }

            if (spec == null)
            {
                throw new MalformedURLException();
            }
            spec = spec.trim();

            // The spec includes a protocol if it includes a colon character
            // before the first occurrence of a slash character. Note that,
            // "protocol" is the field which holds this URLs protocol.
            int index;
            try
            {
                index = spec.indexOf(':');
            }
            catch (java.lang.NullPointerException e)
            {
                throw new MalformedURLException(e.toString());
            }
            int startIPv6Addr = spec.indexOf('[');
            if (index >= 0)
            {
                if ((startIPv6Addr == -1) || (index < startIPv6Addr))
                {
                    protocol = spec.substring(0, index);
                    // According to RFC 2396 scheme part should match
                    // the following expression:
                    // alpha *( alpha | digit | "+" | "-" | "." )
                    char c = protocol.charAt(0);
                    bool valid = ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
                    for (int i = 1; valid && (i < protocol.length()); i++)
                    {
                        c = protocol.charAt(i);
                        valid = ('a' <= c && c <= 'z') ||
                                ('A' <= c && c <= 'Z') ||
                                ('0' <= c && c <= '9') ||
                                (c == '+') ||
                                (c == '-') ||
                                (c == '.');
                    }
                    if (!valid)
                    {
                        protocol = null;
                        index = -1;
                    }
                    else
                    {
                        // Ignore case in protocol names.
                        // Scheme is defined by ASCII characters.
                        protocol = Util.toASCIILowerCase(protocol);
                    }
                }
            }

            if (protocol != null)
            {
                // If the context was specified, and it had the same protocol
                // as the spec, then fill in the receiver's slots from the values
                // in the context but still allow them to be over-ridden later
                // by the values in the spec.
                if (context != null && protocol.equals(context.getProtocol()))
                {
                    String cPath = context.getPath();
                    if (cPath != null && cPath.startsWith("/"))
                    { //$NON-NLS-1$
                        set(protocol, context.getHost(), context.getPort(), context
                                .getAuthority(), context.getUserInfo(), cPath,
                                context.getQuery(), null);
                    }
                    if (strmHandler == null)
                    {
                        strmHandler = context.strmHandler;
                    }
                }
            }
            else
            {
                // If the spec did not include a protocol, then the context
                // *must* be specified. Fill in the receiver's slots from the
                // values in the context, but still allow them to be over-ridden
                // by the values in the ("relative") spec.
                if (context == null)
                {
                    throw new MalformedURLException("Protocol not found: " + spec); //$NON-NLS-1$
                }
                set(context.getProtocol(), context.getHost(), context.getPort(),
                        context.getAuthority(), context.getUserInfo(), context
                                .getPath(), context.getQuery(), null);
                if (strmHandler == null)
                {
                    strmHandler = context.strmHandler;
                }
            }

            // If the stream handler has not been determined, set it
            // to the default for the specified protocol.
            if (strmHandler == null)
            {
                setupStreamHandler();
                if (strmHandler == null)
                {
                    throw new MalformedURLException("Unknown protocol: " + protocol); //$NON-NLS-1$
                }
            }

            // Let the handler parse the URL. If the handler throws
            // any exception, throw MalformedURLException instead.
            //
            // Note: We want "index" to be the index of the start of the scheme
            // specific part of the URL. At this point, it will be either
            // -1 or the index of the colon after the protocol, so we
            // increment it to point at either character 0 or the character
            // after the colon.
            try
            {
                strmHandler.parseURL(this, spec, ++index, spec.length());
            }
            catch (Exception e)
            {
                throw new MalformedURLException(e.toString());
            }

            if (port < -1)
            {
                throw new MalformedURLException("Port out of range: " + port); //$NON-NLS-1$
            }
        }
Example #20
0
        public void set(String uri)
        {
            clear();

            uri = uri.trim();
            if (uri.Length == 0)
                return;

            int iColon = uri.indexOf(':');
            if (iColon >= 0) {
                // Make sure the colon came before a '/'.
                int iFirstSlash = uri.indexOf('/');
                if (iFirstSlash < 0 || iColon < iFirstSlash)
                    // Omit the leading protocol such as ndn:
                    uri = uri.Substring(iColon + 1).trim();
            }

            // Trim the leading slash and possibly the authority.
            if (uri[0] == '/') {
                if (uri.Length >= 2 && uri[1] == '/') {
                    // Strip the authority following "//".
                    int iAfterAuthority = uri.indexOf('/', 2);
                    if (iAfterAuthority < 0)
                        // Unusual case: there was only an authority.
                        return;
                    else
                        uri = uri.Substring(iAfterAuthority + 1).trim();
                } else
                    uri = uri.Substring(1).trim();
            }

            int iComponentStart = 0;

            // Unescape the components.
            String sha256digestPrefix = "sha256digest=";
            while (iComponentStart < uri.Length) {
                int iComponentEnd = ILOG.J2CsMapping.Util.StringUtil.IndexOf(uri,"/",iComponentStart);
                if (iComponentEnd < 0)
                    iComponentEnd = uri.Length;

                Name.Component  component;
                if (sha256digestPrefix.regionMatches(0, uri, iComponentStart,
                        sha256digestPrefix.Length)) {
                    try {
                        component = net.named_data.jndn.Name.Component.fromImplicitSha256Digest(fromHex(uri,
                                iComponentStart + sha256digestPrefix.Length,
                                iComponentEnd));
                    } catch (EncodingException ex) {
                        throw new Exception(ex.Message);
                    }
                } else
                    component = new Name.Component (fromEscapedString(uri,
                            iComponentStart, iComponentEnd));

                // Ignore illegal components.  This also gets rid of a trailing '/'.
                if (!component.getValue().isNull())
                    append(component);

                iComponentStart = iComponentEnd + 1;
            }
        }
Example #21
0
 /// <summary>
 /// This method is used to append the provided text and then it
 /// converts the buffered text to return the corrosponding text.
 /// The contents of the buffer remain unchanged after the value
 /// is buffered. It must be cleared if used as replacement only.
 /// </summary>
 /// <param name="value">
 /// this is the value to append to the buffer
 /// </param>
 /// <returns>
 /// returns the value of the buffer after the append
 /// </returns>
 public String Process(String value) {
    if(value.indexOf('$') < 0) {
       return value;
    }
    try {
       source.Append(value);
       Parse();
       return text.ToString();
    }finally {
       Clear();
    }
 }
Example #22
0
        /**
         * &lt;p&gt;&lt;code&gt;QName&lt;/code&gt; derived from parsing the formatted
         * &lt;code&gt;String&lt;/code&gt;.&lt;/p&gt;
         *
         * &lt;p&gt;If the &lt;code&gt;String&lt;/code&gt; is &lt;code&gt;null&lt;/code&gt; or does not conform to
         * {@link #toString() QName.toString()} formatting, an
         * &lt;code&gt;IllegalArgumentException&lt;/code&gt; is thrown.&lt;/p&gt;
         *
         * &lt;p&gt;&lt;em&gt;The &lt;code&gt;String&lt;/code&gt; &lt;strong&gt;MUST&lt;/strong&gt; be in the
         * form returned by {@link #toString() QName.toString()}.&lt;/em&gt;&lt;/p&gt;

         * &lt;p&gt;The commonly accepted way of representing a &lt;code&gt;QName&lt;/code&gt;
         * as a &lt;code&gt;String&lt;/code&gt; was &lt;a href="http://jclark.com/xml/xmlns.htm"&gt;defined&lt;/a&gt;
         * by James Clark.  Although this is not a &lt;em&gt;standard&lt;/em&gt;
         * specification, it is in common use,  e.g. {@link javax.xml.transform.Transformer#setParameter(String name, Object value)}.
         * This implementation parses a &lt;code&gt;String&lt;/code&gt; formatted
         * as: "{" + Namespace URI + "}" + local part.  If the Namespace
         * URI &lt;code&gt;.equals(XMLConstants.NULL_NS_URI)&lt;/code&gt;, only the
         * local part should be provided.&lt;/p&gt;
         *
         * &lt;p&gt;The prefix value &lt;strong&gt;&lt;em&gt;CANNOT&lt;/em&gt;&lt;/strong&gt; be
         * represented in the &lt;code&gt;String&lt;/code&gt; and will be set to
         * {@link javax.xml.XMLConstants#DEFAULT_NS_PREFIX
         * XMLConstants.DEFAULT_NS_PREFIX}.&lt;/p&gt;
         *
         * &lt;p&gt;This method does not do full validation of the resulting
         * &lt;code&gt;QName&lt;/code&gt;.
         * &lt;p&gt;The Namespace URI is not validated as a
         * &lt;a href="http://www.ietf.org/rfc/rfc2396.txt"&gt;URI reference&lt;/a&gt;.
         * The local part is not validated as a
         * &lt;a href="http://www.w3.org/TR/REC-xml-names/#NT-NCName"&gt;NCName&lt;/a&gt;
         * as specified in
         * &lt;a href="http://www.w3.org/TR/REC-xml-names/"&gt;Namespaces in XML&lt;/a&gt;.&lt;/p&gt;
         *
         * @param qNameAsString &lt;code&gt;String&lt;/code&gt; representation
         * of the &lt;code&gt;QName&lt;/code&gt;
         * @return &lt;code&gt;QName&lt;/code&gt; corresponding to the given &lt;code&gt;String&lt;/code&gt;
         * @see #toString() QName.toString()
         */
        public static QName valueOf(String qNameAsString)
        {
            // null is not valid
            if (qNameAsString == null)
            {
                throw new java.lang.IllegalArgumentException("cannot create QName from \"null\" or \"\" String");
            }

            // "" local part is valid to preserve compatible behavior with QName 1.0
            if (qNameAsString.length() == 0)
            {
                return new QName(
                    XMLConstants.NULL_NS_URI,
                    qNameAsString,
                    XMLConstants.DEFAULT_NS_PREFIX);
            }

            // local part only?
            if (qNameAsString.charAt(0) != '{')
            {
                return new QName(
                    XMLConstants.NULL_NS_URI,
                    qNameAsString,
                    XMLConstants.DEFAULT_NS_PREFIX);
            }

            // Namespace URI improperly specified?
            if (qNameAsString.startsWith("{" + XMLConstants.NULL_NS_URI + "}"))
            {
                throw new java.lang.IllegalArgumentException(
                    "Namespace URI .equals(XMLConstants.NULL_NS_URI), "
                    + ".equals(\"" + XMLConstants.NULL_NS_URI + "\"), "
                    + "only the local part, "
                    + "\"" + qNameAsString.substring(2 + XMLConstants.NULL_NS_URI.length()) + "\", "
                    + "should be provided.");
            }

            // Namespace URI and local part specified
            int endOfNamespaceURI = qNameAsString.indexOf('}');
            if (endOfNamespaceURI == -1)
            {
                throw new java.lang.IllegalArgumentException(
                    "cannot create QName from \""
                        + qNameAsString
                        + "\", missing closing \"}\"");
            }
            return new QName(
                qNameAsString.substring(1, endOfNamespaceURI),
                qNameAsString.substring(endOfNamespaceURI + 1),
                XMLConstants.DEFAULT_NS_PREFIX);
        }
Example #23
0
        /**
         * Parses the clear text URL in {@code str} into a URL object. URL strings
         * generally have the following format:
         * <p/>
         * http://www.company.com/java/file1.java#reference
         * <p/>
         * The string is parsed in HTTP format. If the protocol has a different URL
         * format this method must be overridden.
         *
         * @param u
         *            the URL to fill in the parsed clear text URL parts.
         * @param str
         *            the URL string that is to be parsed.
         * @param start
         *            the string position from where to begin parsing.
         * @param end
         *            the string position to stop parsing.
         * @see #toExternalForm
         * @see URL
         */
        protected internal void parseURL(URL u, String str, int start, int end)
        {
            if (end < start || end < 0) {
            // Checks to ensure string index exception ahead of
            // security exception for compatibility.
            if (end <= java.lang.Integer.MIN_VALUE + 1 && (start >= str.length() || start < 0)
                    || str.startsWith("//", start) && str.indexOf('/', start + 2) == -1) { //$NON-NLS-1$
                throw new java.lang.StringIndexOutOfBoundsException(end);
            }
            if (this != u.strmHandler) {
                throw new java.lang.SecurityException();
            }
            return;
            }
            String parseString = str.substring(start, end);
            end -= start;
            int fileIdx = 0;

            // Default is to use info from context
            String host = u.getHost();
            int port = u.getPort();
            String refJ = u.getRef();
            String file = u.getPath();
            String query = u.getQuery();
            String authority = u.getAuthority();
            String userInfo = u.getUserInfo();

            int refIdx = parseString.indexOf('#', 0);
            if (parseString.startsWith("//") && !parseString.startsWith("////")) { //$NON-NLS-1$
            int hostIdx = 2, portIdx = -1;
            port = -1;
            fileIdx = parseString.indexOf('/', hostIdx);
            int questionMarkIndex = parseString.indexOf('?', hostIdx);
            if ((questionMarkIndex != -1)
                    && ((fileIdx == -1) || (fileIdx > questionMarkIndex))) {
                fileIdx = questionMarkIndex;
            }
            if (fileIdx == -1) {
                fileIdx = end;
                // Use default
                file = ""; //$NON-NLS-1$
            }
            int hostEnd = fileIdx;
            if (refIdx != -1 && refIdx < fileIdx) {
                hostEnd = refIdx;
            }
            int userIdx = parseString.lastIndexOf('@', hostEnd);
            authority = parseString.substring(hostIdx, hostEnd);
            if (userIdx > -1) {
                userInfo = parseString.substring(hostIdx, userIdx);
                hostIdx = userIdx + 1;
            }

            portIdx = parseString.indexOf(':', userIdx == -1 ? hostIdx
                    : userIdx);
            int endOfIPv6Addr = parseString.indexOf(']');
            // if there are square braces, ie. IPv6 address, use last ':'
            if (endOfIPv6Addr != -1) {
                try {
                    if (parseString.length() > endOfIPv6Addr + 1) {
                        char c = parseString.charAt(endOfIPv6Addr + 1);
                        if (c == ':') {
                            portIdx = endOfIPv6Addr + 1;
                        } else {
                            portIdx = -1;
                        }
                    } else {
                        portIdx = -1;
                    }
                } catch (Exception e) {
                    // Ignored
                }
            }

            if (portIdx == -1 || portIdx > fileIdx) {
                host = parseString.substring(hostIdx, hostEnd);
            } else {
                host = parseString.substring(hostIdx, portIdx);
                String portString = parseString.substring(portIdx + 1, hostEnd);
                if (portString.length() == 0) {
                    port = -1;
                } else {
                    port = java.lang.Integer.parseInt(portString);
                }
            }
            }

            if (refIdx > -1) {
            refJ = parseString.substring(refIdx + 1, end);
            }
            int fileEnd = (refIdx == -1 ? end : refIdx);

            int queryIdx = parseString.lastIndexOf('?', fileEnd);
            bool canonicalize = false;
            if (queryIdx > -1) {
            query = parseString.substring(queryIdx + 1, fileEnd);
            if (queryIdx == 0 && file != null) {
                if (file.equals("")) { //$NON-NLS-1$
                    file = "/"; //$NON-NLS-1$
                } else if (file.startsWith("/")) { //$NON-NLS-1$
                    canonicalize = true;
                }
                int last = file.lastIndexOf('/') + 1;
                file = file.substring(0, last);
            }
            fileEnd = queryIdx;
            } else
            // Don't inherit query unless only the ref is changed
            if (refIdx != 0) {
            query = null;
            }

            if (fileIdx > -1) {
            if (fileIdx < end && parseString.charAt(fileIdx) == '/') {
                file = parseString.substring(fileIdx, fileEnd);
            } else if (fileEnd > fileIdx) {
                if (file == null) {
                    file = ""; //$NON-NLS-1$
                } else if (file.equals("")) { //$NON-NLS-1$
                    file = "/"; //$NON-NLS-1$
                } else if (file.startsWith("/")) { //$NON-NLS-1$
                    canonicalize = true;
                }
                int last = file.lastIndexOf('/') + 1;
                if (last == 0) {
                    file = parseString.substring(fileIdx, fileEnd);
                } else {
                    file = file.substring(0, last)
                            + parseString.substring(fileIdx, fileEnd);
                }
            }
            }
            if (file == null) {
            file = ""; //$NON-NLS-1$
            }

            if (host == null) {
            host = ""; //$NON-NLS-1$
            }

            if (canonicalize) {
            // modify file if there's any relative referencing
            file = URLUtil.canonicalizePath(file);
            }

            setURL(u, u.getProtocol(), host, port, authority, userInfo, file,
                query, refJ);
        }
Example #24
0
 private void validateName(String name)
 {
     if (name.endsWith("/") && name.length() > 1) { //$NON-NLS-1$
     // prefs.6=Name cannot end with '/'
         throw new java.lang.IllegalArgumentException("Name cannot end with '/'"); //$NON-NLS-1$
     }
     if (name.indexOf("//") >= 0) { //$NON-NLS-1$
     // prefs.7=Name cannot contains consecutive '/'
         throw new java.lang.IllegalArgumentException("Name cannot contains consecutive '/'"); //$NON-NLS-1$
     }
 }
Example #25
0
 /**
  * Returns the numerical representation of the argument.
  *
  * @param actionNames
  *            the action names
  * @return the action mask
  */
 private int getMask(String actionNames)
 {
     int actionInt = 0, head = 0, tail = 0;
     do {
     tail = actionNames.indexOf(",", head); //$NON-NLS-1$
     String action = tail > 0 ? actionNames.substring(head, tail).trim()
             : actionNames.substring(head).trim();
     if (action.equals("read")) { //$NON-NLS-1$
         actionInt |= 8;
     } else if (action.equals("write")) { //$NON-NLS-1$
         actionInt |= 4;
     } else if (action.equals("execute")) { //$NON-NLS-1$
         actionInt |= 2;
     } else if (action.equals("delete")) { //$NON-NLS-1$
         actionInt |= 1;
     } else {
             throw new java.lang.IllegalArgumentException("invalid permission: "+ action); //$NON-NLS-1$
     }
     head = tail + 1;
     } while (tail > 0);
     return actionInt;
 }
Example #26
0
        /**
         * Creates a new URL instance using the given arguments. The URL uses the
         * specified port instead of the default port for the given protocol.
         *
         * @param protocol
         *            the protocol of the new URL.
         * @param host
         *            the host name or IP address of the new URL.
         * @param port
         *            the specific port number of the URL. {@code -1} represents the
         *            default port of the protocol.
         * @param file
         *            the name of the resource.
         * @param handler
         *            the stream handler to be used by this URL.
         * @throws MalformedURLException
         *             if the combination of all arguments do not represent a valid
         *             URL or the protocol is invalid.
         * @throws SecurityException
         *             if {@code handler} is non-{@code null}, and a security
         *             manager is installed that disallows user-defined protocol
         *             handlers.
         */
        public URL(String protocol, String host, int port, String file,
                URLStreamHandler handler)
        {
            // throws MalformedURLException {
            if (port < -1)
            {
                throw new MalformedURLException("Port out of range: " + port); //$NON-NLS-1$
            }

            if (host != null && host.indexOf(":") != -1 && host.charAt(0) != '[')
            { //$NON-NLS-1$
                host = "[" + host + "]"; //$NON-NLS-1$ //$NON-NLS-2$
            }

            if (protocol == null)
            {
                throw new java.lang.NullPointerException("Unknown protocol: " + "null"); //$NON-NLS-1$ //$NON-NLS-2$
            }

            this.protocol = protocol;
            this.host = host;
            this.port = port;

            // Set the fields from the arguments. Handle the case where the
            // passed in "file" includes both a file and a reference part.
            int index = -1;
            index = file.indexOf("#", file.lastIndexOf("/")); //$NON-NLS-1$ //$NON-NLS-2$
            if (index >= 0)
            {
                this.file = file.substring(0, index);
                refJ = file.substring(index + 1);
            }
            else
            {
                this.file = file;
            }
            fixURL(false);

            // Set the stream handler for the URL either to the handler
            // argument if it was specified, or to the default for the
            // receiver's protocol if the handler was null.
            if (handler == null)
            {
                setupStreamHandler();
                if (strmHandler == null)
                {
                    throw new MalformedURLException("Unknown protocol: " + protocol); //$NON-NLS-1$
                }
            }
            else
            {
                java.lang.SecurityManager sm = java.lang.SystemJ.getSecurityManager();
                if (sm != null)
                {
                    sm.checkPermission(specifyStreamHandlerPermission);
                }
                strmHandler = handler;
            }
        }
Example #27
0
        public static String getQueryString(String strUrl)
        {
            int nQuest = strUrl.indexOf('?');
            if (nQuest < 0 )
                return "";

            return strUrl.substring(nQuest + 1);
        }