Ejemplo n.º 1
0
        public static String urlEncode(String fullPath)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            int len = fullPath.length();

            char c;
            for (int index = 0; index < len; index++)
            {
                c = fullPath.charAt(index);
                if (c == '^' || c == '_'
                       || c == '\\' || c == '-'
                       || c == '.'
                       || (c >= 'A' && c <= 'Z')
                       || (c >= 'a' && c <= 'z')
                       || (c >= '0' && c <= '9'))
                {
                    sb.Append(c);
                }
                else
                {
                    sb.Append('%');
                    sb.Append(String.Format("{0:X2}", (int)c));
                }

            }
            return sb.ToString();
        }
 		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;
 		}
Ejemplo n.º 3
0
 /**
  * Returns whether the given source string ends with the suffix, ignoring
  * case and assuming that the strings are ascii encoded.
  *
  * @param source
  *            the string to match.
  * @param suffix
  *            the suffix to test.
  * @return {@code true} if the source does end with the given suffix, or
  *         {@code false} if not.
  */
 public static bool asciiEndsWithIgnoreCase(String source, String suffix)
 {
     int length = suffix.length();
     if (length > source.length()) {
         return false;
     }
     int offset = source.length() - length;
     for (int i = 0; i < length; i++) {
         char c1 = source.charAt(i + offset);
         char c2 = suffix.charAt(i);
         if (c1 != c2 && toASCIIUpperCase(c1) != toASCIIUpperCase(c2)) {
             return false;
         }
     }
     return true;
 }
 public static String toASCIIUpperCase(String s)
 {
     int len = s.length();
     StringBuilder buffer = new StringBuilder(len);
     for (int i = 0; i < len; i++)
     {
         char c = s.charAt(i);
         if ('a' <= c && c <= 'z')
         {
             buffer.append((char)(c - ('a' - 'A')));
         }
         else
         {
             buffer.append(c);
         }
     }
     return buffer.toString();
 }
Ejemplo n.º 5
0
	    /**
	     * Parses <code>source</code> until a non-whitespace character is found.
	     *
	     * @param source the string to parse
	     * @param pos input/ouput parsing parameter.
	     * @return the first non-whitespace character.
	     */
	    public static char parseNextCharacter(String source,
	                                          ParsePosition pos) {
	         int index = pos.getIndex();
	         int n = source.length();
	         char ret = 0;
	
	         if (index < n) {
	             char c;
	             do {
	                 c = source.charAt(index++);
	             } while (Character.isWhitespace(c) && index < n);
	             pos.setIndex(index);
	
	             if (index < n) {
	                 ret = c;
	             }
	         }
	
	         return ret;
	    }
Ejemplo n.º 6
0
        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();
        }
Ejemplo n.º 7
0
 internal long countUTFBytes(String str)
 {
     int utfCount = 0, length = str.length();
     for (int i = 0; i < length; i++) {
         int charValue = str.charAt(i);
         if (charValue > 0 && charValue <= 127) {
             utfCount++;
         } else if (charValue <= 2047) {
             utfCount += 2;
         } else {
             utfCount += 3;
         }
     }
     return utfCount;
 }
Ejemplo n.º 8
0
 protected internal static bool upToWithQuotes(String s, ParsePosition position,
         java.lang.StringBuffer buffer, char stop, char start)
 {
     int index = position.getIndex(), length = s.length(), count = 1;
     bool quote = false;
     while (index < length) {
         char ch = s.charAt(index++);
         if (ch == '\'') {
             quote = !quote;
         }
         if (!quote) {
             if (ch == stop) {
                 count--;
             }
             if (count == 0) {
                 position.setIndex(index);
                 return true;
             }
             if (ch == start) {
                 count++;
             }
         }
         buffer.append(ch);
     }
     // text.07=Unmatched braces in the pattern
     throw new java.lang.IllegalArgumentException("Unmatched braces in the pattern"); //$NON-NLS-1$
 }
Ejemplo n.º 9
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();
 }
Ejemplo n.º 10
0
 static int utf8Count(String value)
 {
     int total = 0;
     for (int i = value.length(); --i >= 0;) {
         char ch = value.charAt(i);
         if (ch < 0x80) {
             total++;
         } else if (ch < 0x800) {
             total += 2;
         } else {
             total += 3;
         }
     }
     return total;
 }
