Search in sources :

Example 41 with MessageFormat

use of android.icu.text.MessageFormat in project j2objc by google.

the class MessageRegressionTest method test4293229.

@Test
public void test4293229() {
    MessageFormat format = new MessageFormat("'''{'0}'' '''{0}'''");
    Object[] args = { null };
    String expected = "'{0}' '{0}'";
    String result = format.format(args);
    if (!result.equals(expected)) {
        throw new RuntimeException("wrong format result - expected \"" + expected + "\", got \"" + result + "\"");
    }
}
Also used : MessageFormat(android.icu.text.MessageFormat) Test(org.junit.Test)

Example 42 with MessageFormat

use of android.icu.text.MessageFormat in project j2objc by google.

the class MessageRegressionTest method Test4052223.

@Test
public void Test4052223() {
    ParsePosition pos = new ParsePosition(0);
    if (pos.getErrorIndex() != -1) {
        errln("ParsePosition.getErrorIndex initialization failed.");
    }
    MessageFormat fmt = new MessageFormat("There are {0} apples growing on the {1} tree.");
    String str = new String("There is one apple growing on the peach tree.");
    Object[] objs = fmt.parse(str, pos);
    logln("unparsable string , should fail at " + pos.getErrorIndex());
    if (pos.getErrorIndex() == -1)
        errln("Bug 4052223 failed : parsing string " + str);
    pos.setErrorIndex(4);
    if (pos.getErrorIndex() != 4)
        errln("setErrorIndex failed, got " + pos.getErrorIndex() + " instead of 4");
    if (objs != null) {
        errln("objs should be null");
    }
    ChoiceFormat f = new ChoiceFormat("-1#are negative|0#are no or fraction|1#is one|1.0<is 1+|2#are two|2<are more than 2.");
    pos.setIndex(0);
    pos.setErrorIndex(-1);
    Number obj = f.parse("are negative", pos);
    if (pos.getErrorIndex() != -1 && obj.doubleValue() == -1.0)
        errln("Parse with \"are negative\" failed, at " + pos.getErrorIndex());
    pos.setIndex(0);
    pos.setErrorIndex(-1);
    obj = f.parse("are no or fraction ", pos);
    if (pos.getErrorIndex() != -1 && obj.doubleValue() == 0.0)
        errln("Parse with \"are no or fraction\" failed, at " + pos.getErrorIndex());
    pos.setIndex(0);
    pos.setErrorIndex(-1);
    obj = f.parse("go postal", pos);
    if (pos.getErrorIndex() == -1 && !Double.isNaN(obj.doubleValue()))
        errln("Parse with \"go postal\" failed, at " + pos.getErrorIndex());
}
Also used : MessageFormat(android.icu.text.MessageFormat) ChoiceFormat(java.text.ChoiceFormat) ParsePosition(java.text.ParsePosition) Test(org.junit.Test)

Example 43 with MessageFormat

use of android.icu.text.MessageFormat in project j2objc by google.

the class TestMessageFormat method TestDecimals.

@Test
public void TestDecimals() {
    // Simple number replacement.
    MessageFormat m = new MessageFormat("{0,plural,one{one meter}other{# meters}}", ULocale.ENGLISH);
    Object[] args = new Object[] { 1 };
    FieldPosition ignore = null;
    StringBuffer result = new StringBuffer();
    assertEquals("simple format(1)", "one meter", m.format(args, result, ignore).toString());
    args[0] = 1.5;
    result.delete(0, result.length());
    assertEquals("simple format(1.5)", "1.5 meters", m.format(args, result, ignore).toString());
    // Simple but explicit.
    MessageFormat m0 = new MessageFormat("{0,plural,one{one meter}other{{0} meters}}", ULocale.ENGLISH);
    args[0] = 1;
    result.delete(0, result.length());
    assertEquals("explicit format(1)", "one meter", m0.format(args, result, ignore).toString());
    args[0] = 1.5;
    result.delete(0, result.length());
    assertEquals("explicit format(1.5)", "1.5 meters", m0.format(args, result, ignore).toString());
    // With offset and specific simple format with optional decimals.
    MessageFormat m1 = new MessageFormat("{0,plural,offset:1 one{another meter}other{{0,number,00.#} meters}}", ULocale.ENGLISH);
    args[0] = 1;
    result.delete(0, result.length());
    assertEquals("offset format(1)", "01 meters", m1.format(args, result, ignore).toString());
    args[0] = 2;
    result.delete(0, result.length());
    assertEquals("offset format(1)", "another meter", m1.format(args, result, ignore).toString());
    args[0] = 2.5;
    result.delete(0, result.length());
    assertEquals("offset format(1)", "02.5 meters", m1.format(args, result, ignore).toString());
    // With offset and specific simple format with forced decimals.
    MessageFormat m2 = new MessageFormat("{0,plural,offset:1 one{another meter}other{{0,number,0.0} meters}}", ULocale.ENGLISH);
    args[0] = 1;
    result.delete(0, result.length());
    assertEquals("offset-decimals format(1)", "1.0 meters", m2.format(args, result, ignore).toString());
    args[0] = 2;
    result.delete(0, result.length());
    assertEquals("offset-decimals format(1)", "2.0 meters", m2.format(args, result, ignore).toString());
    args[0] = 2.5;
    result.delete(0, result.length());
    assertEquals("offset-decimals format(1)", "2.5 meters", m2.format(args, result, ignore).toString());
}
Also used : MessageFormat(android.icu.text.MessageFormat) FieldPosition(java.text.FieldPosition) Test(org.junit.Test)

