Esempio n. 1
0
        public static DateTime ToDateTime(string s, string[] formats)
        {
            foreach (var format in formats)
            {
                var simpleDateFormat = new SimpleDateFormat(ToJavaFormat(format), Locale.US);
                var parsePosition = new ParsePosition(0);
                var date = simpleDateFormat.Parse(s, parsePosition);
                if (date != null && parsePosition.Index != 0) return DateTime.FromDate(date);
            }

            throw new ArgumentException(s + " cannot be parsed as DateTime");
        }
Esempio n. 2
0
 /// <summary>
 /// Parse a Date from the specified String starting at the index specified by
 /// the ParsePosition. If the string is successfully parsed, the index of the
 /// ParsePosition is updated to the index following the parsed text.
 /// </summary>
 ///
 /// <param name="string">the String to parse</param>
 /// <param name="position">the ParsePosition, updated on return with the index followingthe parsed text, or on error the index is unchanged and theerror index is set to the index where the error occurred</param>
 /// <returns>the Date resulting from the parse, or null if there is an error</returns>
 public abstract DateTime Parse(String str0, ParsePosition position);
Esempio n. 3
0
 bool ParseEOS(ParsePosition position)
 {
     return(position.ReachedEnd);
 }
Esempio n. 4
0
        /// <summary>
        /// Parses the pattern to determine new strings and ranges for this
        /// ChoiceFormat.
        /// </summary>
        ///
        /// <param name="template">the pattern of strings and ranges</param>
        /// <exception cref="IllegalArgumentException">then an error occurs parsing the pattern</exception>
        public void ApplyPattern(String template)
        {
            double[]       limits = new double[5];
            IList <String> formats = new List <String>();
            int            length = template.Length, limitCount = 0, index = 0;
            StringBuilder  buffer = new StringBuilder();

            IBM.ICU.Text.NumberFormat format   = IBM.ICU.Text.NumberFormat.GetInstance(ILOG.J2CsMapping.Util.Locale.US);
            ParsePosition             position = new ParsePosition(0);

            while (true)
            {
                index = SkipWhitespace(template, index);
                if (index >= length)
                {
                    if (limitCount == limits.Length)
                    {
                        choiceLimits = limits;
                    }
                    else
                    {
                        choiceLimits = new double[limitCount];
                        System.Array.Copy((Array)(limits), 0, (Array)(choiceLimits), 0, limitCount);
                    }
                    choiceFormats = new String[formats.Count];
                    for (int i = 0; i < formats.Count; i++)
                    {
                        choiceFormats[i] = formats[i];
                    }
                    return;
                }

                position.SetIndex(index);
                object value_ren = format.Parse(template, position);
                index = SkipWhitespace(template, position.GetIndex());
                if (position.GetErrorIndex() != -1 || index >= length)
                {
                    // Fix Harmony 540
                    choiceLimits  = new double[0];
                    choiceFormats = new String[0];
                    return;
                }
                char ch = template[index++];
                if (limitCount == limits.Length)
                {
                    double[] newLimits = new double[limitCount * 2];
                    System.Array.Copy((Array)(limits), 0, (Array)(newLimits), 0, limitCount);
                    limits = newLimits;
                }
                double next;
                switch ((int)ch)
                {
                case '#':
                case '\u2264':
                    next = Convert.ToDouble(value_ren);
                    break;

                case '<':
                    next = NextDouble(Convert.ToDouble(value_ren));
                    break;

                default:
                    throw new ArgumentException();
                }
                if (limitCount > 0 && next <= limits[limitCount - 1])
                {
                    throw new ArgumentException();
                }
                buffer.Length = 0;
                position.SetIndex(index);
                ILOG.J2CsMapping.Formatting.Format.UpTo(template, position, buffer, '|');
                index = position.GetIndex();
                limits[limitCount++] = next;
                ILOG.J2CsMapping.Collections.Generics.Collections.Add(formats, buffer.ToString());
            }
        }
