Inheritance: java.lang.AbstractStringBuilder, java.lang.Appendable, java.lang.CharSequence
        /**
         * Gets the name of the file that contains the mapping data for the {@code countryCallingCode} in
         * the language specified.
         *
         * @param countryCallingCode  the country calling code of phone numbers which the data file
         *     contains
         * @param language  two-letter lowercase ISO language codes as defined by ISO 639-1
         * @param script  four-letter titlecase (the first letter is uppercase and the rest of the letters
         *     are lowercase) ISO script codes as defined in ISO 15924
         * @param region  two-letter uppercase ISO country codes as defined by ISO 3166-1
         * @return  the name of the file, or empty string if no such file can be found
         */
        internal String getFileName(int countryCallingCode, String language, String script, String region)
        {
            if (language.length() == 0)
            {
                return("");
            }
            int index = Arrays.binarySearch(countryCallingCodes, countryCallingCode);

            if (index < 0)
            {
                return("");
            }
            Set <String> setOfLangs = availableLanguages.get(index);

            if (setOfLangs.size() > 0)
            {
                String languageCode = findBestMatchingLanguageCode(setOfLangs, language, script, region);
                if (languageCode.length() > 0)
                {
                    StringBuilder fileName = new StringBuilder();
                    fileName.append(countryCallingCode).append('_').append(languageCode);
                    return(fileName.toString());
                }
            }
            return("");
        }
Ejemplo n.º 2
0
            public String toString()
            {
                StringBuilder outputString = new StringBuilder();

                outputString.append("Country Code: ").append(countryCode_);
                outputString.append(" National Number: ").append(nationalNumber_);
                if (hasItalianLeadingZero() && isItalianLeadingZero())
                {
                    outputString.append(" Leading Zero: true");
                }
                if (hasExtension())
                {
                    outputString.append(" Extension: ").append(extension_);
                }
                if (hasCountryCodeSource())
                {
                    outputString.append(" Country Code Source: ").append(Enum.GetName(typeof(CountryCodeSource), countryCodeSource_));
                }
                if (hasPreferredDomesticCarrierCode())
                {
                    outputString.append(" Preferred Domestic Carrier Code: ").
                    append(preferredDomesticCarrierCode_);
                }
                return(outputString.toString());
            }
 private void appendSubsequentLocalePart(String subsequentLocalePart, StringBuilder fullLocale)
 {
     if (subsequentLocalePart.length() > 0)
     {
         fullLocale.append('_').append(subsequentLocalePart);
     }
 }
Ejemplo n.º 4
0
        /**
         * Extracts the country calling code from the beginning of nationalNumber to
         * prefixBeforeNationalNumber when they are available, and places the remaining input into
         * nationalNumber.
         *
         * @return  true when a valid country calling code can be found.
         */
        private boolean attemptToExtractCountryCallingCode()
        {
            if (nationalNumber.length() == 0)
            {
                return(false);
            }
            StringBuilder numberWithoutCountryCallingCode = new StringBuilder();
            int           countryCode = phoneUtil.extractCountryCode(nationalNumber, numberWithoutCountryCallingCode);

            if (countryCode == 0)
            {
                return(false);
            }
            nationalNumber.setLength(0);
            nationalNumber.append(numberWithoutCountryCallingCode);
            String newRegionCode = phoneUtil.getRegionCodeForCountryCode(countryCode);

            if (PhoneNumberUtil.REGION_CODE_FOR_NON_GEO_ENTITY.equals(newRegionCode))
            {
                currentMetadata = phoneUtil.getMetadataForNonGeographicalRegion(countryCode);
            }
            else if (!newRegionCode.equals(defaultCountry))
            {
                currentMetadata = getMetadataForRegion(newRegionCode);
            }
            String countryCodeString = Integer.toString(countryCode);

            prefixBeforeNationalNumber.append(countryCodeString).append(SEPARATOR_BEFORE_NATIONAL_NUMBER);
            return(true);
        }
Ejemplo n.º 5
0
 public override void sendValue(object obj, DataOutputStream dos)
 {
   if (obj is object[])
   {
     object[] objArray = (object[]) obj;
     if (objArray.Length > (int) byte.MaxValue)
     {
       string str = new StringBuilder().append("Cannot write ").append(obj).append(" as ").append(this.__\u003C\u003Ename).append(". Arrays have a max length of 255 values").toString();
       Throwable.__\u003CsuppressFillInStackTrace\u003E();
       throw new IOException(str);
     }
     else
     {
       dos.writeByte(objArray.Length);
       for (int index = 0; index < objArray.Length; ++index)
         this.elementType.sendValue(objArray[index], dos);
     }
   }
   else
   {
     string str = new StringBuilder().append("Cannot write ").append(obj).append(" as ").append(this.__\u003C\u003Ename).toString();
     Throwable.__\u003CsuppressFillInStackTrace\u003E();
     throw new IOException(str);
   }
 }
        public MessageBox(View view, string message)
        {
            View v = view;

            if (v == null)
            {
                v = ApplicationActivity.MainView;
            }

            bool err = (v == null);

            if (!err)
            {
                err = (message == null);
            }

            if (err)
            {
                ConsoleMessage c = new ConsoleMessage("ERROR in MessageBox: MainView is null", "ERROR", 0, ConsoleMessage.MessageLevel.ERROR);
                return;
            }

            java.lang.StringBuilder sb = new java.lang.StringBuilder(message);
            Toast.makeText(view.getContext(), sb, Toast.LENGTH_SHORT).show();
        }