Ejemplo n.º 11
0
 /*
  * Gets private field value by reflection.
  *
  * @param fieldName the field name to be set @param target the object which
  * field to be gotten
  *
 internal static Object getInternalField(String fieldName, Object target) {
     Object value = AccessController
             .doPrivileged(new PrivilegedAction<Object>() {
                 public Object run() {
                     Object result = null;
                     java.lang.reflect.Field field = null;
                     try {
                         field = target.getClass().getDeclaredField(
                                 fieldName);
                         field.setAccessible(true);
                         result = field.get(target);
                     } catch (Exception e1) {
                         return null;
                     }
                     return result;
                 }
             });
     return value;
 }*/
 protected internal static bool upTo(String s, ParsePosition position,
         java.lang.StringBuffer buffer, char stop)
 {
     int index = position.getIndex(), length = s.length();
     bool lastQuote = false, quote = false;
     while (index < length) {
         char ch = s.charAt(index++);
         if (ch == '\'') {
             if (lastQuote) {
                 buffer.append('\'');
             }
             quote = !quote;
             lastQuote = true;
         } else if (ch == stop && !quote) {
             position.setIndex(index);
             return true;
         } else {
             lastQuote = false;
             buffer.append(ch);
         }
     }
     position.setIndex(index);
     return false;
 }
Ejemplo n.º 12
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);
        }
Ejemplo n.º 13
0
 /**
  * Searches for the index of the specified character. The search for the
  * character starts at the specified offset and moves towards the beginning.
  *
  * @param subString
  *            the string to find.
  * @param start
  *            the starting offset.
  * @return the index of the specified character, -1 if the character isn't
  *         found.
  * @throws NullPointerException
  *             if {@code subString} is {@code null}.
  * @see String#lastIndexOf(String,int)
  * @since 1.4
  */
 public virtual int lastIndexOf(String subString, int start)
 {
     int subCount = subString.length();
     if (subCount <= count && start >= 0) {
         if (subCount > 0) {
             if (start > count - subCount) {
                 start = count - subCount; // count and subCount are both
             }
             // >= 1
             // TODO optimize charAt to direct array access
             char firstChar = subString.charAt(0);
             while (true) {
                 int i = start;
                 bool found = false;
                 for (; i >= 0; --i) {
                     if (value[i] == firstChar) {
                         found = true;
                         break;
                     }
                 }
                 if (!found) {
                     return -1;
                 }
                 int o1 = i, o2 = 0;
                 while (++o2 < subCount
                         && value[++o1] == subString.charAt(o2)) {
                     // Intentionally empty
                 }
                 if (o2 == subCount) {
                     return i;
                 }
                 start = i - 1;
             }
         }
         return start < count ? start : count;
     }
     return -1;
 }
Ejemplo n.º 14
0
 /**
  * Other characters, which are Unicode chars that are not US-ASCII, and are
  * not ISO Control or are not ISO Space chars are not preserved. They are
  * converted into their hexidecimal value prepended by '%'.
  * <p>
  * For example: Euro currency symbol -> "%E2%82%AC".
  * <p>
  * Called from URI.toASCIIString()
  *
  * @param s
  *            java.lang.String the string to be converted
  * @return java.lang.String the converted string
  */
 static String encodeOthers(String s)
 {
     //throws UnsupportedEncodingException {
     StringBuilder buf = new StringBuilder();
     for (int i = 0; i < s.length(); i++) {
         char ch = s.charAt(i);
         if (ch <= 127) {
             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();
 }
Ejemplo n.º 15
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;
            }
        }
Ejemplo n.º 16
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++;
     }
 }
Ejemplo n.º 17
0
        /**
         * Decodes the string argument which is assumed to be encoded in the {@code
         * x-www-form-urlencoded} MIME content type using the UTF-8 encoding scheme.
         * <p>
         *'%' and two following hex digit characters are converted to the
         * equivalent byte value. All other characters are passed through
         * unmodified.
         * <p>
         * e.g. "A%20B%20C %24%25" -> "A B C $%"
         * <p>
         * Called from URI.getXYZ() methods
         *
         * @param s
         *            java.lang.String The encoded string.
         * @return java.lang.String The decoded version.
         */
        static String decode(String s)
        {
            //throws UnsupportedEncodingException {

            StringBuilder result = new StringBuilder();
            java.io.ByteArrayOutputStream outJ = new java.io.ByteArrayOutputStream();
            for (int i = 0; i < s.length();) {
                char c = s.charAt(i);
                if (c == '%') {
                    outJ.reset();
                    do {
                        if (i + 2 >= s.length()) {
                            throw new java.lang.IllegalArgumentException("Incomplete % sequence at: "+ i); //$NON-NLS-1$
                        }
                        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 java.lang.IllegalArgumentException("Invalid % sequence ("+s.substring(i, i + 3)+") at: "+java.lang.StringJ.valueOf(i));
                        }
                        outJ.write((byte) ((d1 << 4) + d2));
                        i += 3;
                    } while (i < s.length() && s.charAt(i) == '%');
                    result.append(outJ.toString(encoding));
                    continue;
                }
                result.append(c);
                i++;
            }
            return result.toString();
        }