Esempio n. 5
0
        // -----------------------------------------------------------------------
        // parsing
        // -----------------------------------------------------------------------

        /// <summary>
        /// Parses a string. Matches the string to be parsed against each of its
        /// rules (with a base value less than upperBound) and returns the value
        /// produced by the rule that matched the most charcters in the source
        /// string.
        /// </summary>
        ///
        /// <param name="text">The string to parse</param>
        /// <param name="parsePosition">The initial position is ignored and assumed to be 0. On exit,this object has been updated to point to the first characterposition this rule set didn't consume.</param>
        /// <param name="upperBound">Limits the rules that can be allowed to match. Only ruleswhose base values are strictly less than upperBound areconsidered.</param>
        /// <returns>The numerical result of parsing this string. This will be the
        /// matching rule's base value, composed appropriately with the
        /// results of matching any of its substitutions. The object will be
        /// an instance of Long if it's an integral value; otherwise, it will
        /// be an instance of Double. This function always returns a valid
        /// object: If nothing matched the input string at all, this function
        /// returns new Long(0), and the parse position is left unchanged.</returns>
        public object Parse(String text, ParsePosition parsePosition,
                            double upperBound)
        {
            // try matching each rule in the rule set against the text being
            // parsed. Whichever one matches the most characters is the one
            // that determines the value we return.

            ParsePosition highWaterMark = new ParsePosition(0);
            object        result        = (long)(0);
            object        tempResult    = null;

            // dump out if there's no text to parse
            if (text.Length == 0)
            {
                return(result);
            }

            // start by trying the nehative number rule (if there is one)
            if (negativeNumberRule != null)
            {
                tempResult = negativeNumberRule.DoParse(text, parsePosition, false,
                                                        upperBound);
                if (parsePosition.GetIndex() > highWaterMark.GetIndex())
                {
                    result = tempResult;
                    highWaterMark.SetIndex(parsePosition.GetIndex());
                }
                // commented out because the error-index API on ParsePosition isn't
                // there in 1.1.x
                // if (parsePosition.getErrorIndex() >
                // highWaterMark.getErrorIndex()) {
                // highWaterMark.setErrorIndex(parsePosition.getErrorIndex());
                // }
                parsePosition.SetIndex(0);
            }

            // then try each of the fraction rules
            for (int i = 0; i < 3; i++)
            {
                if (fractionRules[i] != null)
                {
                    tempResult = fractionRules[i].DoParse(text, parsePosition,
                                                          false, upperBound);
                    if (parsePosition.GetIndex() > highWaterMark.GetIndex())
                    {
                        result = tempResult;
                        highWaterMark.SetIndex(parsePosition.GetIndex());
                    }
                    // commented out because the error-index API on ParsePosition
                    // isn't there in 1.1.x
                    // if (parsePosition.getErrorIndex() >
                    // highWaterMark.getErrorIndex()) {
                    // highWaterMark.setErrorIndex(parsePosition.getErrorIndex());
                    // }
                    parsePosition.SetIndex(0);
                }
            }

            // finally, go through the regular rules one at a time. We start
            // at the end of the list because we want to try matching the most
            // sigificant rule first (this helps ensure that we parse
            // "five thousand three hundred six" as
            // "(five thousand) (three hundred) (six)" rather than
            // "((five thousand three) hundred) (six)"). Skip rules whose
            // base values are higher than the upper bound (again, this helps
            // limit ambiguity by making sure the rules that match a rule's
            // are less significant than the rule containing the substitutions)/
            for (int i_0 = rules.Length - 1; i_0 >= 0 &&
                 highWaterMark.GetIndex() < text.Length; i_0--)
            {
                if (!isFractionRuleSet && rules[i_0].GetBaseValue() >= upperBound)
                {
                    continue;
                }

                tempResult = rules[i_0].DoParse(text, parsePosition,
                                                isFractionRuleSet, upperBound);
                if (parsePosition.GetIndex() > highWaterMark.GetIndex())
                {
                    result = tempResult;
                    highWaterMark.SetIndex(parsePosition.GetIndex());
                }
                // commented out because the error-index API on ParsePosition isn't
                // there in 1.1.x
                // if (parsePosition.getErrorIndex() >
                // highWaterMark.getErrorIndex()) {
                // highWaterMark.setErrorIndex(parsePosition.getErrorIndex());
                // }
                parsePosition.SetIndex(0);
            }

            // finally, update the parse postion we were passed to point to the
            // first character we didn't use, and return the result that
            // cporresponds to that string of characters
            parsePosition.SetIndex(highWaterMark.GetIndex());
            // commented out because the error-index API on ParsePosition isn't
            // there in 1.1.x
            // if (parsePosition.getIndex() == 0) {
            // parsePosition.setErrorIndex(highWaterMark.getErrorIndex());
            // }

            return(result);
        }
Esempio n. 6
0
 public override Number Parse(string @string, ParsePosition position)
 {
     return(null);
 }