Ejemplo n.º 7
0
        internal static boolean checkNumberGroupingIsValid(
            PhoneNumber number, String candidate, PhoneNumberUtil util, NumberGroupingChecker checker)
        {
            // TODO: Evaluate how this works for other locales (testing has been limited to NANPA regions)
            // and optimise if necessary.
            StringBuilder normalizedCandidate =
                PhoneNumberUtil.normalizeDigits(candidate, true /* keep non-digits */);

            String[] formattedNumberGroups = getNationalNumberGroups(util, number, null);
            if (checker.checkGroups(util, number, normalizedCandidate, formattedNumberGroups))
            {
                return(true);
            }
            // If this didn't pass, see if there are any alternate formats, and try them instead.
            PhoneMetadata alternateFormats =
                MetadataManager.getAlternateFormatsForCountry(number.getCountryCode());

            if (alternateFormats != null)
            {
                foreach (NumberFormat alternateFormat in alternateFormats.numberFormats())
                {
                    formattedNumberGroups = getNationalNumberGroups(util, number, alternateFormat);
                    if (checker.checkGroups(util, number, normalizedCandidate, formattedNumberGroups))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
    public static string test(string s1, string s2)
    {
        SB sb = new SB(s1);

        sb.append(s2);
        return(sb.toString());
    }
        private StringBuilder constructFullLocale(String language, String script, String region)
        {
            StringBuilder fullLocale = new StringBuilder(language);

            appendSubsequentLocalePart(script, fullLocale);
            appendSubsequentLocalePart(region, fullLocale);
            return(fullLocale);
        }
Ejemplo n.º 10
0
 private string compactString([In] string obj0)
 {
   string str = new StringBuilder().append("[").append(String.instancehelper_substring(obj0, this.fPrefix, String.instancehelper_length(obj0) - this.fSuffix + 1)).append("]").toString();
   if (this.fPrefix > 0)
     str = new StringBuilder().append(this.computeCommonPrefix()).append(str).toString();
   if (this.fSuffix > 0)
     str = new StringBuilder().append(str).append(this.computeCommonSuffix()).toString();
   return str;
 }
Ejemplo n.º 11
0
 public static void setTeam(int team)
 {
   StringBuilder stringBuilder = new StringBuilder().append("10.").append(team / 100).append(".");
   int num1 = team;
   int num2 = 100;
   int num3 = -1;
   int num4 = num2 != num3 ? num1 % num2 : 0;
   Robot.setHost(stringBuilder.append(num4).append(".2").toString());
 }
Ejemplo n.º 12
0
 public override string getSaveValue()
 {
   string str = "";
   int[] numArray = this.getValue();
   for (int index = 0; index < numArray.Length; ++index)
   {
     if (index > 0)
       str = new StringBuilder().append(str).append(this.valueSplit).toString();
     str = new StringBuilder().append(str).append(numArray[index]).toString();
   }
   return str;
 }
Ejemplo n.º 13
0
 public override void sendValue([In] object obj0, [In] DataOutputStream obj1)
 {
   if (obj0 is Double)
   {
     obj1.writeDouble(((Double) obj0).doubleValue());
   }
   else
   {
     string str = new StringBuilder().append("Cannot write ").append(obj0).append(" as ").append(this.__\u003C\u003Ename).toString();
     Throwable.__\u003CsuppressFillInStackTrace\u003E();
     throw new IOException(str);
   }
 }
Ejemplo n.º 14
0
		private string join(Iterable<String> items, int limit) {
			StringBuilder sb = new StringBuilder();
			int count = 0;
			foreach (string item in items) {
				if (count > 0)
					sb.append(", ");
				sb.append(item);
				if (limit > 0 && count == limit)
					break;
				count++;
			}
			return sb.toString();
		}
Ejemplo n.º 15
0
        public void HeavyCall()
        {
            var      sb    = new StringBuilder();
            DateTime start = DateTime.Now;

            for (int i = 0; i < 1000000; i++)
            {
                sb.append('a');
            }
            DateTime end = DateTime.Now;

            Console.WriteLine(end - start);
        }
Ejemplo n.º 16
0
		/// <summary>Returns a string containing the tokens joined by delimiters.</summary>
		/// <remarks>Returns a string containing the tokens joined by delimiters.</remarks>
		/// <param name="tokens">
		/// an array objects to be joined. Strings will be formed from
		/// the objects by calling object.toString().
		/// </param>
		public static string join (CharSequence delimiter, Iterable<CharSequence> tokens)
		{
			StringBuilder sb = new StringBuilder ();
			bool firstTime = true;
			foreach (object token in Sharpen.IterableProxy.Create(tokens)) {
				if (firstTime) {
					firstTime = false;
				} else {
					sb.append (delimiter);
				}
				sb.append (token);
			}
			return sb.ToString ();
		}
Ejemplo n.º 17
0
 public static String quoteReplacement(String s)
 {
     if ((s.indexOf('\\') == -1) && (s.indexOf('$') == -1))
     return s;
     StringBuilder sb = new StringBuilder();
     for (int i=0; i<s.length(); i++) {
     char c = s.charAt(i);
     if (c == '\\' || c == '$') {
         sb.append('\\');
     }
     sb.append(c);
     }
     return sb.toString();
 }
        private String findBestMatchingLanguageCode(
            Set <String> setOfLangs, String language, String script, String region)
        {
            StringBuilder fullLocale       = constructFullLocale(language, script, region);
            String        fullLocaleStr    = fullLocale.toString();
            String        normalizedLocale = LOCALE_NORMALIZATION_MAP.get(fullLocaleStr);

            if (normalizedLocale != null)
            {
                if (setOfLangs.contains(normalizedLocale))
                {
                    return(normalizedLocale);
                }
            }
            if (setOfLangs.contains(fullLocaleStr))
            {
                return(fullLocaleStr);
            }

            if (onlyOneOfScriptOrRegionIsEmpty(script, region))
            {
                if (setOfLangs.contains(language))
                {
                    return(language);
                }
            }
            else if (script.length() > 0 && region.length() > 0)
            {
                StringBuilder langWithScript    = new StringBuilder(language).append('_').append(script);
                String        langWithScriptStr = langWithScript.toString();
                if (setOfLangs.contains(langWithScriptStr))
                {
                    return(langWithScriptStr);
                }

                StringBuilder langWithRegion    = new StringBuilder(language).append('_').append(region);
                String        langWithRegionStr = langWithRegion.toString();
                if (setOfLangs.contains(langWithRegionStr))
                {
                    return(langWithRegionStr);
                }

                if (setOfLangs.contains(language))
                {
                    return(language);
                }
            }
            return("");
        }
Ejemplo n.º 19
0
        public override string ToString()
        {
            java.lang.StringBuilder builder = new java.lang.StringBuilder(GetClassName());
            builder.append(": ").append(Message);

            if (innerException != null)
            {
                builder.append(" ---> ").append(innerException.ToString())
                .append(Environment.NewLine).append(Local.GetText("  --- End of inner exception stack trace ---"));
            }
            if (StackTrace != null)
            {
                builder.append(Environment.NewLine).append(StackTrace);
            }
            return(builder.ToString());
        }
Ejemplo n.º 20
0
        public String toString()
        {
            StringBuilder sb = new StringBuilder();

            sb.append("java.util.regex.Matcher");
            sb.append("[pattern=" + pattern());
            sb.append(" region=");
            sb.append(regionStart() + "," + regionEnd());
            sb.append(" lastmatch=");
            if ((first >= 0) && (group() != null))
            {
                sb.append(group());
            }
            sb.append("]");
            return(sb.toString());
        }
Ejemplo n.º 21
0
        public override string format(LogRecord logrecord)
        {
            var stringbuilder = new StringBuilder();
            stringbuilder.append(dateFormat.format(Long.valueOf(logrecord.getMillis())));
            Level level = logrecord.getLevel();
            if (level == Level.FINEST)
            {
                stringbuilder.append(" [FINEST] ");
            }
            else if (level == Level.FINER)
            {
                stringbuilder.append(" [FINER] ");
            }
            else if (level == Level.FINE)
            {
                stringbuilder.append(" [FINE] ");
            }
            else if (level == Level.INFO)
            {
                stringbuilder.append(" [INFO] ");
            }
            else if (level == Level.WARNING)
            {
                stringbuilder.append(" [WARNING] ");
            }
            else if (level == Level.SEVERE)
            {
                stringbuilder.append(" [SEVERE] ");
            }
            else if (level == Level.SEVERE)
            {
                stringbuilder.append(
                    (new StringBuilder()).append(" [").append(level.getLocalizedName()).append("] ").toString());
            }
            stringbuilder.append(logrecord.getMessage());
            stringbuilder.append('\n');
            var throwable = logrecord.getThrown() as Throwable;
            if (throwable != null)
            {
                var stringwriter = new StringWriter();
                throwable.printStackTrace(new PrintWriter(stringwriter));
                stringbuilder.append(stringwriter.toString());
            }

            Debug.WriteLine(stringbuilder.toString());
            return stringbuilder.toString();
        }
Ejemplo n.º 22
0
        internal static boolean isNationalPrefixPresentIfRequired(PhoneNumber number, PhoneNumberUtil util)
        {
            // First, check how we deduced the country code. If it was written in international format, then
            // the national prefix is not required.
            if (number.getCountryCodeSource() != CountryCodeSource.FROM_DEFAULT_COUNTRY)
            {
                return(true);
            }
            String phoneNumberRegion =
                util.getRegionCodeForCountryCode(number.getCountryCode());
            PhoneMetadata metadata = util.getMetadataForRegion(phoneNumberRegion);

            if (metadata == null)
            {
                return(true);
            }
            // Check if a national prefix should be present when formatting this number.
            String       nationalNumber = util.getNationalSignificantNumber(number);
            NumberFormat formatRule     =
                util.chooseFormattingPatternForNumber(metadata.numberFormats(), nationalNumber);

            // To do this, we check that a national prefix formatting rule was present and that it wasn't
            // just the first-group symbol ($1) with punctuation.
            if ((formatRule != null) && formatRule.getNationalPrefixFormattingRule().length() > 0)
            {
                if (formatRule.isNationalPrefixOptionalWhenFormatting())
                {
                    // The national-prefix is optional in these cases, so we don't need to check if it was
                    // present.
                    return(true);
                }
                if (PhoneNumberUtil.formattingRuleHasFirstGroupOnly(
                        formatRule.getNationalPrefixFormattingRule()))
                {
                    // National Prefix not needed for this number.
                    return(true);
                }
                // Normalize the remainder.
                String        rawInputCopy = PhoneNumberUtil.normalizeDigitsOnly(number.getRawInput());
                StringBuilder rawInput     = new StringBuilder(rawInputCopy);
                // Check if we found a national prefix and/or carrier code at the start of the raw input, and
                // return the result.
                return(util.maybeStripNationalPrefixAndCarrierCode(rawInput, metadata, null));
            }
            return(true);
        }
        /**
         * Returns a string representing the data in this class. The string contains one line for each
         * country calling code. The country calling code is followed by a '|' and then a list of
         * comma-separated languages sorted in ascending order.
         */
        public String toString()
        {
            StringBuilder output = new StringBuilder();

            for (int i = 0; i < numOfEntries; i++)
            {
                output.append(countryCallingCodes[i]);
                output.append('|');
                SortedSet <String> sortedSetOfLangs = new TreeSet <String>(availableLanguages.get(i));
                foreach (String lang in sortedSetOfLangs)
                {
                    output.append(lang);
                    output.append(',');
                }
                output.append('\n');
            }
            return(output.toString());
        }
Ejemplo n.º 24
0
        internal static boolean allNumberGroupsRemainGrouped(PhoneNumberUtil util,
                                                             PhoneNumber number,
                                                             StringBuilder normalizedCandidate,
                                                             String[] formattedNumberGroups)
        {
            int fromIndex = 0;

            // Check each group of consecutive digits are not broken into separate groupings in the
            // {@code normalizedCandidate} string.
            for (int i = 0; i < formattedNumberGroups.length(); i++)
            {
                // Fails if the substring of {@code normalizedCandidate} starting from {@code fromIndex}
                // doesn't contain the consecutive digits in formattedNumberGroups[i].
                fromIndex = normalizedCandidate.indexOf(formattedNumberGroups[i], fromIndex);
                if (fromIndex < 0)
                {
                    return(false);
                }
                // Moves {@code fromIndex} forward.
                fromIndex += formattedNumberGroups[i].length();
                if (i == 0 && fromIndex < normalizedCandidate.length())
                {
                    // We are at the position right after the NDC. We get the region used for formatting
                    // information based on the country code in the phone number, rather than the number itself,
                    // as we do not need to distinguish between different countries with the same country
                    // calling code and this is faster.
                    String region = util.getRegionCodeForCountryCode(number.getCountryCode());
                    if (util.getNddPrefixForRegion(region, true) != null &&
                        Character.isDigit(normalizedCandidate.charAt(fromIndex)))
                    {
                        // This means there is no formatting symbol after the NDC. In this case, we only
                        // accept the number if there is no formatting symbol at all in the number, except
                        // for extensions. This is only important for countries with national prefixes.
                        String nationalSignificantNumber = util.getNationalSignificantNumber(number);
                        return(normalizedCandidate.substring(fromIndex - formattedNumberGroups[i].length())
                               .startsWith(nationalSignificantNumber));
                    }
                }
            }
            // The check here makes sure that we haven't mistakenly already used the extension to
            // match the last group of the subscriber number. Note the extension cannot have
            // formatting in-between digits.
            return(normalizedCandidate.substring(fromIndex).contains(number.getExtension()));
        }
Ejemplo n.º 25
0
        public static String quoteReplacement(String s)
        {
            if ((s.indexOf('\\') == -1) && (s.indexOf('$') == -1))
            {
                return(s);
            }
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < s.length(); i++)
            {
                char c = s.charAt(i);
                if (c == '\\' || c == '$')
                {
                    sb.append('\\');
                }
                sb.append(c);
            }
            return(sb.toString());
        }
Ejemplo n.º 26
0
 protected internal NamedDataType(string name, Class defaultWidget, params DataType[] parents)
   : base(name, defaultWidget, parents)
 {
   NamedDataType namedDataType = this;
   if (name == null)
   {
     string str = "Name can not be null";
     Throwable.__\u003CsuppressFillInStackTrace\u003E();
     throw new IllegalArgumentException(str);
   }
   else if (NamedDataType.map.containsKey((object) name))
   {
     string str = new StringBuilder().append("Given name \"").append(name).append("\" has already been claimed").toString();
     Throwable.__\u003CsuppressFillInStackTrace\u003E();
     throw new IllegalArgumentException(str);
   }
   else
     NamedDataType.map.put((object) name, (object) this);
 }
Ejemplo n.º 27
0
 protected internal virtual void printFailures(Result result)
 {
   List failures = result.getFailures();
   if (failures.size() == 0)
     return;
   if (failures.size() == 1)
     this.getWriter().println(new StringBuilder().append("There was ").append(failures.size()).append(" failure:").toString());
   else
     this.getWriter().println(new StringBuilder().append("There were ").append(failures.size()).append(" failures:").toString());
   int num1 = 1;
   Iterator iterator = failures.iterator();
   while (iterator.hasNext())
   {
     Failure each = (Failure) iterator.next();
     StringBuilder stringBuilder = new StringBuilder().append("");
     int num2 = num1;
     ++num1;
     string prefix = stringBuilder.append(num2).toString();
     this.printFailure(each, prefix);
   }
 }
Ejemplo n.º 28
0
        internal static boolean allNumberGroupsAreExactlyPresent(PhoneNumberUtil util,
                                                                 PhoneNumber number,
                                                                 StringBuilder normalizedCandidate,
                                                                 String[] formattedNumberGroups)
        {
            String[] candidateGroups =
                PhoneNumberUtil.NON_DIGITS_PATTERN.split(normalizedCandidate.toString());
            // Set this to the last group, skipping it if the number has an extension.
            int candidateNumberGroupIndex =
                number.hasExtension() ? candidateGroups.length() - 2 : candidateGroups.length() - 1;

            // First we check if the national significant number is formatted as a block.
            // We use contains and not equals, since the national significant number may be present with
            // a prefix such as a national number prefix, or the country code itself.
            if (candidateGroups.length() == 1 ||
                candidateGroups[candidateNumberGroupIndex].contains(
                    util.getNationalSignificantNumber(number)))
            {
                return(true);
            }
            // Starting from the end, go through in reverse, excluding the first group, and check the
            // candidate and number groups are the same.
            for (int formattedNumberGroupIndex = (formattedNumberGroups.length() - 1);
                 formattedNumberGroupIndex > 0 && candidateNumberGroupIndex >= 0;
                 formattedNumberGroupIndex--, candidateNumberGroupIndex--)
            {
                if (!candidateGroups[candidateNumberGroupIndex].equals(
                        formattedNumberGroups[formattedNumberGroupIndex]))
                {
                    return(false);
                }
            }
            // Now check the first group. There may be a national prefix at the start, so we only check
            // that the candidate group ends with the formatted number group.
            return(candidateNumberGroupIndex >= 0 &&
                   candidateGroups[candidateNumberGroupIndex].endsWith(formattedNumberGroups[0]));
        }
Ejemplo n.º 29
0
 public static void failSame(string message)
 {
   string str = "";
   if (message != null)
     str = new StringBuilder().append(message).append(" ").toString();
   Assert.fail(new StringBuilder().append(str).append("expected not same").toString());
 }
Ejemplo n.º 30
0
 public static void failNotSame(string message, object expected, object actual)
 {
   string str = "";
   if (message != null)
     str = new StringBuilder().append(message).append(" ").toString();
   Assert.fail(new StringBuilder().append(str).append("expected same:<").append(expected).append("> was not:<").append(actual).append(">").toString());
 }
Ejemplo n.º 31
0
        public Matcher appendReplacement(StringBuffer sb, String replacement)
        {
            // If no match, return error
            if (first < 0)
            {
                throw new InvalidOperationException("No match available");
            }
            // Process substitution string to replace group references with groups
            int           cursor = 0;
            StringBuilder result = new StringBuilder();

            while (cursor < replacement.length())
            {
                char nextChar = replacement.charAt(cursor);
                if (nextChar == '\\')
                {
                    cursor++;
                    nextChar = replacement.charAt(cursor);
                    result.append(nextChar);
                    cursor++;
                }
                else if (nextChar == '$')
                {
                    // Skip past $
                    cursor++;
                    // A StringIndexOutOfBoundsException is thrown if
                    // this "$" is the last character in replacement
                    // string in current implementation, a IAE might be
                    // more appropriate.
                    nextChar = replacement.charAt(cursor);
                    int refNum = -1;
                    if (nextChar == '{')
                    {
                        cursor++;
                        StringBuilder gsb = new StringBuilder();
                        while (cursor < replacement.length())
                        {
                            nextChar = replacement.charAt(cursor);
                            if (ASCII.isLower(nextChar) ||
                                ASCII.isUpper(nextChar) ||
                                ASCII.isDigit(nextChar))
                            {
                                gsb.append(nextChar);
                                cursor++;
                            }
                            else
                            {
                                break;
                            }
                        }
                        if (gsb.length() == 0)
                        {
                            throw new IllegalArgumentException(
                                      "named capturing group has 0 length name");
                        }
                        if (nextChar != '}')
                        {
                            throw new IllegalArgumentException(
                                      "named capturing group is missing trailing '}'");
                        }
                        String gname = gsb.toString();
                        if (ASCII.isDigit(gname.charAt(0)))
                        {
                            throw new IllegalArgumentException(
                                      "capturing group name {" + gname +
                                      "} starts with digit character");
                        }
                        if (!parentPattern.namedGroups().containsKey(gname))
                        {
                            throw new IllegalArgumentException(
                                      "No group with name {" + gname + "}");
                        }
                        refNum = parentPattern.namedGroups().get(gname);
                        cursor++;
                    }
                    else
                    {
                        // The first number is always a group
                        refNum = (int)nextChar - '0';
                        if ((refNum < 0) || (refNum > 9))
                        {
                            throw new IllegalArgumentException(
                                      "Illegal group reference");
                        }
                        cursor++;
                        // Capture the largest legal group string
                        boolean done = false;
                        while (!done)
                        {
                            if (cursor >= replacement.length())
                            {
                                break;
                            }
                            int nextDigit = replacement.charAt(cursor) - '0';
                            if ((nextDigit < 0) || (nextDigit > 9)) // not a number
                            {
                                break;
                            }
                            int newRefNum = (refNum * 10) + nextDigit;
                            if (groupCount() < newRefNum)
                            {
                                done = true;
                            }
                            else
                            {
                                refNum = newRefNum;
                                cursor++;
                            }
                        }
                    }
                    // Append group
                    if (start(refNum) != -1 && end(refNum) != -1)
                    {
                        result.append(text, start(refNum), end(refNum));
                    }
                }
                else
                {
                    result.append(nextChar);
                    cursor++;
                }
            }
            // Append the intervening text
            sb.append(text, lastAppendPosition, first);
            // Append the match substitution
            sb.append(result);
            lastAppendPosition = last;
            return(this);
        }
Ejemplo n.º 32
0
 public static DataType getType(object value)
 {
   if (value == null)
   {
     string str = "Can not be given null value";
     Throwable.__\u003CsuppressFillInStackTrace\u003E();
     throw new IllegalArgumentException(str);
   }
   else if (value is ITable)
   {
     ITable table = (ITable) value;
     if (!table.containsKey("~TYPE~"))
       return DataType.__\u003C\u003ETABLE;
     return (DataType) NamedDataType.get(table.getString("~TYPE~"));
   }
   else
   {
     if (value is Double)
       return DataType.__\u003C\u003ENUMBER;
     if (value is Boolean)
       return DataType.__\u003C\u003EBOOLEAN;
     if (value is string)
       return DataType.__\u003C\u003ESTRING;
     string str = new StringBuilder().append("Can not get type for class:").append(Object.instancehelper_getClass(value).getName()).toString();
     Throwable.__\u003CsuppressFillInStackTrace\u003E();
     throw new IllegalArgumentException(str);
   }
 }
Ejemplo n.º 33
0
 /**
  * Returns true if the groups of digits found in our candidate phone number match our
  * expectations.
  *
  * @param number  the original number we found when parsing
  * @param normalizedCandidate  the candidate number, normalized to only contain ASCII digits,
  *     but with non-digits (spaces etc) retained
  * @param expectedNumberGroups  the groups of digits that we would expect to see if we
  *     formatted this number
  */
 internal boolean checkGroups(PhoneNumberUtil util, PhoneNumber number,
                              StringBuilder normalizedCandidate, String[] expectedNumberGroups)
 {
     return(checkGroupsFunk(util, number, normalizedCandidate, expectedNumberGroups));
 }
Ejemplo n.º 34
0
 public static string format(string message, object expected, object actual)
 {
   string str = "";
   if (message != null)
     str = new StringBuilder().append(message).append(" ").toString();
   return new StringBuilder().append(str).append("expected:<").append(expected).append("> but was:<").append(actual).append(">").toString();
 }
 private int readUTFChar(StringBuilder sbuf, long utflen)
 {
     int b1, b2, b3;
     b1 = readByte() & 0xFF;
     switch (b1 >> 4) {
     case 0:
     case 1:
     case 2:
     case 3:
     case 4:
     case 5:
     case 6:
     case 7:     // 1 byte format: 0xxxxxxx
         sbuf.append((char) b1);
         return 1;
     case 12:
     case 13:    // 2 byte format: 110xxxxx 10xxxxxx
         if (utflen < 2) {
             throw new Exception();
         }
         b2 = readByte();
         if ((b2 & 0xC0) != 0x80) {
             throw new Exception();
         }
         sbuf.append((char) (((b1 & 0x1F) << 6) |
                             ((b2 & 0x3F) << 0)));
         return 2;
     case 14:    // 3 byte format: 1110xxxx 10xxxxxx 10xxxxxx
         if (utflen < 3) {
             if (utflen == 2) {
                 readByte();         // consume remaining byte
             }
             throw new Exception();
         }
         b2 = readByte();
         b3 = readByte();
         if ((b2 & 0xC0) != 0x80 || (b3 & 0xC0) != 0x80) {
             throw new Exception();
         }
         sbuf.append((char) (((b1 & 0x0F) << 12) |
                             ((b2 & 0x3F) << 6) |
                             ((b3 & 0x3F) << 0)));
         return 3;
     default:   // 10xx xxxx, 1111 xxxx
         throw new Exception();
     }
 }
Ejemplo n.º 36
0
        public void HeavyCall()
        {
            var sb = new StringBuilder();
            DateTime start = DateTime.Now;
            for (int i = 0; i < 1000000; i++)
            {
                sb.append('a');
            }
            DateTime end = DateTime.Now;

            Console.WriteLine(end - start);
        }
		public void save(IFile file) {
			try {
				var document = XmlHelper.load(new StringReader(EMPTY_DOC));
				var libs = (Element)document.getElementsByTagName("libraries").item(0);
				foreach (var lib in this.Libraries) {
					var e = document.createElement("library");
					libs.appendChild(e);
					e.setAttribute("name", lib.Path);
					if (!lib.Enabled) {
						e.setAttribute("enabled", "false");
					}
				}
				if (this.PreprocessorSymbols.any()) {
					var sb = new StringBuilder();
					var first = true;
					foreach (String s in this.PreprocessorSymbols) {
						if (first) {
							first = false;
						} else {
							sb.append(';');
						}
						sb.append(s);
					}
					var e = document.createElement("preprocessorSymbols");
					document.getDocumentElement().appendChild(e);
					e.setTextContent(sb.toString());
				}
				var outputElt = document.createElement("outputPath");
				document.getDocumentElement().appendChild(outputElt);
				outputElt.setTextContent(this.OutputPath);
				
	            var writer = new StringWriter();
				XmlHelper.save(document, writer);
	            var bytes = writer.toString().getBytes("UTF-8");
	            var stream = new ByteArrayInputStream(bytes);
	            if (file.exists()) {
	            	file.setContents(stream, IResource.FORCE, null);
	            } else {
	            	file.create(stream, true, null);
	            }
			} catch (Exception e) {
				Environment.logException(e);
			}
		}
Ejemplo n.º 38
0
 public override object internalizeValue(string str, object obj1, object obj2)
 {
   if (this.externalArrayType.isInstance(obj1))
   {
     ArrayData arrayData = (ArrayData) obj1;
     object[] objArray1;
     if (obj2 is object[] && (objArray1 = (object[]) obj2).Length == arrayData.size())
     {
       ByteCodeHelper.arraycopy((object) arrayData.getDataArray(), 0, (object) objArray1, 0, objArray1.Length);
       return (object) objArray1;
     }
     else
     {
       object[] objArray2 = new object[arrayData.size()];
       ByteCodeHelper.arraycopy((object) arrayData.getDataArray(), 0, (object) objArray2, 0, objArray2.Length);
       return (object) objArray2;
     }
   }
   else
   {
     string str1 = str;
     string str2 = new StringBuilder().append(obj1).append(" is not a ").append((object) this.externalArrayType).toString();
     Throwable.__\u003CsuppressFillInStackTrace\u003E();
     throw new TableKeyExistsWithDifferentTypeException(str1, (NetworkTableEntryType) this, str2);
   }
 }
 private static String getIdString(MethodInfo method) {
     var p = method.getUserData(typeof(PropertyMemberInfo));
     var sb = new StringBuilder();
     if (p != null) {
         sb.append("P:");
         sb.append(getIdName(method.DeclaringType)).append('.');
         sb.append(p.Name);
         return sb.toString();
     }
     var i = method.getUserData(typeof(IndexerMemberInfo));
     int nparams = method.Parameters.count();
     if (i != null) {
         sb.append("P:");
         if (method.ReturnType == method.ReturnType.Library.VoidType) {
             nparams--;
         }
     } else {
         sb.append("M:");
     }
     sb.append(getIdName(method.DeclaringType)).append('.');
     sb.append((method.Name.equals("<init>")) ? "#init" : method.Name);
     if (method.Parameters.any()) {
         sb.append('(');
         var first = true;
         foreach (var t in method.Parameters.take(nparams).select(p => p.Type)) {
             if (first) {
                 first = false;
             } else {
                 sb.append(",");
             }
             sb.append(getIdName(t));
         }
         sb.append(')');
     }
     return sb.toString();
 }
Ejemplo n.º 40
0
 public override void exportValue(string str, object obj1, object obj2)
 {
   if (!this.externalArrayType.isInstance(obj2))
   {
     string str1 = str;
     string str2 = new StringBuilder().append(obj2).append(" is not a ").append((object) this.externalArrayType).toString();
     Throwable.__\u003CsuppressFillInStackTrace\u003E();
     throw new TableKeyExistsWithDifferentTypeException(str1, (NetworkTableEntryType) this, str2);
   }
   else if (!(obj1 is object[]))
   {
     string str1 = str;
     string str2 = new StringBuilder().append("Internal data: ").append(obj1).append(" is not an array").toString();
     Throwable.__\u003CsuppressFillInStackTrace\u003E();
     throw new TableKeyExistsWithDifferentTypeException(str1, (NetworkTableEntryType) this, str2);
   }
   else
   {
     object[] objArray = (object[]) obj1;
     ArrayData arrayData = (ArrayData) obj2;
     arrayData.setSize(objArray.Length);
     ByteCodeHelper.arraycopy((object) objArray, 0, (object) arrayData.getDataArray(), 0, objArray.Length);
   }
 }
 private static String getIdName(TypeInfo type) {
     switch (type.TypeKind) {
     case Boolean:
         return "boolean";
     case Byte:
         return "byte";
     case Char:
         return "char";
     case Double:
         return "double";
     case Float:
         return "float";
     case Int:
         return "int";
     case Long:
         return "long";
     case Short:
         return "short";
     case Void:
         return "void";
     case Array:
         return getIdName(type.ElementType) + "[]";
     default:
         var result = type.FullName.replace('/', '.').replace('$', '.');
         if (type.OriginalTypeDefinition != type && type.GenericArguments.any()) {
             var sb = new StringBuilder();
             sb.append(result).append('{');
             var first = true;
             foreach (var t in type.GenericArguments) {
                 if (first) {
                     first = false;
                 } else {
                     sb.append(", ");
                 }
                 sb.append(getIdName(t));
             }
             sb.append('}');
             result = sb.toString();
         }
         return result;
     }
 }
 //void readFloats(float[] v, int off, int len) {
 //    int span, endoff = off + len;
 //    while (off < endoff) {
 //        if (!blkmode) {
 //            span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 2);
 //            @in.readFully(buf, 0, span << 2);
 //            pos = 0;
 //        } else if (end - pos < 4) {
 //            v[off++] = din.readFloat();
 //            continue;
 //        } else {
 //            span = Math.min(endoff - off, ((end - pos) >> 2));
 //        }
 //        bytesToFloats(buf, pos, v, off, span);
 //        off += span;
 //        pos += span << 2;
 //    }
 //}
 //void readLongs(long[] v, int off, int len) {
 //    int stop, endoff = off + len;
 //    while (off < endoff) {
 //        if (!blkmode) {
 //            int span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 3);
 //            @in.readFully(buf, 0, span << 3);
 //            stop = off + span;
 //            pos = 0;
 //        } else if (end - pos < 8) {
 //            v[off++] = din.readLong();
 //            continue;
 //        } else {
 //            stop = Math.min(endoff, off + ((end - pos) >> 3));
 //        }
 //        while (off < stop) {
 //            v[off++] = Bits.getLong(buf, pos);
 //            pos += 8;
 //        }
 //    }
 //}
 //void readDoubles(double[] v, int off, int len) {
 //    int span, endoff = off + len;
 //    while (off < endoff) {
 //        if (!blkmode) {
 //            span = Math.min(endoff - off, MAX_BLOCK_SIZE >> 3);
 //            @in.readFully(buf, 0, span << 3);
 //            pos = 0;
 //        } else if (end - pos < 8) {
 //            v[off++] = din.readDouble();
 //            continue;
 //        } else {
 //            span = Math.min(endoff - off, ((end - pos) >> 3));
 //        }
 //        bytesToDoubles(buf, pos, v, off, span);
 //        off += span;
 //        pos += span << 3;
 //    }
 //}
 //String readLongUTF() {
 //    return readUTFBody(readLong());
 //}
 private String readUTFBody(long utflen)
 {
     StringBuilder sbuf = new StringBuilder();
     if (!blkmode) {
     end = pos = 0;
     }
     while (utflen > 0) {
     int avail = end - pos;
     if (avail >= 3 || (long) avail == utflen) {
         utflen -= readUTFSpan(sbuf, utflen);
     } else {
         if (blkmode) {
             // near block boundary, read one byte at a time
             utflen -= readUTFChar(sbuf, utflen);
         } else {
             // shift and refill buffer manually
             if (avail > 0) {
                 System.Array.Copy(buf, pos, buf, 0, avail);
             }
             pos = 0;
             end = (int) Math.min(MAX_BLOCK_SIZE, (int)utflen);
             @in.readFully(buf, avail, end - avail);
         }
     }
     }
     return sbuf.toString();
 }
        public static String unescapeString(char[] text, int offset, int length) {
            var sb = new StringBuilder();
            var end = offset + length;
            for (var i = offset; i < end; i++) {
                var c = text[i];
                if (c == '\\') {
                    switch (c = text[++i]) {
                    case '"':
                    case '\\':
                    case '\'':
                        sb.append(c);
                        break;
                    case '0':
                        sb.append((char)0);
                        break;
                    case 'a':
                        sb.append((char)7);
                        break;
                    case 'b':
                        sb.append((char)8);
                        break;
                    case 'f':
                        sb.append((char)12);
                        break;
                    case 'n':
                        sb.append((char)10);
                        break;
                    case 'r':
                        sb.append((char)13);
                        break;
                    case 't':
                        sb.append((char)9);
                        break;
                    case 'v':
                        sb.append((char)11);
                        break;

                    case 'u': {
                        var value = 0;
                        for (var j = 0; j < 4; j++) {
                            value = value * 16 + ParserHelper.scanHexDigit(text[++i]);
                        }
                        sb.append((char)value);
                        break;
                    }
                    case 'U': {
                        var value = 0;
                        for (var j = 0; j < 4; j++) {
                            value = value * 16 + ParserHelper.scanHexDigit(text[++i]);
                        }
                        sb.append((char)value);
                        value = 0;
                        for (int j = 0; j < 4; j++) {
                            value = value * 16 + ParserHelper.scanHexDigit(text[++i]);
                        }
                        sb.append((char)value);
                        break;
                    }
                    case 'x': {
                        var value = ParserHelper.scanHexDigit(text[++i]);
                        var d = ParserHelper.scanHexDigit(text[i + 1]);
                        if (d > -1) {
                            value = value * 16 + d;
                            if ((d = ParserHelper.scanHexDigit(text[++i + 1])) > -1) {
                                value = value * 16 + d;
                                if ((d = ParserHelper.scanHexDigit(text[++i + 1])) > -1) {
                                    value = value * 16 + d;
                                    i++;
                                }
                            }
                        }
                        sb.append((char)value);
                        break;
                    }
                    }
                } else {
                    sb.append(c);
                }
            }
            return sb.toString();
        }
 private long readUTFSpan(StringBuilder sbuf, long utflen)
 {
     int cpos = 0;
     int start = pos;
     int avail = Math.min(end - pos, CHAR_BUF_SIZE);
     // stop short of last char unless all of utf bytes @in buffer
     int stop = pos + ((utflen > avail) ? avail - 2 : (int) utflen);
     boolean outOfBounds = false;
     try {
     while (pos < stop) {
         int b1, b2, b3;
         b1 = buf[pos++] & 0xFF;
         switch (b1 >> 4) {
             case 0:
             case 1:
             case 2:
             case 3:
             case 4:
             case 5:
             case 6:
             case 7:   // 1 byte format: 0xxxxxxx
                 cbuf[cpos++] = (char) b1;
                 break;
             case 12:
             case 13:  // 2 byte format: 110xxxxx 10xxxxxx
                 b2 = buf[pos++];
                 if ((b2 & 0xC0) != 0x80) {
                     throw new Exception();
                 }
                 cbuf[cpos++] = (char) (((b1 & 0x1F) << 6) |
                                        ((b2 & 0x3F) << 0));
                 break;
             case 14:  // 3 byte format: 1110xxxx 10xxxxxx 10xxxxxx
                 b3 = buf[pos + 1];
                 b2 = buf[pos + 0];
                 pos += 2;
                 if ((b2 & 0xC0) != 0x80 || (b3 & 0xC0) != 0x80) {
                     throw new Exception();
                 }
                 cbuf[cpos++] = (char) (((b1 & 0x0F) << 12) |
                                        ((b2 & 0x3F) << 6) |
                                        ((b3 & 0x3F) << 0));
                 break;
             default:  // 10xx xxxx, 1111 xxxx
                 throw new Exception();
         }
     }
     } catch (Exception) {
     outOfBounds = true;
     } finally {
     if (outOfBounds || (pos - start) > utflen) {
         /*
          * Fix for 4450867: if a malformed utf char causes the
          * conversion loop to scan past the expected end of the utf
          * string, only consume the expected number of utf bytes.
          */
         pos = start + (int) utflen;
         throw new Exception();
     }
     }
     sbuf.append(cbuf, 0, cpos);
     return pos - start;
 }
 public static String unescapeVerbatimString(char[] text, int offset, int length) {
     var sb = new StringBuilder();
     var end = offset + length;
     for (var i = offset; i < end; i++) {
         var c = text[i];
         if (c == '"') {
             i++;
         }
         sb.append(c);
     }
     return sb.toString();
 }
Ejemplo n.º 46
0
 public String toString()
 {
     StringBuilder sb = new StringBuilder();
     sb.append("java.util.regex.Matcher");
     sb.append("[pattern=" + pattern());
     sb.append(" region=");
     sb.append(regionStart() + "," + regionEnd());
     sb.append(" lastmatch=");
     if ((first >= 0) && (group() != null)) {
     sb.append(group());
     }
     sb.append("]");
     return sb.toString();
 }
 public static void unescapeIdentifier(StringBuilder sb, char[] text, int offset, int length) {
     var end = offset + length;
     if (text[offset] == '@') {
         offset++;
     }
     for (var i = offset; i < end; i++) {
         var c = text[i];
         if (c == '\\') {
             c = text[++i];
             if (c == 'u') {
                 var value = 0;
                 for (var j = 0; j < 4; j++) {
                     value = value * 16 + ParserHelper.scanHexDigit(text[++i]);
                 }
                 sb.append((char)value);
             } else {
                 var value = 0;
                 for (var j = 0; j < 4; j++) {
                     value = value * 16 + ParserHelper.scanHexDigit(text[++i]);
                 }
                 sb.append((char)value);
                 value = 0;
                 for (int j = 0; j < 4; j++) {
                     value = value * 16 + ParserHelper.scanHexDigit(text[++i]);
                 }
                 sb.append((char)value);
             }
         } else {
             sb.append(c);
         }
     }
 }
Ejemplo n.º 48
0
 public Matcher appendReplacement(StringBuffer sb, String replacement)
 {
     // If no match, return error
     if (first < 0)
     throw new InvalidOperationException("No match available");
     // Process substitution string to replace group references with groups
     int cursor = 0;
     StringBuilder result = new StringBuilder();
     while (cursor < replacement.length()) {
     char nextChar = replacement.charAt(cursor);
     if (nextChar == '\\') {
         cursor++;
         nextChar = replacement.charAt(cursor);
         result.append(nextChar);
         cursor++;
     } else if (nextChar == '$') {
         // Skip past $
         cursor++;
         // A StringIndexOutOfBoundsException is thrown if
         // this "$" is the last character in replacement
         // string in current implementation, a IAE might be
         // more appropriate.
         nextChar = replacement.charAt(cursor);
         int refNum = -1;
         if (nextChar == '{') {
             cursor++;
             StringBuilder gsb = new StringBuilder();
             while (cursor < replacement.length()) {
                 nextChar = replacement.charAt(cursor);
                 if (ASCII.isLower(nextChar) ||
                     ASCII.isUpper(nextChar) ||
                     ASCII.isDigit(nextChar)) {
                     gsb.append(nextChar);
                     cursor++;
                 } else {
                     break;
                 }
             }
             if (gsb.length() == 0)
                 throw new IllegalArgumentException(
                     "named capturing group has 0 length name");
             if (nextChar != '}')
                 throw new IllegalArgumentException(
                     "named capturing group is missing trailing '}'");
             String gname = gsb.toString();
             if (ASCII.isDigit(gname.charAt(0)))
                 throw new IllegalArgumentException(
                     "capturing group name {" + gname +
                     "} starts with digit character");
             if (!parentPattern.namedGroups().containsKey(gname))
                 throw new IllegalArgumentException(
                     "No group with name {" + gname + "}");
             refNum = parentPattern.namedGroups().get(gname);
             cursor++;
         } else {
             // The first number is always a group
             refNum = (int)nextChar - '0';
             if ((refNum < 0)||(refNum > 9))
                 throw new IllegalArgumentException(
                     "Illegal group reference");
             cursor++;
             // Capture the largest legal group string
             boolean done = false;
             while (!done) {
                 if (cursor >= replacement.length()) {
                     break;
                 }
                 int nextDigit = replacement.charAt(cursor) - '0';
                 if ((nextDigit < 0)||(nextDigit > 9)) { // not a number
                     break;
                 }
                 int newRefNum = (refNum * 10) + nextDigit;
                 if (groupCount() < newRefNum) {
                     done = true;
                 } else {
                     refNum = newRefNum;
                     cursor++;
                 }
             }
         }
         // Append group
         if (start(refNum) != -1 && end(refNum) != -1)
             result.append(text, start(refNum), end(refNum));
     } else {
         result.append(nextChar);
         cursor++;
     }
     }
     // Append the intervening text
     sb.append(text, lastAppendPosition, first);
     // Append the match substitution
     sb.append(result);
     lastAppendPosition = last;
     return this;
 }
 public static String decodeDocumentation(char[] text, int offset, int length) {
     var end = offset + length;
     offset++;
     var sb = new StringBuilder();
     if (text[offset] == '*') {
         offset += 2;
         for (var i = offset; i < end; i++) {
             var c = text[i];
             switch (c) {
             case '\r':
                 sb.append(c);
                 if (text[i + 1] == '\n') {
                     i++;
                 }
                 goto case '\n';
                 
             case '\u2028':
             case '\u2029':
             case '\n':
                 sb.append(c);
                 var done = false;
                 while (i + 1 < end && !done) {
                     switch (text[i + 1]) {
                     case ' ':
                     case '\t':
                     case '\v':
                     case '\f':
                         i++;
                         break;
                     case '*':
                         if (text[i + 2] != '/') {
                             i++;
                             if (text[i + 1] == ' ') {
                                 i++;
                             }
                         }
                         goto default;
                     default:
                         done = true;
                         break;
                     }
                 }
                 break;
                
             case '*':
                 if (text[i + 1] != '/') {
                     sb.append(c);
                 } else {
                     i++;
                 }
                 break;
                
             default:
                 sb.append(c);
                 break;
             }
         }                
     } else {
         offset += 2;
         if (offset < end && text[offset] == ' ') {
             offset++;
         }
         for (var i = offset; i < end; i++) {
             var c = text[i];
             switch (c) {
             case '\r':
                 sb.append(c);
                 if (text[i + 1] == '\n') {
                     c = '\n';
                     i++;
                 }
                 goto case '\n';
                 
             case '\u2028':
             case '\u2029':
             case '\n':
                 sb.append(c);
                 do {
                     i++;
                 } while (i < end && text[i] != '/');
                 i += 2;
                 if (i + 1 < end && text[i + 1] == ' ') {
                     i++;
                 }
                 break;
                 
             default:
                 sb.append(c);
                 break;
             }
         }
     }
     return sb.toString();
 }