Example 44 with MessageFormat

use of android.icu.text.MessageFormat in project j2objc by google.

the class TestMessageFormat method TestFormatToCharacterIterator.

// Test case for formatToCharacterIterator
@Test
public void TestFormatToCharacterIterator() {
    MessageFormat[] msgfmts = { new MessageFormat("The {3,ordinal} folder ''{0}'' contains {2,number} file(s), created at {1,time} on {1,date}."), new MessageFormat(// same
    "The {arg3,ordinal} folder ''{arg0}'' contains {arg2,number} file(s), created at {arg1,time} on {arg1,date}."), // args
    new MessageFormat("The folder contains {0}.") };
    double[] filelimits = { 0, 1, 2 };
    String[] filepart = { "no files", "one file", "{0,number} files" };
    ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
    msgfmts[2].setFormat(0, fileform);
    Object[] args0 = new Object[] { "tmp", new Date(1184777888000L), new Integer(15), new Integer(2) };
    HashMap args1 = new HashMap();
    args1.put("arg0", "tmp");
    args1.put("arg1", new Date(1184777888000L));
    args1.put("arg2", new Integer(15));
    args1.put("arg3", new Integer(2));
    Object[] args2 = new Object[] { new Integer(34) };
    Object[] args = { args0, args1, args2 };
    String[] expectedStrings = { "The 2nd folder 'tmp' contains 15 file(s), created at 9:58:08 AM on Jul 18, 2007.", "The 2nd folder 'tmp' contains 15 file(s), created at 9:58:08 AM on Jul 18, 2007.", "The folder contains 34 files." };
    AttributedString[] expectedAttributedStrings = { new AttributedString(expectedStrings[0]), new AttributedString(expectedStrings[1]), new AttributedString(expectedStrings[2]) };
    // Add expected attributes to the expectedAttributedStrings[0]
    expectedAttributedStrings[0].addAttribute(MessageFormat.Field.ARGUMENT, new Integer(3), 4, 7);
    expectedAttributedStrings[0].addAttribute(MessageFormat.Field.ARGUMENT, new Integer(0), 16, 19);
    expectedAttributedStrings[0].addAttribute(MessageFormat.Field.ARGUMENT, new Integer(2), 30, 32);
    expectedAttributedStrings[0].addAttribute(NumberFormat.Field.INTEGER, NumberFormat.Field.INTEGER, 30, 32);
    expectedAttributedStrings[0].addAttribute(MessageFormat.Field.ARGUMENT, new Integer(1), 53, 63);
    expectedAttributedStrings[0].addAttribute(DateFormat.Field.HOUR1, DateFormat.Field.HOUR1, 53, 54);
    // expectedAttributedStrings[0].addAttribute(DateFormat.Field.TIME_SEPARATOR, DateFormat.Field.TIME_SEPARATOR, 54, 55);
    expectedAttributedStrings[0].addAttribute(DateFormat.Field.MINUTE, DateFormat.Field.MINUTE, 55, 57);
    // expectedAttributedStrings[0].addAttribute(DateFormat.Field.TIME_SEPARATOR, DateFormat.Field.TIME_SEPARATOR, 57, 58);
    expectedAttributedStrings[0].addAttribute(DateFormat.Field.SECOND, DateFormat.Field.SECOND, 58, 60);
    expectedAttributedStrings[0].addAttribute(DateFormat.Field.AM_PM, DateFormat.Field.AM_PM, 61, 63);
    expectedAttributedStrings[0].addAttribute(MessageFormat.Field.ARGUMENT, new Integer(1), 67, 79);
    expectedAttributedStrings[0].addAttribute(DateFormat.Field.MONTH, DateFormat.Field.MONTH, 67, 70);
    expectedAttributedStrings[0].addAttribute(DateFormat.Field.DAY_OF_MONTH, DateFormat.Field.DAY_OF_MONTH, 71, 73);
    expectedAttributedStrings[0].addAttribute(DateFormat.Field.YEAR, DateFormat.Field.YEAR, 75, 79);
    // Add expected attributes to the expectedAttributedStrings[1]
    expectedAttributedStrings[1].addAttribute(MessageFormat.Field.ARGUMENT, "arg3", 4, 7);
    expectedAttributedStrings[1].addAttribute(MessageFormat.Field.ARGUMENT, "arg0", 16, 19);
    expectedAttributedStrings[1].addAttribute(MessageFormat.Field.ARGUMENT, "arg2", 30, 32);
    expectedAttributedStrings[1].addAttribute(NumberFormat.Field.INTEGER, NumberFormat.Field.INTEGER, 30, 32);
    expectedAttributedStrings[1].addAttribute(MessageFormat.Field.ARGUMENT, "arg1", 53, 63);
    expectedAttributedStrings[1].addAttribute(DateFormat.Field.HOUR1, DateFormat.Field.HOUR1, 53, 54);
    // expectedAttributedStrings[1].addAttribute(DateFormat.Field.TIME_SEPARATOR, DateFormat.Field.TIME_SEPARATOR, 54, 55);
    expectedAttributedStrings[1].addAttribute(DateFormat.Field.MINUTE, DateFormat.Field.MINUTE, 55, 57);
    // expectedAttributedStrings[1].addAttribute(DateFormat.Field.TIME_SEPARATOR, DateFormat.Field.TIME_SEPARATOR, 57, 58);
    expectedAttributedStrings[1].addAttribute(DateFormat.Field.SECOND, DateFormat.Field.SECOND, 58, 60);
    expectedAttributedStrings[1].addAttribute(DateFormat.Field.AM_PM, DateFormat.Field.AM_PM, 61, 63);
    expectedAttributedStrings[1].addAttribute(MessageFormat.Field.ARGUMENT, "arg1", 67, 79);
    expectedAttributedStrings[1].addAttribute(DateFormat.Field.MONTH, DateFormat.Field.MONTH, 67, 70);
    expectedAttributedStrings[1].addAttribute(DateFormat.Field.DAY_OF_MONTH, DateFormat.Field.DAY_OF_MONTH, 71, 73);
    expectedAttributedStrings[1].addAttribute(DateFormat.Field.YEAR, DateFormat.Field.YEAR, 75, 79);
    // Add expected attributes to the expectedAttributedStrings[2]
    expectedAttributedStrings[2].addAttribute(MessageFormat.Field.ARGUMENT, new Integer(0), 20, 28);
    expectedAttributedStrings[2].addAttribute(NumberFormat.Field.INTEGER, NumberFormat.Field.INTEGER, 20, 22);
    for (int i = 0; i < msgfmts.length; i++) {
        AttributedCharacterIterator acit = msgfmts[i].formatToCharacterIterator(args[i]);
        AttributedCharacterIterator expectedAcit = expectedAttributedStrings[i].getIterator();
        // Check available attributes
        Set attrSet = acit.getAllAttributeKeys();
        Set expectedAttrSet = expectedAcit.getAllAttributeKeys();
        if (attrSet.size() != expectedAttrSet.size()) {
            errln("FAIL: Number of attribute keys is " + attrSet.size() + " expected: " + expectedAttrSet.size());
        }
        Iterator attrIterator = attrSet.iterator();
        while (attrIterator.hasNext()) {
            AttributedCharacterIterator.Attribute attr = (AttributedCharacterIterator.Attribute) attrIterator.next();
            if (!expectedAttrSet.contains(attr)) {
                errln("FAIL: The attribute " + attr + " is not expected.");
            }
        }
        StringBuffer buf = new StringBuffer();
        int index = acit.getBeginIndex();
        int end = acit.getEndIndex();
        int indexExp = expectedAcit.getBeginIndex();
        int expectedLen = expectedAcit.getEndIndex() - indexExp;
        if (end - index != expectedLen) {
            errln("FAIL: Length of the result attributed string is " + (end - index) + " expected: " + expectedLen);
        } else {
            // Check attributes associated with each character
            while (index < end) {
                char c = acit.setIndex(index);
                buf.append(c);
                expectedAcit.setIndex(indexExp);
                Map attrs = acit.getAttributes();
                Map attrsExp = expectedAcit.getAttributes();
                if (attrs.size() != attrsExp.size()) {
                    errln("FAIL: Number of attributes associated with index " + index + " is " + attrs.size() + " expected: " + attrsExp.size());
                } else {
                    // Check all attributes at the index
                    Iterator entryIterator = attrsExp.entrySet().iterator();
                    while (entryIterator.hasNext()) {
                        Map.Entry entry = (Map.Entry) entryIterator.next();
                        if (attrs.containsKey(entry.getKey())) {
                            Object value = attrs.get(entry.getKey());
                            assertEquals("Attribute value at index " + index, entry.getValue(), value);
                        } else {
                            errln("FAIL: Attribute " + entry.getKey() + " is missing at index " + index);
                        }
                    }
                }
                index++;
                indexExp++;
            }
            assertEquals("AttributedString contents", expectedStrings[i], buf.toString());
        }
    }
    // Tests when "if (arguments == null)" is true
    try {
        MessageFormat mf = new MessageFormat("");
        mf.formatToCharacterIterator(null);
        errln("MessageFormat.formatToCharacterIterator(Object) was suppose " + "to return an exception when null is passed.");
    } catch (Exception e) {
    }
}
Also used : Set(java.util.Set) HashMap(java.util.HashMap) AttributedString(java.text.AttributedString) AttributedString(java.text.AttributedString) Iterator(java.util.Iterator) AttributedCharacterIterator(java.text.AttributedCharacterIterator) MessageFormat(android.icu.text.MessageFormat) ChoiceFormat(java.text.ChoiceFormat) Date(java.util.Date) ParseException(java.text.ParseException) AttributedCharacterIterator(java.text.AttributedCharacterIterator) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) Test(org.junit.Test)