Esempio n. 7
0
        //----------------------------------------------------------------
        // Private implementation
        //----------------------------------------------------------------

        /// <summary>
        /// Parse an ID into component pieces.  Take IDs of the form T,
        /// T/V, S-T, S-T/V, or S/V-T.  If the source is missing, return a
        /// source of ANY.
        /// </summary>
        /// <param name="id">The id string, in any of several forms.</param>
        /// <param name="pos">INPUT-OUTPUT parameter.  On input, pos[0] is the
        /// offset of the first character to parse in id.  On output,
        /// pos[0] is the offset after the last parsed character.  If the
        /// parse failed, pos[0] will be unchanged.</param>
        /// <param name="allowFilter">If true, a <see cref="UnicodeSet"/> pattern is allowed
        /// at any location between specs or delimiters, and is returned
        /// as the fifth string in the array.</param>
        /// <returns>A <see cref="Specs"/> object, or null if the parse failed.  If
        /// neither source nor target was seen in the parsed id, then the
        /// parse fails.  If <paramref name="allowFilter"/> is true, then the parsed filter
        /// pattern is returned in the <see cref="Specs"/> object, otherwise the returned
        /// filter reference is null.  If the parse fails for any reason
        /// null is returned.</returns>
        private static Specs ParseFilterID(string id, int[] pos,
                                           bool allowFilter)
        {
            string first     = null;
            string source    = null;
            string target    = null;
            string variant   = null;
            string filter    = null;
            char   delimiter = (char)0;
            int    specCount = 0;
            int    start     = pos[0];

            // This loop parses one of the following things with each
            // pass: a filter, a delimiter character (either '-' or '/'),
            // or a spec (source, target, or variant).
            for (; ;)
            {
                pos[0] = PatternProps.SkipWhiteSpace(id, pos[0]);
                if (pos[0] == id.Length)
                {
                    break;
                }

                // Parse filters
                if (allowFilter && filter == null &&
                    UnicodeSet.ResemblesPattern(id, pos[0]))
                {
                    ParsePosition ppos = new ParsePosition(pos[0]);
                    // Parse the set to get the position.
                    new UnicodeSet(id, ppos, null);
                    filter = id.Substring(pos[0], ppos.Index - pos[0]); // ICU4N: Corrected 2nd parameter
                    pos[0] = ppos.Index;
                    continue;
                }

                if (delimiter == 0)
                {
                    char c = id[pos[0]];
                    if ((c == TARGET_SEP && target == null) ||
                        (c == VARIANT_SEP && variant == null))
                    {
                        delimiter = c;
                        ++pos[0];
                        continue;
                    }
                }

                // We are about to try to parse a spec with no delimiter
                // when we can no longer do so (we can only do so at the
                // start); break.
                if (delimiter == 0 && specCount > 0)
                {
                    break;
                }

                string spec = Utility.ParseUnicodeIdentifier(id, pos);
                if (spec == null)
                {
                    // Note that if there was a trailing delimiter, we
                    // consume it.  So Foo-, Foo/, Foo-Bar/, and Foo/Bar-
                    // are legal.
                    break;
                }

                switch (delimiter)
                {
                case (char)0:
                    first = spec;
                    break;

                case TARGET_SEP:
                    target = spec;
                    break;

                case VARIANT_SEP:
                    variant = spec;
                    break;
                }
                ++specCount;
                delimiter = (char)0;
            }

            // A spec with no prior character is either source or target,
            // depending on whether an explicit "-target" was seen.
            if (first != null)
            {
                if (target == null)
                {
                    target = first;
                }
                else
                {
                    source = first;
                }
            }

            // Must have either source or target
            if (source == null && target == null)
            {
                pos[0] = start;
                return(null);
            }

            // Empty source or target defaults to ANY
            bool sawSource = true;

            if (source == null)
            {
                source    = ANY;
                sawSource = false;
            }
            if (target == null)
            {
                target = ANY;
            }

            return(new Specs(source, target, variant, sawSource, filter));
        }
Esempio n. 8
0
        public void Should_throw_exception_when_given_invalid_position_input_string()
        {
            const string invalidPositionString = "THIS IS NOT A VALID POSITION";
            var          exception             = Assert.Throws <CouldNotParsePositionException>(() => ParsePosition.From(invalidPositionString));

            Assert.That(exception.Message, Is.EqualTo("Could not parse position from: " + invalidPositionString));
        }