Ejemplo n.º 18
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++;
            }
        }
Ejemplo n.º 19
0
 private static int parseNumber(String s, int offset, int[] position)
 {
     int index = offset, length = s.length(), digit, result = 0;
     while (index < length
             && (digit = java.lang.Character.digit(s.charAt(index), 10)) != -1)
     {
         index++;
         result = result * 10 + digit;
     }
     position[0] = index == offset ? -1 : index;
     return result;
 }
Ejemplo n.º 20
0
        private static String formatTimeZoneName(String name, int offset)
        {
            java.lang.StringBuilder buf = new java.lang.StringBuilder();
            int index = offset, length = name.length();
            buf.append(name.substring(0, offset));

            while (index < length)
            {
                if (java.lang.Character.digit(name.charAt(index), 10) != -1)
                {
                    buf.append(name.charAt(index));
                    if ((length - (index + 1)) == 2)
                    {
                        buf.append(':');
                    }
                }
                else if (name.charAt(index) == ':')
                {
                    buf.append(':');
                }
                index++;
            }

            if (buf.toString().indexOf(":") == -1)
            {
                buf.append(':');
                buf.append("00");
            }

            if (buf.toString().indexOf(":") == 5)
            {
                buf.insert(4, '0');
            }

            return buf.toString();
        }
Ejemplo n.º 21
0
        public void addObjectNotify(String strSrcName, String strObject )
        {
    	    lock(m_mxObjectNotify)
    	    {
	            m_strSingleObjectSrcName = strSrcName;
	            m_strSingleObjectID = strObject.charAt(0) == '{' ? strObject.substring(1,strObject.length()-2) : strObject ;
    	    }
        }
Ejemplo n.º 22
0
 static byte[] toUTF8Bytes(String value, int length)
 {
     byte[] result = new byte[length];
     int pos = result.Length;
     for (int i = value.length(); --i >= 0;) {
         char ch = value.charAt(i);
         if (ch < 0x80) {
             result[--pos] = (byte) ch;
         } else if (ch < 0x800) {
             result[--pos] = (byte) (0x80 | (ch & 0x3f));
             result[--pos] = (byte) (0xc0 | (ch >> 6));
         } else {
             result[--pos] = (byte) (0x80 | (ch & 0x3f));
             result[--pos] = (byte) (0x80 | ((ch >> 6) & 0x3f));
             result[--pos] = (byte) (0xe0 | (ch >> 12));
         }
     }
     return result;
 }
Ejemplo n.º 23
0
        public static void saveSudokuToFile(String puzzle, String filename)
        {
            FileOutputStream FO = null;
              byte[] buffer = new byte[puzzle.length()+1];
              int i = 0;

              while (i < puzzle.length()){
            buffer[i] = (byte) puzzle.charAt(i);
            i++;
              }

              try {
            FO = new FileOutputStream(filename);
            FO.write(buffer);
            FO.close();
              } catch (IOException IOE) {
            // Well, well, well....
            return;
              }
        }
Ejemplo n.º 24
0
        public void writeLogMessage(String strMsg) 
        {
#if DEBUG
            if ( strMsg.charAt(strMsg.length() - 1) != '\n' )
                System.Diagnostics.Debug.WriteLine(strMsg);
            else
                System.Diagnostics.Debug.WriteLine(strMsg.Substring(0, strMsg.length() - 1));
#endif
	    }
Ejemplo n.º 25
0
 /**
  * Searches for the index of the specified character. The search for the
  * character starts at the specified offset and moves towards the end.
  *
  * @param subString
  *            the string to find.
  * @param start
  *            the starting offset.
  * @return the index of the specified character, -1 if the character isn't
  *         found
  * @see #lastIndexOf(String,int)
  * @since 1.4
  */
 public virtual int indexOf(String subString, int start)
 {
     if (start < 0) {
         start = 0;
     }
     int subCount = subString.length();
     if (subCount > 0) {
         if (subCount + start > count) {
             return -1;
         }
         // TODO optimize charAt to direct array access
         char firstChar = subString.charAt(0);
         while (true) {
             int i = start;
             bool found = false;
             for (; i < count; i++) {
                 if (value[i] == firstChar) {
                     found = true;
                     break;
                 }
             }
             if (!found || subCount + i > count) {
                 return -1; // handles subCount > count || start >= count
             }
             int o1 = i, o2 = 0;
             while (++o2 < subCount && value[++o1] == subString.charAt(o2)) {
                 // Intentionally empty
             }
             if (o2 == subCount) {
                 return i;
             }
             start = i + 1;
         }
     }
     return (start < count || start == 0) ? start : count;
 }