Example 45 with MessageFormat

use of android.icu.text.MessageFormat in project j2objc by google.

the class TestMessageFormat method testParseNamedArguments.

// This tests parsing formatted messages with named arguments instead of
// numbers.
@Test
public void testParseNamedArguments() {
    String msgFormatString = "{foo} =sep= {bar}";
    MessageFormat msg = new MessageFormat(msgFormatString);
    String source = "abc =sep= def";
    try {
        Map fmt_map = msg.parseToMap(source);
        if (fmt_map.keySet().size() != 2) {
            errln("*** MSG parse (ustring, count, err) count err.");
        } else {
            assertEquals("parse()[0]", "abc", fmt_map.get("foo"));
            assertEquals("parse()[1]", "def", fmt_map.get("bar"));
        }
    } catch (ParseException e1) {
        errln("*** MSG parse (ustring, count, err) error.");
    }
    ParsePosition pp = new ParsePosition(0);
    Map fmt_map = msg.parseToMap(source, pp);
    if (pp.getIndex() == 0 || fmt_map == null) {
        errln("*** MSG parse (ustring, parsepos., count) error.");
    } else {
        if (fmt_map.keySet().size() != 2) {
            errln("*** MSG parse (ustring, parsepos., count) count err.");
        } else {
            assertEquals("parse()[0]", "abc", fmt_map.get("foo"));
            assertEquals("parse()[1]", "def", fmt_map.get("bar"));
        }
    }
    pp.setIndex(0);
    Map fmta = (Map) msg.parseObject(source, pp);
    if (pp.getIndex() == 0) {
        errln("*** MSG parse (ustring, Object, parsepos ) error.");
    } else {
        if (fmta.keySet().size() != 2) {
            errln("*** MSG parse (ustring, count, err) count err.");
        } else {
            assertEquals("parse()[0]", "abc", fmta.get("foo"));
            assertEquals("parse()[1]", "def", fmta.get("bar"));
        }
    }
}
Also used : MessageFormat(android.icu.text.MessageFormat) AttributedString(java.text.AttributedString) ParseException(java.text.ParseException) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) ParsePosition(java.text.ParsePosition) Test(org.junit.Test)

Aggregations

MessageFormat (android.icu.text.MessageFormat)61 Test (org.junit.Test)53 AttributedString (java.text.AttributedString)24 HashMap (java.util.HashMap)15 FieldPosition (java.text.FieldPosition)12 ParsePosition (java.text.ParsePosition)10 Date (java.util.Date)10 ChoiceFormat (java.text.ChoiceFormat)9 ParseException (java.text.ParseException)9 IOException (java.io.IOException)7 Map (java.util.Map)7 TreeMap (java.util.TreeMap)6 SimpleDateFormat (android.icu.text.SimpleDateFormat)5 DateFormat (android.icu.text.DateFormat)4 DecimalFormat (android.icu.text.DecimalFormat)4 NumberFormat (android.icu.text.NumberFormat)4 UFormat (android.icu.text.UFormat)3 ULocale (android.icu.util.ULocale)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3