Esempio n. 9
0
        /// <summary>
        /// Parse in tag
        /// </summary>
        protected ParsedToken ParseInTag()
        {
            _CurrentRead = null;
            // Whitespaces
            CharInfo c;

            while ((c = ReadChar(false)) != CharInfo.EOF && Char.IsWhiteSpace(c.AsChar))
            {
                ;
            }
            var cpos = c.Position;

            // EOF ?
            if (c == CharInfo.EOF)
            {
                _CurrentToken = null;
                _State        = ParseState.Content;
                ResetTagBuffer();
                throw new ParseError("Unexpected end of file. Tag not closed.", ReadPosition);
            }
            // End of auto closed tag ?
            else if (c == '/' && _State == ParseState.Tag)
            {
                CharInfo saveSlash = c;
                bool     spaces    = false;
                while ((c = ReadChar(false)) != CharInfo.EOF && Char.IsWhiteSpace(c.AsChar))
                {
                    spaces = true;
                }
                if (c != '>')
                {
                    // Prepare a correct next tag
                    SaveChar(new CharInfo('>', (c == CharInfo.EOF) ? saveSlash.Position : c.Position));
                    SaveChar(saveSlash);
                    throw new ParseError("Invalid char after '/'. End of auto closed tag expected.", cpos);
                }
                if (spaces)
                {
                    // Prepare a correct next tag
                    SaveChar(c);
                    SaveChar(saveSlash);
                    // Raise the error
                    throw new ParseError("Invalid auto closed tag, '/' need to be follow by '>'.", cpos);
                }
                // Returns autoclosed
                var result = ParsedTag.AutoClosedTag(((ParsedTag)_CurrentToken).TagName);
                result.Position = cpos;
                _CurrentToken   = null;
                _CurrentRead    = null;
                _State          = ParseState.Content;
                ResetTagBuffer();
                return(result);
            }
            // End of process instruction
            else if (c == '?' && _State == ParseState.ProcessInstruction)
            {
                c = ReadChar(false);
                if (c != '>')
                {
                    throw new ParseError("Invalid char after '?'. End of process instruction expected.", cpos);
                }
                // Returns processinstruction
                var result = ParsedTag.CloseProcessInstruction(((ParsedTag)_CurrentToken).TagName);
                result.Position = cpos;
                _CurrentToken   = null;
                _CurrentRead    = null;
                _State          = ParseState.Content;
                ResetTagBuffer();
                return(result);
            }
            else if (c == '>')
            {
                // Check tag
                if (_State == ParseState.ProcessInstruction)
                {
                    throw new ParseError("A process instruction need to be closed with '?>'.", cpos);
                }
                // Returns close
                var result = ParsedTag.CloseTag(((ParsedTag)_CurrentToken).TagName);
                result.Position = cpos;
                _CurrentToken   = null;
                _CurrentRead    = null;
                _State          = ParseState.Content;
                ResetTagBuffer();
                return(result);
            }
            // Get the attribute name
            if (!IsAttributeNameChar(c.AsChar))
            {
                throw new ParseError("Unexpected character.", cpos);
            }
            AddToCurrentRead(c);
            while ((c = ReadChar(false)) != CharInfo.EOF && IsAttributeNameChar(c.AsChar))
            {
                AddToCurrentRead(c);
            }
            if (c != CharInfo.EOF)
            {
                SaveChar(c);
            }
            String        attrName = GetCurrentRead(true);
            ParsePosition attrPos  = cpos;

            // Whitespaces
            while ((c = ReadChar(false)) != CharInfo.EOF && Char.IsWhiteSpace(c.AsChar))
            {
                ;
            }
            // Attribute whithout value
            if (c != '=')
            {
                SaveChar(c);
                // Attribute whithout content
                return(new ParsedAttribute()
                {
                    Position = attrPos,
                    Name = attrName,
                    Value = null,
                    Quote = '\0'
                });
            }
            // Whitespaces
            while ((c = ReadChar(false)) != CharInfo.EOF && Char.IsWhiteSpace(c.AsChar))
            {
                ;
            }
            // Search the value
            if (c == 0 || c == '/' || c == '?' || c == '>')
            {
                _CurrentAttr = new ParsedAttribute()
                {
                    Position = attrPos,
                    Name     = attrName,
                    Value    = null,
                    Quote    = '\0'
                };
                if (c != CharInfo.EOF)
                {
                    SaveChar(c);
                }
                throw new ParseError("Attribute value expected.", ReadPosition);
            }
            // Quoted value ?
            _CurrentRead = null;
            char quote = '\0';

            if (c == '"' || c == '\'')
            {
                quote = c.AsChar;
                while ((c = ReadChar(false)) != CharInfo.EOF && c != quote)
                {
                    AddToCurrentRead(c);
                }
                _CurrentAttr = new ParsedAttribute()
                {
                    Position = attrPos,
                    Name     = attrName,
                    Value    = HEntity.HtmlDecode(GetCurrentRead(true), RemoveUnknownOrInvalidEntities),
                    Quote    = quote
                };
                if (c == CharInfo.EOF)
                {
                    throw new ParseError("Unexpected end of file. Attribute is not closed.", ReadPosition);
                }
                var result = _CurrentAttr;
                _CurrentAttr = null;
                return(result);
            }
            // Unquoted value
            AddToCurrentRead(c);
            while ((c = ReadChar(false)) != CharInfo.EOF && !Char.IsWhiteSpace(c.AsChar) && c != '"' && c != '\'' && c != '=' && c != '<' && c != '>' && c != '`')
            {
                AddToCurrentRead(c);
            }
            SaveChar(c);
            return(new ParsedAttribute()
            {
                Position = attrPos,
                Name = attrName,
                Value = HEntity.HtmlDecode(GetCurrentRead(true), RemoveUnknownOrInvalidEntities),
                Quote = quote
            });
        }
Esempio n. 10
0
 /// <summary>
 /// New CharInfo
 /// </summary>
 public CharInfo(int c, ParsePosition pos)
     : this()
 {
     CharValue = c;
     Position  = pos;
 }
Esempio n. 11
0
 /// <summary>
 /// Parse the specified String starting at the index specified by the
 /// ParsePosition. If the string is successfully parsed, the index of the
 /// ParsePosition is updated to the index following the parsed text.
 /// </summary>
 ///
 /// <param name="string">the String to parse</param>
 /// <param name="position">the ParsePosition, updated on return with the index followingthe parsed text, or on error the index is unchanged and theerror index is set to the index where the error occurred</param>
 /// <returns>the object resulting from the parse, or null if there is an error</returns>
 public abstract Object ParseObject(String str0, ParsePosition position);