Ejemplo n.º 26
0
        internal int writeUTFBytesToBuffer(String str, long count,
	                              byte[] buffer, int offset)
        {
            //throws IOException {
            int length = str.length();
            for (int i = 0; i < length; i++) {
                int charValue = str.charAt(i);
                if (charValue > 0 && charValue <= 127) {
                    buffer[offset++] = (byte) charValue;
                } else if (charValue <= 2047) {
                    buffer[offset++] = (byte) (0xc0 | (0x1f & (charValue >> 6)));
                    buffer[offset++] = (byte) (0x80 | (0x3f & charValue));
                } else {
                    buffer[offset++] = (byte) (0xe0 | (0x0f & (charValue >> 12)));
                    buffer[offset++] = (byte) (0x80 | (0x3f & (charValue >> 6)));
                    buffer[offset++] = (byte) (0x80 | (0x3f & charValue));
                 }
            }
            return offset;
        }
Ejemplo n.º 27
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$
            }
        }
Ejemplo n.º 28
0
        // To escape a file path to a URI, by using %HH to represent
        // special ASCII characters: 0x00~0x1F, 0x7F, ' ', '<', '>', '#', '%'
        // and '"' and non-ASCII characters (whose value >= 128).
        public static String filepath2URI(String path)
        {
            // return null if path is null.
            if (path == null)
                return null;

            char separator = java.io.File.separatorChar;
            path = path.replace (separator, '/');

            int len = path.length (), ch;
            java.lang.StringBuffer buffer = new java.lang.StringBuffer (len * 3);
            buffer.append ("file://");
            // change C:/blah to /C:/blah
            if (len >= 2 && path.charAt (1) == ':') {
                ch = java.lang.Character.toUpperCase (path.charAt (0));
                if (ch >= 'A' && ch <= 'Z') {
                    buffer.append ('/');
                }
            }

            // for each character in the path
            int i = 0;
            for (; i < len; i++) {
                ch = path.charAt (i);
                // if it's not an ASCII character, break here, and use UTF-8 encoding
                if (ch >= 128)
                    break;
                if (gNeedEscaping [ch]) {
                    buffer.append ('%');
                    buffer.append (gAfterEscaping1 [ch]);
                    buffer.append (gAfterEscaping2 [ch]);
                    // record the fact that it's escaped
                } else {
                    buffer.append ((char)ch);
                }
            }

            // we saw some non-ascii character
            if (i < len) {
                // get UTF-8 bytes for the remaining sub-string
                byte[] bytes = null;
                byte b;
                try {
                    bytes = path.substring (i).getBytes ("UTF-8");
                } catch (java.io.UnsupportedEncodingException e) {
                    // should never happen
                    return path;
                }
                len = bytes.Length;

                // for each byte
                for (i = 0; i < len; i++) {
                    b = bytes [i];
                    // for non-ascii character: make it positive, then escape
                    if (b < 0) {
                        ch = b + 256;
                        buffer.append ('%');
                        buffer.append (gHexChs [ch >> 4]);
                        buffer.append (gHexChs [ch & 0xf]);
                    } else if (gNeedEscaping [b]) {
                        buffer.append ('%');
                        buffer.append (gAfterEscaping1 [b]);
                        buffer.append (gAfterEscaping2 [b]);
                    } else {
                        buffer.append ((char)b);
                    }
                }
            }

            return buffer.toString ();
        }
Ejemplo n.º 29
0
        /**
         * Decapitalizes a given string according to the rule:
         * <ul>
         * <li>If the first or only character is Upper Case, it is made Lower Case
         * <li>UNLESS the second character is also Upper Case, when the String is
         * returned unchanged <eul>
         *
         * @param name -
         *            the String to decapitalize
         * @return the decapitalized version of the String
         */
        public static String decapitalize(String name)
        {
            if (name == null)
                return null;
            // The rule for decapitalize is that:
            // If the first letter of the string is Upper Case, make it lower case
            // UNLESS the second letter of the string is also Upper Case, in which case no
            // changes are made.
            if (name.length() == 0 || (name.length() > 1 && java.lang.Character.isUpperCase(name.charAt(1))))
            {
                return name;
            }

            char[] chars = name.toCharArray();
            chars[0] = java.lang.Character.toLowerCase(chars[0]);
            return new String(chars);
        }
Ejemplo n.º 30
0
        // END - Interface GoalTest
        //

        public NQueensBoard getBoardForIndividual(String individual)
        {
            int boardSize = individual.length();
            NQueensBoard board = new NQueensBoard(boardSize);
            for (int i = 0; i < boardSize; i++)
            {
                int pos = Character
                        .digit(individual.charAt(i), individual.length());
                board.AddQueenAt(new XYLocation(i, pos));
            }

            return board;
        }