Esempio n. 12
0
 /// <summary>
 /// This method is not yet supported by <c>PluralFormat</c>.
 /// </summary>
 ///
 /// <param name="text">the string to be parsed.</param>
 /// <param name="parsePosition">defines the position where parsing is to begin, and uponreturn, the position where parsing left off. If the positionhas not changed upon return, then parsing failed.</param>
 /// <returns>nothing because this method is not yet implemented.</returns>
 /// <exception cref="UnsupportedOperationException">will always be thrown by this method.</exception>
 /// @draft ICU 3.8
 /// @provisional This API might change or be removed in a future release.
 public object Parse(String text, ParsePosition parsePosition)
 {
     throw new NotSupportedException();
 }
Esempio n. 13
0
 private CharacterSetParser(string input, ParsePosition position)
 {
     _Input       = input;
     _InputLength = input.Length;
     _Position    = position;
 }
Esempio n. 14
0
 /// <summary>
 /// Parse a Number from the specified String starting at the index specified
 /// by the ParsePosition. If the string is successfully parsed, the index of
 /// the ParsePosition is updated to the index following the parsed text.
 /// </summary>
 ///
 /// <param name="string">the String to parse</param>
 /// <param name="position">the ParsePosition, updated on return with the index followingthe parsed text, or on error the index is unchanged and theerror index is set to the index where the error occurred</param>
 /// <returns>the Number resulting from the parse, or null if there is an error</returns>
 public abstract object Parse(String str0, ParsePosition position);
Esempio n. 15
0
 /// <summary>
 /// Parse a Date from the specified String starting at the index specified by
 /// the ParsePosition. If the string is successfully parsed, the index of the
 /// ParsePosition is updated to the index following the parsed text.
 /// </summary>
 ///
 /// <param name="string">the String to parse</param>
 /// <param name="position">the ParsePosition, updated on return with the index followingthe parsed text, or on error the index is unchanged and theerror index is set to the index where the error occurred</param>
 /// <returns>the Date resulting from the parse, or null if there is an error</returns>
 public override Object ParseObject(String str0, ParsePosition position)
 {
     return(Parse(str0, position));
 }
Esempio n. 16
0
        public void TestBugTestsWithNamesArguments()
        {
            { // Taken from Test4031438().
                String pattern1 = "Impossible {arg1} has occurred -- status code is {arg0} and message is {arg2}.";
                String pattern2 = "Double '' Quotes {ARG_ZERO} test and quoted '{ARG_ONE}' test plus 'other {ARG_TWO} stuff'.";

                MessageFormat messageFormatter = new MessageFormat("");

                try
                {
                    Logln("Apply with pattern : " + pattern1);
                    messageFormatter.ApplyPattern(pattern1);
                    IDictionary <string, object> paramsMap = new Dictionary <string, object>();
                    paramsMap["arg0"] = 7;
                    String tempBuffer = messageFormatter.Format(paramsMap);
                    if (!tempBuffer.Equals("Impossible {arg1} has occurred -- status code is 7 and message is {arg2}."))
                    {
                        Errln("Tests arguments < substitution failed");
                    }
                    Logln("Formatted with 7 : " + tempBuffer);
                    ParsePosition status = new ParsePosition(0);
                    var           objs   = messageFormatter.ParseToMap(tempBuffer, status);
                    if (objs.Get("arg1") != null || objs.Get("arg2") != null)
                    {
                        Errln("Parse failed with more than expected arguments");
                    }
                    //for (Iterator keyIter = objs.keySet().iterator();
                    //     keyIter.hasNext();)
                    //{
                    //    String key = (String)keyIter.next();
                    foreach (var key in objs.Keys)
                    {
                        if (objs.Get(key) != null && !objs.Get(key).ToString().Equals(paramsMap.Get(key).ToString()))
                        {
                            Errln("Parse failed on object " + objs.Get(key) + " with argument name : " + key);
                        }
                    }
                    tempBuffer = messageFormatter.Format((object)null);
                    if (!tempBuffer.Equals("Impossible {arg1} has occurred -- status code is {arg0} and message is {arg2}."))
                    {
                        Errln("Tests with no arguments failed");
                    }
                    Logln("Formatted with null : " + tempBuffer);
                    Logln("Apply with pattern : " + pattern2);
                    messageFormatter.ApplyPattern(pattern2);
                    paramsMap.Clear();
                    paramsMap["ARG_ZERO"] = 7;
                    tempBuffer            = messageFormatter.Format(paramsMap);
                    if (!tempBuffer.Equals("Double ' Quotes 7 test and quoted {ARG_ONE} test plus 'other {ARG_TWO} stuff'."))
                    {
                        Errln("quote format test (w/ params) failed.");
                    }
                    Logln("Formatted with params : " + tempBuffer);
                    tempBuffer = messageFormatter.Format((object)null);
                    if (!tempBuffer.Equals("Double ' Quotes {ARG_ZERO} test and quoted {ARG_ONE} test plus 'other {ARG_TWO} stuff'."))
                    {
                        Errln("quote format test (w/ null) failed.");
                    }
                    Logln("Formatted with null : " + tempBuffer);
                    Logln("toPattern : " + messageFormatter.ToPattern());
                }
                catch (Exception foo)
                {
                    Warnln("Exception when formatting in bug 4031438. " + foo.Message);
                }
            }
            { // Taken from Test4052223().
                ParsePosition pos = new ParsePosition(0);
                if (pos.ErrorIndex != -1)
                {
                    Errln("ParsePosition.getErrorIndex initialization failed.");
                }
                MessageFormat fmt  = new MessageFormat("There are {numberOfApples} apples growing on the {whatKindOfTree} tree.");
                String        str  = "There is one apple growing on the peach tree.";
                var           objs = fmt.ParseToMap(str, pos);
                Logln("unparsable string , should fail at " + pos.ErrorIndex);
                if (pos.ErrorIndex == -1)
                {
                    Errln("Bug 4052223 failed : parsing string " + str);
                }
                pos.ErrorIndex = (4);
                if (pos.ErrorIndex != 4)
                {
                    Errln("setErrorIndex failed, got " + pos.ErrorIndex + " instead of 4");
                }
                if (objs != null)
                {
                    Errln("unparsable string, should return null");
                }
            }
            // ICU4N TODO: Serialization
            //{ // Taken from Test4111739().
            //    MessageFormat format1 = null;
            //    MessageFormat format2 = null;
            //    ObjectOutputStream ostream = null;
            //    ByteArrayOutputStream baos = null;
            //    ObjectInputStream istream = null;

            //    try
            //    {
            //        baos = new ByteArrayOutputStream();
            //        ostream = new ObjectOutputStream(baos);
            //    }
            //    catch (IOException e)
            //    {
            //        Errln("Unexpected exception : " + e.getMessage());
            //        return;
            //    }

            //    try
            //    {
            //        format1 = new MessageFormat("pattern{argument}");
            //        ostream.writeObject(format1);
            //        ostream.flush();

            //        byte bytes[] = baos.toByteArray();

            //        istream = new ObjectInputStream(new ByteArrayInputStream(bytes));
            //        format2 = (MessageFormat)istream.readObject();
            //    }
            //    catch (Exception e)
            //    {
            //        Errln("Unexpected exception : " + e.Message);
            //    }

            //    if (!format1.Equals(format2))
            //    {
            //        Errln("MessageFormats before and after serialization are not" +
            //            " equal\nformat1 = " + format1 + "(" + format1.ToPattern() + ")\nformat2 = " +
            //            format2 + "(" + format2.ToPattern() + ")");
            //    }
            //    else
            //    {
            //        Logln("Serialization for MessageFormat is OK.");
            //    }
            //}
            { // Taken from Test4116444().
                String[]      patterns = { "", "one", "{namedArgument,date,short}" };
                MessageFormat mf       = new MessageFormat("");

                for (int i = 0; i < patterns.Length; i++)
                {
                    String pattern = patterns[i];
                    mf.ApplyPattern(pattern);
                    try
                    {
                        var objs = mf.ParseToMap(null, new ParsePosition(0));
                        Logln("pattern: \"" + pattern + "\"");
                        Log(" parsedObjects: ");
                        if (objs != null)
                        {
                            Log("{");
                            //for (Iterator keyIter = objs.keySet().iterator();
                            //     keyIter.hasNext();)
                            //{
                            //    String key = (String)keyIter.next();
                            bool first = true;
                            foreach (var key in objs.Keys)
                            {
                                if (first)
                                {
                                    first = false;
                                }
                                else
                                {
                                    Log(",");
                                }
                                if (objs.Get(key) != null)
                                {
                                    Err("\"" + objs.Get(key).ToString() + "\"");
                                }
                                else
                                {
                                    Log("null");
                                }
                                //if (keyIter.hasNext())
                                //{
                                //    Log(",");
                                //}
                            }
                            Log("}");
                        }
                        else
                        {
                            Log("null");
                        }
                        Logln("");
                    }
                    catch (Exception e)
                    {
                        Errln("pattern: \"" + pattern + "\"");
                        Errln("  Exception: " + e.Message);
                    }
                }
            }
            { // Taken from Test4114739().
                MessageFormat mf = new MessageFormat("<{arg}>");
                IDictionary <string, object> objs1 = null;
                IDictionary <string, object> objs2 = new Dictionary <string, object>();
                IDictionary <string, object> objs3 = new Dictionary <string, object>();
                objs3["arg"] = null;
                try
                {
                    Logln("pattern: \"" + mf.ToPattern() + "\"");
                    Log("format(null) : ");
                    Logln("\"" + mf.Format(objs1) + "\"");
                    Log("format({})   : ");
                    Logln("\"" + mf.Format(objs2) + "\"");
                    Log("format({null}) :");
                    Logln("\"" + mf.Format(objs3) + "\"");
                }
                catch (Exception e)
                {
                    Errln("Exception thrown for null argument tests.");
                }
            }
            { // Taken from Test4118594().
                String        argName    = "something_stupid";
                MessageFormat mf         = new MessageFormat("{" + argName + "}, {" + argName + "}, {" + argName + "}");
                String        forParsing = "x, y, z";
                var           objs       = mf.ParseToMap(forParsing, new ParsePosition(0));
                Logln("pattern: \"" + mf.ToPattern() + "\"");
                Logln("text for parsing: \"" + forParsing + "\"");
                if (!objs.Get(argName).ToString().Equals("z"))
                {
                    Errln("argument0: \"" + objs.Get(argName) + "\"");
                }
                mf.SetLocale(new CultureInfo("en-us"));
                mf.ApplyPattern("{" + argName + ",number,#.##}, {" + argName + ",number,#.#}");
                var oldobjs = new Dictionary <string, object>();
                oldobjs[argName] = 3.1415d;
                String result = mf.Format(oldobjs);
                Logln("pattern: \"" + mf.ToPattern() + "\"");
                Logln("text for parsing: \"" + result + "\"");
                // result now equals "3.14, 3.1"
                if (!result.Equals("3.14, 3.1"))
                {
                    Errln("result = " + result);
                }
                var newobjs = mf.ParseToMap(result, new ParsePosition(0));
                // newobjs now equals {new Double(3.1)}
                if (Convert.ToDouble(newobjs.Get(argName)) != 3.1) // was (Double) [alan]
                {
                    Errln("newobjs.get(argName) = " + newobjs.Get(argName));
                }
            }
            { // Taken from Test4105380().
                String        patternText1 = "The disk \"{diskName}\" contains {numberOfFiles}.";
                String        patternText2 = "There are {numberOfFiles} on the disk \"{diskName}\"";
                MessageFormat form1        = new MessageFormat(patternText1);
                MessageFormat form2        = new MessageFormat(patternText2);
                double[]      filelimits   = { 0, 1, 2 };
                String[]      filepart     = { "no files", "one file", "{numberOfFiles,number} files" };
                ChoiceFormat  fileform     = new ChoiceFormat(filelimits, filepart);
                form1.SetFormat(1, fileform);
                form2.SetFormat(0, fileform);
                var testArgs = new Dictionary <string, object>();
                testArgs["diskName"]      = "MyDisk";
                testArgs["numberOfFiles"] = 12373L;
                Logln(form1.Format(testArgs));
                Logln(form2.Format(testArgs));
            }
            { // Taken from test4293229().
                MessageFormat format   = new MessageFormat("'''{'myNamedArgument}'' '''{myNamedArgument}'''");
                var           args     = new Dictionary <string, object>();
                String        expected = "'{myNamedArgument}' '{myNamedArgument}'";
                String        result   = format.Format(args);
                if (!result.Equals(expected))
                {
                    throw new Exception("wrong format result - expected \"" +
                                        expected + "\", got \"" + result + "\"");
                }
            }
        }
Esempio n. 17
0
 /// <summary>
 /// This method is not yet supported by <see cref="PluralFormat"/>.
 /// </summary>
 /// <param name="text">the string to be parsed.</param>
 /// <param name="parsePosition">defines the position where parsing is to begin,
 /// and upon return, the position where parsing left off.  If the position
 /// has not changed upon return, then parsing failed.</param>
 /// <returns>nothing because this method is not yet implemented.</returns>
 /// <exception cref="InvalidOperationException">will always be thrown by this method.</exception>
 /// <stable>ICU 3.8</stable>
 public virtual /*Number*/ object Parse(string text, ParsePosition parsePosition)
 {
     // You get number ranges from this. You can't get an exact number.
     throw new InvalidOperationException();
 }
Esempio n. 18
0
        /// <summary>
        /// Parse a global filter of the form "[f]" or "([f])", depending
        /// on <paramref name="withParens"/>.
        /// </summary>
        /// <param name="id">The pattern to parse.</param>
        /// <param name="pos">INPUT-OUTPUT parameter.  On input, the position of
        /// the first character to parse.  On output, the position after
        /// the last character parsed.</param>
        /// <param name="dir">The direction.</param>
        /// <param name="withParens">INPUT-OUTPUT parameter.  On entry, if
        /// withParens[0] is 0, then parens are disallowed.  If it is 1,
        /// then parens are requires.  If it is -1, then parens are
        /// optional, and the return result will be set to 0 or 1.</param>
        /// <param name="canonID">OUTPUT parameter.  The pattern for the filter
        /// added to the canonID, either at the end, if dir is <see cref="TransliterationDirection.Forward"/>, or
        /// at the start, if dir is <see cref="TransliterationDirection.Reverse"/>.  The pattern will be enclosed
        /// in parentheses if appropriate, and will be suffixed with an
        /// <see cref="ID_DELIM"/> character.  May be null.</param>
        /// <returns>A <see cref="UnicodeSet"/> object or null.  A non-null results
        /// indicates a successful parse, regardless of whether the filter
        /// applies to the given direction.  The caller should discard it
        /// if withParens != (dir == <see cref="TransliterationDirection.Reverse"/>).</returns>
        public static UnicodeSet ParseGlobalFilter(string id, int[] pos, TransliterationDirection dir,
                                                   int[] withParens,
                                                   StringBuffer canonID)
        {
            UnicodeSet filter = null;
            int        start  = pos[0];

            if (withParens[0] == -1)
            {
                withParens[0] = Utility.ParseChar(id, pos, OPEN_REV) ? 1 : 0;
            }
            else if (withParens[0] == 1)
            {
                if (!Utility.ParseChar(id, pos, OPEN_REV))
                {
                    pos[0] = start;
                    return(null);
                }
            }

            pos[0] = PatternProps.SkipWhiteSpace(id, pos[0]);

            if (UnicodeSet.ResemblesPattern(id, pos[0]))
            {
                ParsePosition ppos = new ParsePosition(pos[0]);
                try
                {
                    filter = new UnicodeSet(id, ppos, null);
                }
                catch (ArgumentException)
                {
                    pos[0] = start;
                    return(null);
                }

                string pattern = id.Substring(pos[0], ppos.Index - pos[0]); // ICU4N: Corrected 2nd parameter
                pos[0] = ppos.Index;

                if (withParens[0] == 1 && !Utility.ParseChar(id, pos, CLOSE_REV))
                {
                    pos[0] = start;
                    return(null);
                }

                // In the forward direction, append the pattern to the
                // canonID.  In the reverse, insert it at zero, and invert
                // the presence of parens ("A" <-> "(A)").
                if (canonID != null)
                {
                    if (dir == Forward)
                    {
                        if (withParens[0] == 1)
                        {
                            pattern = OPEN_REV + pattern + CLOSE_REV;
                        }
                        canonID.Append(pattern + ID_DELIM);
                    }
                    else
                    {
                        if (withParens[0] == 0)
                        {
                            pattern = OPEN_REV + pattern + CLOSE_REV;
                        }
                        canonID.Insert(0, pattern + ID_DELIM);
                    }
                }
            }

            return(filter);
        }
Esempio n. 19
0
 /// <summary>
 /// This method is not yet supported by <see cref="PluralFormat"/>.
 /// </summary>
 /// <param name="source">the string to be parsed.</param>
 /// <param name="pos">defines the position where parsing is to begin,
 /// and upon return, the position where parsing left off.  If the position
 /// has not changed upon return, then parsing failed.</param>
 /// <returns>nothing because this method is not yet implemented.</returns>
 /// <exception cref="InvalidOperationException">will always be thrown by this method.</exception>
 /// <stable>ICU 3.8</stable>
 public override object ParseObject(String source, ParsePosition pos)
 {
     throw new InvalidOperationException();
 }
Esempio n. 20
0
 public override Number Parse(string @string, ParsePosition position)
 {
     return null;
 }
Esempio n. 21
0
 /// <summary>
 /// Override Format.parseObject().
 /// </summary>
 ///
 /// <seealso cref="M:ILOG.J2CsMapping.Text.IlFormat.ParseObject(System.String, IBM.ICU.Text.ParsePosition)"/>
 public override Object ParseObject(String source, ParsePosition pos)
 {
     return(fmt.ParseCurrency(source, pos));
 }
Esempio n. 22
0
 ///
 /// <summary>
 /// This method is not supported by <see cref="SelectFormat"/>.
 /// </summary>
 /// <param name="source">the string to be parsed.</param>
 /// <param name="pos">defines the position where parsing is to begin,
 /// and upon return, the position where parsing left off.  If the position
 /// has not changed upon return, then parsing failed.</param>
 /// <returns>nothing because this method is not supported.</returns>
 /// <exception cref="NotSupportedException">thrown always.</exception>
 /// <stable>ICU 4.4</stable>
 public override object ParseObject(string source, ParsePosition pos)
 {
     throw new NotSupportedException();
 }
Esempio n. 23
0
 /// <summary>
 /// Parse a Date from the specified String starting at the index specified by
 /// the ParsePosition. If the string is successfully parsed, the index of the
 /// ParsePosition is updated to the index following the parsed text.
 /// </summary>
 ///
 /// <param name="string">the String to parse according to the pattern of thisSimpleDateFormat</param>
 /// <param name="position">the ParsePosition, updated on return with the index followingthe parsed text, or on error the index is unchanged and theerror index is set to the index where the error occurred</param>
 /// <returns>the Date resulting from the parse, or null if there is an error</returns>
 /// <exception cref="IllegalArgumentException">when there are invalid characters in the pattern</exception>
 public override DateTime Parse(String str0, ParsePosition position)
 {
     icuFormat.SetTimeZone(IBM.ICU.Util.TimeZone.GetTimeZone(calendar
                                                             .GetTimeZone().GetID()));
     return(icuFormat.Parse(str0, position));
 }