Home | History | Annotate | Download | only in text
      1 /*
      2  * Licensed to the Apache Software Foundation (ASF) under one or more
      3  * contributor license agreements.  See the NOTICE file distributed with
      4  * this work for additional information regarding copyright ownership.
      5  * The ASF licenses this file to You under the Apache License, Version 2.0
      6  * (the "License"); you may not use this file except in compliance with
      7  * the License.  You may obtain a copy of the License at
      8  *
      9  *     http://www.apache.org/licenses/LICENSE-2.0
     10  *
     11  * Unless required by applicable law or agreed to in writing, software
     12  * distributed under the License is distributed on an "AS IS" BASIS,
     13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14  * See the License for the specific language governing permissions and
     15  * limitations under the License.
     16  */
     17 
     18 package org.apache.harmony.text.tests.java.text;
     19 
     20 import dalvik.annotation.KnownFailure;
     21 import dalvik.annotation.TestLevel;
     22 import dalvik.annotation.TestTargetClass;
     23 import dalvik.annotation.TestTargetNew;
     24 
     25 import junit.framework.TestCase;
     26 
     27 import tests.support.Support_MessageFormat;
     28 
     29 import java.io.ByteArrayInputStream;
     30 import java.io.ByteArrayOutputStream;
     31 import java.io.IOException;
     32 import java.io.ObjectInputStream;
     33 import java.io.ObjectOutputStream;
     34 import java.text.ChoiceFormat;
     35 import java.text.DateFormat;
     36 import java.text.FieldPosition;
     37 import java.text.Format;
     38 import java.text.MessageFormat;
     39 import java.text.NumberFormat;
     40 import java.text.ParseException;
     41 import java.text.ParsePosition;
     42 import java.text.SimpleDateFormat;
     43 import java.util.Calendar;
     44 import java.util.Date;
     45 import java.util.GregorianCalendar;
     46 import java.util.Locale;
     47 import java.util.TimeZone;
     48 
     49 @TestTargetClass(MessageFormat.class)
     50 public class MessageFormatTest extends TestCase {
     51 
     52     private MessageFormat format1, format2, format3;
     53 
     54     private Locale defaultLocale;
     55 
     56     private void checkSerialization(MessageFormat format) {
     57         try {
     58             ByteArrayOutputStream ba = new ByteArrayOutputStream();
     59             ObjectOutputStream out = new ObjectOutputStream(ba);
     60             out.writeObject(format);
     61             out.close();
     62             ObjectInputStream in = new ObjectInputStream(
     63                     new ByteArrayInputStream(ba.toByteArray()));
     64             MessageFormat read = (MessageFormat) in.readObject();
     65             assertTrue("Not equal: " + format.toPattern(), format.equals(read));
     66         } catch (IOException e) {
     67             fail("Format: " + format.toPattern() + " caused IOException: " + e);
     68         } catch (ClassNotFoundException e) {
     69             fail("Format: " + format.toPattern()
     70                     + " caused ClassNotFoundException: " + e);
     71         }
     72     }
     73 
     74     /**
     75      * @tests java.text.MessageFormat#MessageFormat(java.lang.String,
     76      *        java.util.Locale)
     77      */
     78     @TestTargetNew(
     79         level = TestLevel.PARTIAL_COMPLETE,
     80         notes = "IllegalArgumentException is not verified.",
     81         method = "MessageFormat",
     82         args = {java.lang.String.class, java.util.Locale.class}
     83     )
     84     public void test_ConstructorLjava_lang_StringLjava_util_Locale() {
     85         // Test for method java.text.MessageFormat(java.lang.String,
     86         // java.util.Locale)
     87         Locale mk = new Locale("mk", "MK");
     88         MessageFormat format = new MessageFormat(
     89                 "Date: {0,date} Currency: {1, number, currency} Integer: {2, number, integer}",
     90                 mk);
     91 
     92         assertTrue("Wrong locale1", format.getLocale().equals(mk));
     93         assertTrue("Wrong locale2", format.getFormats()[0].equals(DateFormat
     94                 .getDateInstance(DateFormat.DEFAULT, mk)));
     95         assertTrue("Wrong locale3", format.getFormats()[1].equals(NumberFormat
     96                 .getCurrencyInstance(mk)));
     97         assertTrue("Wrong locale4", format.getFormats()[2].equals(NumberFormat
     98                 .getIntegerInstance(mk)));
     99     }
    100 
    101     /**
    102      * @tests java.text.MessageFormat#MessageFormat(java.lang.String)
    103      */
    104     @TestTargetNew(
    105         level = TestLevel.COMPLETE,
    106         method = "MessageFormat",
    107         args = {java.lang.String.class}
    108     )
    109     public void test_ConstructorLjava_lang_String() {
    110         // Test for method java.text.MessageFormat(java.lang.String)
    111         MessageFormat format = new MessageFormat(
    112                 "abc {4,time} def {3,date} ghi {2,number} jkl {1,choice,0#low|1#high} mnop {0}");
    113         assertTrue("Not a MessageFormat",
    114                 format.getClass() == MessageFormat.class);
    115         Format[] formats = format.getFormats();
    116         assertNotNull("null formats", formats);
    117         assertTrue("Wrong format count: " + formats.length, formats.length >= 5);
    118         assertTrue("Wrong time format", formats[0].equals(DateFormat
    119                 .getTimeInstance()));
    120         assertTrue("Wrong date format", formats[1].equals(DateFormat
    121                 .getDateInstance()));
    122         assertTrue("Wrong number format", formats[2].equals(NumberFormat
    123                 .getInstance()));
    124         assertTrue("Wrong choice format", formats[3].equals(new ChoiceFormat(
    125                 "0.0#low|1.0#high")));
    126         assertNull("Wrong string format", formats[4]);
    127 
    128         Date date = new Date();
    129         FieldPosition pos = new FieldPosition(-1);
    130         StringBuffer buffer = new StringBuffer();
    131         format.format(new Object[] { "123", new Double(1.6), new Double(7.2),
    132                 date, date }, buffer, pos);
    133         String result = buffer.toString();
    134         buffer.setLength(0);
    135         buffer.append("abc ");
    136         buffer.append(DateFormat.getTimeInstance().format(date));
    137         buffer.append(" def ");
    138         buffer.append(DateFormat.getDateInstance().format(date));
    139         buffer.append(" ghi ");
    140         buffer.append(NumberFormat.getInstance().format(new Double(7.2)));
    141         buffer.append(" jkl high mnop 123");
    142         assertTrue("Wrong answer:\n" + result + "\n" + buffer, result
    143                 .equals(buffer.toString()));
    144 
    145         assertEquals("Simple string", "Test message", new MessageFormat(
    146                 "Test message").format(new Object[0]));
    147 
    148         result = new MessageFormat("Don't").format(new Object[0]);
    149         assertTrue("Should not throw IllegalArgumentException: " + result,
    150                     "Dont".equals(result));
    151 
    152         try {
    153             new MessageFormat("Invalid {1,foobar} format descriptor!");
    154             fail("Expected test_ConstructorLjava_lang_String to throw IAE.");
    155         } catch (IllegalArgumentException ex) {
    156             // expected
    157         }
    158 
    159         try {
    160             new MessageFormat(
    161                     "Invalid {1,date,invalid-spec} format descriptor!");
    162         } catch (IllegalArgumentException ex) {
    163             // expected
    164         }
    165 
    166         checkSerialization(new MessageFormat(""));
    167         checkSerialization(new MessageFormat("noargs"));
    168         checkSerialization(new MessageFormat("{0}"));
    169         checkSerialization(new MessageFormat("a{0}"));
    170         checkSerialization(new MessageFormat("{0}b"));
    171         checkSerialization(new MessageFormat("a{0}b"));
    172 
    173         // Regression for HARMONY-65
    174         try {
    175             new MessageFormat("{0,number,integer");
    176             fail("Assert 0: Failed to detect unmatched brackets.");
    177         } catch (IllegalArgumentException e) {
    178             // expected
    179         }
    180     }
    181 
    182     /**
    183      * @tests java.text.MessageFormat#applyPattern(java.lang.String)
    184      */
    185     @TestTargetNew(
    186         level = TestLevel.COMPLETE,
    187         method = "applyPattern",
    188         args = {java.lang.String.class}
    189     )
    190     public void test_applyPatternLjava_lang_String() {
    191         // Test for method void
    192         // java.text.MessageFormat.applyPattern(java.lang.String)
    193         MessageFormat format = new MessageFormat("test");
    194         format.applyPattern("xx {0}");
    195         assertEquals("Invalid number", "xx 46", format
    196                 .format(new Object[] { new Integer(46) }));
    197         Date date = new Date();
    198         String result = format.format(new Object[] { date });
    199         String expected = "xx " + DateFormat.getInstance().format(date);
    200         assertTrue("Invalid date:\n" + result + "\n" + expected, result
    201                 .equals(expected));
    202         format = new MessageFormat("{0,date}{1,time}{2,number,integer}");
    203         format.applyPattern("nothing");
    204         assertEquals("Found formats", "nothing", format.toPattern());
    205 
    206         format.applyPattern("{0}");
    207         assertNull("Wrong format", format.getFormats()[0]);
    208         assertEquals("Wrong pattern", "{0}", format.toPattern());
    209 
    210         format.applyPattern("{0, \t\u001ftime }");
    211         assertTrue("Wrong time format", format.getFormats()[0]
    212                 .equals(DateFormat.getTimeInstance()));
    213         assertEquals("Wrong time pattern", "{0,time}", format.toPattern());
    214         format.applyPattern("{0,Time, Short\n}");
    215         assertTrue("Wrong short time format", format.getFormats()[0]
    216                 .equals(DateFormat.getTimeInstance(DateFormat.SHORT)));
    217         assertEquals("Wrong short time pattern", "{0,time,short}", format
    218                 .toPattern());
    219         format.applyPattern("{0,TIME,\nmedium  }");
    220         assertTrue("Wrong medium time format", format.getFormats()[0]
    221                 .equals(DateFormat.getTimeInstance(DateFormat.MEDIUM)));
    222         assertEquals("Wrong medium time pattern", "{0,time}", format
    223                 .toPattern());
    224         format.applyPattern("{0,time,LONG}");
    225         assertTrue("Wrong long time format", format.getFormats()[0]
    226                 .equals(DateFormat.getTimeInstance(DateFormat.LONG)));
    227         assertEquals("Wrong long time pattern", "{0,time,long}", format
    228                 .toPattern());
    229         format.setLocale(Locale.FRENCH); // use French since English has the
    230         // same LONG and FULL time patterns
    231         format.applyPattern("{0,time, Full}");
    232         assertTrue("Wrong full time format", format.getFormats()[0]
    233                 .equals(DateFormat.getTimeInstance(DateFormat.FULL,
    234                         Locale.FRENCH)));
    235 // Outsourced to _AndroidFailure:
    236 //
    237 //        assertEquals("Wrong full time pattern", "{0,time,full}", format
    238 //                .toPattern());
    239         format.setLocale(Locale.getDefault());
    240 
    241         format.applyPattern("{0, date}");
    242         assertTrue("Wrong date format", format.getFormats()[0]
    243                 .equals(DateFormat.getDateInstance()));
    244         assertEquals("Wrong date pattern", "{0,date}", format.toPattern());
    245         format.applyPattern("{0, date, short}");
    246         assertTrue("Wrong short date format", format.getFormats()[0]
    247                 .equals(DateFormat.getDateInstance(DateFormat.SHORT)));
    248         assertEquals("Wrong short date pattern", "{0,date,short}", format
    249                 .toPattern());
    250         format.applyPattern("{0, date, medium}");
    251         assertTrue("Wrong medium date format", format.getFormats()[0]
    252                 .equals(DateFormat.getDateInstance(DateFormat.MEDIUM)));
    253         assertEquals("Wrong medium date pattern", "{0,date}", format
    254                 .toPattern());
    255         format.applyPattern("{0, date, long}");
    256         assertTrue("Wrong long date format", format.getFormats()[0]
    257                 .equals(DateFormat.getDateInstance(DateFormat.LONG)));
    258         assertEquals("Wrong long date pattern", "{0,date,long}", format
    259                 .toPattern());
    260         format.applyPattern("{0, date, full}");
    261         assertTrue("Wrong full date format", format.getFormats()[0]
    262                 .equals(DateFormat.getDateInstance(DateFormat.FULL)));
    263         assertEquals("Wrong full date pattern", "{0,date,full}", format
    264                 .toPattern());
    265 
    266         format.applyPattern("{0, date, MMM d {hh:mm:ss}}");
    267         assertEquals("Wrong time/date format", " MMM d {hh:mm:ss}",
    268                 ((SimpleDateFormat) (format.getFormats()[0])).toPattern());
    269         assertEquals("Wrong time/date pattern", "{0,date, MMM d {hh:mm:ss}}",
    270                 format.toPattern());
    271 
    272         format.applyPattern("{0, number}");
    273         assertTrue("Wrong number format", format.getFormats()[0]
    274                 .equals(NumberFormat.getNumberInstance()));
    275         assertEquals("Wrong number pattern", "{0,number}", format.toPattern());
    276         format.applyPattern("{0, number, currency}");
    277         assertTrue("Wrong currency number format", format.getFormats()[0]
    278                 .equals(NumberFormat.getCurrencyInstance()));
    279         assertEquals("Wrong currency number pattern", "{0,number,currency}",
    280                 format.toPattern());
    281         format.applyPattern("{0, number, percent}");
    282         assertTrue("Wrong percent number format", format.getFormats()[0]
    283                 .equals(NumberFormat.getPercentInstance()));
    284         assertEquals("Wrong percent number pattern", "{0,number,percent}",
    285                 format.toPattern());
    286         format.applyPattern("{0, number, integer}");
    287         NumberFormat nf = NumberFormat.getInstance();
    288         nf.setMaximumFractionDigits(0);
    289         nf.setParseIntegerOnly(true);
    290         assertTrue("Wrong integer number format", format.getFormats()[0]
    291                 .equals(nf));
    292         assertEquals("Wrong integer number pattern", "{0,number,integer}",
    293                 format.toPattern());
    294 
    295         format.applyPattern("{0, number, {'#'}##0.0E0}");
    296 
    297         /*
    298          * TODO validate these assertions String actual =
    299          * ((DecimalFormat)(format.getFormats()[0])).toPattern();
    300          * assertEquals("Wrong pattern number format", "' {#}'##0.0E0", actual);
    301          * assertEquals("Wrong pattern number pattern", "{0,number,'
    302          * {#}'##0.0E0}", format.toPattern());
    303          *
    304          */
    305 
    306         format.applyPattern("{0, choice,0#no|1#one|2#{1,number}}");
    307         assertEquals("Wrong choice format",
    308 
    309         "0.0#no|1.0#one|2.0#{1,number}",
    310                 ((ChoiceFormat) format.getFormats()[0]).toPattern());
    311         assertEquals("Wrong choice pattern",
    312                 "{0,choice,0.0#no|1.0#one|2.0#{1,number}}", format.toPattern());
    313         assertEquals("Wrong formatted choice", "3.6", format
    314                 .format(new Object[] { new Integer(2), new Float(3.6) }));
    315 
    316         try {
    317             format.applyPattern("WRONG MESSAGE FORMAT {0,number,{}");
    318             fail("Expected IllegalArgumentException for invalid pattern");
    319         } catch (IllegalArgumentException e) {
    320         }
    321 
    322         // Regression for HARMONY-65
    323         MessageFormat mf = new MessageFormat("{0,number,integer}");
    324         String badpattern = "{0,number,#";
    325         try {
    326             mf.applyPattern(badpattern);
    327             fail("Assert 0: Failed to detect unmatched brackets.");
    328         } catch (IllegalArgumentException e) {
    329             // expected
    330         }
    331     }
    332 
    333     @TestTargetNew(
    334         level = TestLevel.COMPLETE,
    335         method = "applyPattern",
    336         args = {java.lang.String.class}
    337     )
    338     public void test_applyPatternLjava_lang_String_AndroidFailure() {
    339         MessageFormat format = new MessageFormat("test");
    340         format.setLocale(Locale.FRENCH); // use French since English has the
    341         // same LONG and FULL time patterns
    342         format.applyPattern("{0,time, Full}");
    343         assertEquals("Wrong full time pattern", "{0,time,full}", format
    344                 .toPattern());
    345     }
    346 
    347     /**
    348      * @tests java.text.MessageFormat#clone()
    349      */
    350     @TestTargetNew(
    351         level = TestLevel.COMPLETE,
    352         notes = "",
    353         method = "clone",
    354         args = {}
    355     )
    356     public void test_clone() {
    357         // Test for method java.lang.Object java.text.MessageFormat.clone()
    358         MessageFormat format = new MessageFormat("'{'choice'}'{0}");
    359         MessageFormat clone = (MessageFormat) format.clone();
    360         assertTrue("Clone not equal", format.equals(clone));
    361         assertEquals("Wrong answer", "{choice}{0}", format
    362                 .format(new Object[] {}));
    363         clone.setFormat(0, DateFormat.getInstance());
    364         assertTrue("Clone shares format data", !format.equals(clone));
    365         format = (MessageFormat) clone.clone();
    366         Format[] formats = clone.getFormats();
    367         ((SimpleDateFormat) formats[0]).applyPattern("adk123");
    368         assertTrue("Clone shares format data", !format.equals(clone));
    369     }
    370 
    371     /**
    372      * @tests java.text.MessageFormat#equals(java.lang.Object)
    373      */
    374     @TestTargetNew(
    375         level = TestLevel.COMPLETE,
    376         method = "equals",
    377         args = {java.lang.Object.class}
    378     )
    379     public void test_equalsLjava_lang_Object() {
    380         // Test for method boolean
    381         // java.text.MessageFormat.equals(java.lang.Object)
    382         MessageFormat format1 = new MessageFormat("{0}");
    383         MessageFormat format2 = new MessageFormat("{1}");
    384         assertTrue("Should not be equal", !format1.equals(format2));
    385         format2.applyPattern("{0}");
    386         assertTrue("Should be equal", format1.equals(format2));
    387         SimpleDateFormat date = (SimpleDateFormat) DateFormat.getTimeInstance();
    388         format1.setFormat(0, DateFormat.getTimeInstance());
    389         format2.setFormat(0, new SimpleDateFormat(date.toPattern()));
    390         assertTrue("Should be equal2", format1.equals(format2));
    391     }
    392 
    393     /**
    394      * @tests java.text.MessageFormat#hashCode()
    395      */
    396     @TestTargetNew(
    397         level = TestLevel.COMPLETE,
    398         notes = "",
    399         method = "hashCode",
    400         args = {}
    401     )
    402     public void test_hashCode() {
    403         // Test for method
    404         // int java.text.MessageFormat.hashCode()
    405         assertEquals("Should be equal", 3648, new MessageFormat("rr", null)
    406                 .hashCode());
    407     }
    408 
    409     /**
    410      * @tests java.text.MessageFormat#formatToCharacterIterator(java.lang.Object)
    411      */
    412     @TestTargetNew(
    413         level = TestLevel.COMPLETE,
    414         notes = "",
    415         method = "formatToCharacterIterator",
    416         args = {java.lang.Object.class}
    417     )
    418     // FIXME This test fails on Harmony ClassLibrary
    419     public void test_formatToCharacterIteratorLjava_lang_Object() {
    420         // Test for method formatToCharacterIterator(java.lang.Object)
    421         new Support_MessageFormat(
    422                 "test_formatToCharacterIteratorLjava_lang_Object")
    423                 .t_formatToCharacterIterator();
    424 
    425         try {
    426             new MessageFormat("{1, number}").formatToCharacterIterator(null);
    427             fail("NullPointerException was not thrown.");
    428         } catch(NullPointerException npe) {
    429             //expected
    430         }
    431 
    432         try {
    433             new MessageFormat("{0, time}").formatToCharacterIterator(new Object[]{""});
    434             fail("IllegalArgumentException was not thrown.");
    435         } catch(IllegalArgumentException iae) {
    436             //expected
    437         }
    438     }
    439 
    440     /**
    441      * @tests java.text.MessageFormat#format(java.lang.Object[],
    442      *        java.lang.StringBuffer, java.text.FieldPosition)
    443      */
    444     @TestTargetNew(
    445         level = TestLevel.COMPLETE,
    446         notes = "",
    447         method = "format",
    448         args = {java.lang.Object[].class, java.lang.StringBuffer.class, java.text.FieldPosition.class}
    449     )
    450     public void test_format$Ljava_lang_ObjectLjava_lang_StringBufferLjava_text_FieldPosition() {
    451         // Test for method java.lang.StringBuffer
    452         // java.text.MessageFormat.format(java.lang.Object [],
    453         // java.lang.StringBuffer, java.text.FieldPosition)
    454         MessageFormat format = new MessageFormat("{1,number,integer}");
    455         StringBuffer buffer = new StringBuffer();
    456         format.format(new Object[] { "0", new Double(53.863) }, buffer,
    457                 new FieldPosition(MessageFormat.Field.ARGUMENT));
    458         assertEquals("Wrong result", "54", buffer.toString());
    459 
    460         format.format(new Object[] { "0", new Double(53.863) }, buffer,
    461                 new FieldPosition(MessageFormat.Field.ARGUMENT));
    462 
    463         assertEquals("Wrong result", "5454", buffer.toString());
    464 
    465         buffer = new StringBuffer();
    466         format
    467                 .applyPattern("{0,choice,0#zero|1#one '{1,choice,2#two {2,time}}'}");
    468         Date date = new Date();
    469         String expected = "one two "
    470                 + DateFormat.getTimeInstance().format(date);
    471         format.format(new Object[] { new Double(1.6),
    472                 new Integer(3), date }, buffer, new FieldPosition(MessageFormat
    473                         .Field.ARGUMENT));
    474         assertEquals("Choice not recursive:\n" + expected + "\n" + buffer,
    475                 expected, buffer.toString());
    476 
    477         StringBuffer str = format.format(new Object[] { new Double(0.6),
    478                 new Integer(3)}, buffer, null);
    479 
    480         assertEquals(expected + "zero", str.toString());
    481         assertEquals(expected + "zero", buffer.toString());
    482 
    483         try {
    484             format.format(new Object[] { "0", new Double(1), "" }, buffer,
    485                     new FieldPosition(MessageFormat.Field.ARGUMENT));
    486             fail("IllegalArgumentException was not thrown.");
    487         } catch(IllegalArgumentException iae) {
    488             //expected
    489         }
    490 
    491         try {
    492             format.format(new Object[] { "",  new Integer(3)}, buffer,
    493                     new FieldPosition(MessageFormat.Field.ARGUMENT));
    494             fail("IllegalArgumentException was not thrown.");
    495         } catch(IllegalArgumentException iae) {
    496             //expected
    497         }
    498     }
    499 
    500     /**
    501      * @tests java.text.MessageFormat#format(java.lang.Object,
    502      *        java.lang.StringBuffer, java.text.FieldPosition)
    503      */
    504     @TestTargetNew(
    505         level = TestLevel.COMPLETE,
    506         notes = "",
    507         method = "format",
    508         args = {java.lang.Object.class, java.lang.StringBuffer.class, java.text.FieldPosition.class}
    509     )
    510     public void test_formatLjava_lang_ObjectLjava_lang_StringBufferLjava_text_FieldPosition() {
    511         // Test for method java.lang.StringBuffer
    512         // java.text.MessageFormat.format(java.lang.Object,
    513         // java.lang.StringBuffer, java.text.FieldPosition)
    514         new Support_MessageFormat(
    515                 "test_formatLjava_lang_ObjectLjava_lang_StringBufferLjava_text_FieldPosition")
    516                 .t_format_with_FieldPosition();
    517 
    518         String pattern = "On {4,date} at {3,time}, he ate {2,number, integer} " +
    519                 "hamburger{2,choice,1#|1<s}.";
    520         MessageFormat format = new MessageFormat(pattern, Locale.US);
    521 
    522         Object[] objects = new Object[] { "", new Integer(3), 8, ""};
    523 
    524         try {
    525             format.format(objects, new StringBuffer(),
    526                     new FieldPosition(DateFormat.Field.AM_PM));
    527             fail("IllegalArgumentException was not thrown.");
    528         } catch(IllegalArgumentException iae) {
    529             //expected
    530         }
    531     }
    532 
    533     /**
    534      * @tests java.text.MessageFormat#format(java.lang.String,
    535      *        java.lang.Object...) Test of method
    536      *        java.text.MessageFormat#format(java.lang.String,
    537      *        java.lang.Object...).
    538      */
    539     @TestTargetNew(
    540         level = TestLevel.COMPLETE,
    541         notes = "",
    542         method = "format",
    543         args = {java.lang.String.class, java.lang.Object[].class}
    544     )
    545     public void test_formatLjava_lang_StringLjava_lang_Object() {
    546         int iCurrency = 123;
    547         int iInteger  = Integer.MIN_VALUE;
    548 
    549         Date     date     = new Date(12345678);
    550         Object[] args     = { date, iCurrency, iInteger };
    551         String   resStr   = "Date: Jan 1, 1970 Currency: $" + iCurrency
    552                     + ".00 Integer: -2,147,483,648";
    553         String   pattern  = "Date: {0,date} Currency: {1, number, currency} Integer: {2, number, integer}";
    554         String   sFormat  = MessageFormat.format(pattern, (Object[]) args);
    555         assertEquals(
    556                 "format(String, Object[]) with valid parameters returns incorrect string: case 1",
    557                 sFormat, resStr);
    558 
    559         pattern = "abc {4, number, integer} def {3,date} ghi {2,number} jkl {1,choice,0#low|1#high} mnop {0}";
    560         resStr  = "abc -2,147,483,648 def Jan 1, 1970 ghi -2,147,483,648 jkl high mnop -2,147,483,648";
    561         Object[] args_ = { iInteger, 1, iInteger, date, iInteger };
    562         sFormat = MessageFormat.format(pattern, args_);
    563         assertEquals(
    564                 "format(String, Object[]) with valid parameters returns incorrect string: case 1",
    565                 sFormat, resStr);
    566 
    567         try {
    568             args = null;
    569             MessageFormat.format(null, args);
    570             fail("Doesn't throw IllegalArgumentException: null, null");
    571         } catch (Exception e) {
    572             // expected
    573         }
    574 
    575         try {
    576             MessageFormat.format("Invalid {1,foobar} format descriptor!",
    577                     new Object[] {iInteger} );
    578             fail("Doesn't throw IllegalArgumentException with invalid pattern as a parameter: case 1");
    579         } catch (IllegalArgumentException ex) {
    580             // expected
    581         }
    582 
    583         try {
    584             MessageFormat.format(
    585                     "Invalid {1,date,invalid-spec} format descriptor!", new Object[]{""});
    586             fail("Doesn't throw IllegalArgumentException with invalid pattern as a parameter: case 2");
    587         } catch (IllegalArgumentException ex) {
    588             // expected
    589         }
    590 
    591         try {
    592             MessageFormat.format("{0,number,integer", new Object[] {iInteger});
    593             fail("Doesn't throw IllegalArgumentException, doesn't detect unmatched brackets");
    594         } catch (IllegalArgumentException ex) {
    595             // expected
    596         }
    597 
    598         try {
    599             MessageFormat.format(
    600                     "Valid {1, date} format {0, number} descriptor!", new Object[]{ "" } );
    601             fail("Doesn't throw IllegalArgumentException with invalid Object array");
    602         } catch (IllegalArgumentException ex) {
    603             // expected
    604         }
    605     }
    606 
    607     /**
    608      * @tests java.text.MessageFormat#getFormats()
    609      */
    610     @TestTargetNew(
    611         level = TestLevel.COMPLETE,
    612         notes = "",
    613         method = "getFormats",
    614         args = {}
    615     )
    616     public void test_getFormats() {
    617         // Test for method java.text.Format []
    618         // java.text.MessageFormat.getFormats()
    619 
    620         // test with repeating formats and max argument index < max offset
    621         Format[] formats = format1.getFormats();
    622         Format[] correctFormats = new Format[] {
    623                 NumberFormat.getCurrencyInstance(),
    624                 DateFormat.getTimeInstance(),
    625                 NumberFormat.getPercentInstance(), null,
    626                 new ChoiceFormat("0#off|1#on"), DateFormat.getDateInstance(), };
    627 
    628         assertEquals("Test1:Returned wrong number of formats:",
    629                 correctFormats.length, formats.length);
    630         for (int i = 0; i < correctFormats.length; i++) {
    631             assertEquals("Test1:wrong format for pattern index " + i + ":",
    632                     correctFormats[i], formats[i]);
    633         }
    634 
    635         // test with max argument index > max offset
    636         formats = format2.getFormats();
    637         correctFormats = new Format[] { NumberFormat.getCurrencyInstance(),
    638                 DateFormat.getTimeInstance(),
    639                 NumberFormat.getPercentInstance(), null,
    640                 new ChoiceFormat("0#off|1#on"), DateFormat.getDateInstance() };
    641 
    642         assertEquals("Test2:Returned wrong number of formats:",
    643                 correctFormats.length, formats.length);
    644         for (int i = 0; i < correctFormats.length; i++) {
    645             assertEquals("Test2:wrong format for pattern index " + i + ":",
    646                     correctFormats[i], formats[i]);
    647         }
    648 
    649         // test with argument number being zero
    650         formats = format3.getFormats();
    651         assertEquals("Test3: Returned wrong number of formats:", 0,
    652                 formats.length);
    653     }
    654 
    655     /**
    656      * @tests java.text.MessageFormat#getFormatsByArgumentIndex()
    657      */
    658     @TestTargetNew(
    659         level = TestLevel.COMPLETE,
    660         notes = "",
    661         method = "getFormatsByArgumentIndex",
    662         args = {}
    663     )
    664     public void test_getFormatsByArgumentIndex() {
    665         // Test for method java.text.Format [] test_getFormatsByArgumentIndex()
    666 
    667         // test with repeating formats and max argument index < max offset
    668         Format[] formats = format1.getFormatsByArgumentIndex();
    669         Format[] correctFormats = new Format[] { DateFormat.getDateInstance(),
    670                 new ChoiceFormat("0#off|1#on"), DateFormat.getTimeInstance(),
    671                 NumberFormat.getCurrencyInstance(), null };
    672 
    673         assertEquals("Test1:Returned wrong number of formats:",
    674                 correctFormats.length, formats.length);
    675         for (int i = 0; i < correctFormats.length; i++) {
    676             assertEquals("Test1:wrong format for argument index " + i + ":",
    677                     correctFormats[i], formats[i]);
    678         }
    679 
    680         // test with max argument index > max offset
    681         formats = format2.getFormatsByArgumentIndex();
    682         correctFormats = new Format[] { DateFormat.getDateInstance(),
    683                 new ChoiceFormat("0#off|1#on"), null,
    684                 NumberFormat.getCurrencyInstance(), null, null, null, null,
    685                 DateFormat.getTimeInstance() };
    686 
    687         assertEquals("Test2:Returned wrong number of formats:",
    688                 correctFormats.length, formats.length);
    689         for (int i = 0; i < correctFormats.length; i++) {
    690             assertEquals("Test2:wrong format for argument index " + i + ":",
    691                     correctFormats[i], formats[i]);
    692         }
    693 
    694         // test with argument number being zero
    695         formats = format3.getFormatsByArgumentIndex();
    696         assertEquals("Test3: Returned wrong number of formats:", 0,
    697                 formats.length);
    698     }
    699 
    700     /**
    701      * @tests java.text.MessageFormat#getLocale() Test of method
    702      *        java.text.MessageFormat#getLocale().
    703      */
    704     @TestTargetNew(
    705         level = TestLevel.COMPLETE,
    706         notes = "",
    707         method = "getLocale",
    708         args = {}
    709     )
    710     public void test_getLocale() {
    711         try {
    712             Locale[] l = {
    713                     Locale.FRANCE,
    714                     Locale.KOREA,
    715                     new Locale(Locale.FRANCE.getCountry(), Locale.FRANCE
    716                             .getLanguage()), new Locale("mk"),
    717                     new Locale("mk", "MK"), Locale.US,
    718                     new Locale("#ru", "@31230") };
    719 
    720             String pattern = "getLocale test {0,number,#,####}";
    721             MessageFormat mf;
    722 
    723             for (int i = 0; i < 0; i++) {
    724                 mf = new MessageFormat(pattern, l[i]);
    725                 Locale result = mf.getLocale();
    726                 assertEquals("Returned local: " + result + " instead of "
    727                         + l[i], l[i], result);
    728                 assertEquals("Returned language: " + result.getLanguage()
    729                         + " instead of " + l[i].getLanguage(), l[i]
    730                         .getLanguage(), result.getLanguage());
    731                 assertEquals("Returned country: " + result.getCountry()
    732                         + " instead of " + l[i].getCountry(),
    733                         l[i].getCountry(), result.getCountry());
    734             }
    735 
    736             mf = new MessageFormat(pattern);
    737             mf.setLocale(null);
    738             Locale result = mf.getLocale();
    739             assertEquals("Returned local: " + result + " instead of null",
    740                     null, result);
    741         } catch (Exception e) {
    742             fail("unexpected exception " + e.toString());
    743         }
    744     }
    745 
    746     /**
    747      * @tests java.text.MessageFormat#setFormat(int, Format) Test of method
    748      *        java.text.MessageFormat#setFormat(int, Format). Case 1: Compare
    749      *        getFormats() results after calls to setFormat(). Case 2: Try to
    750      *        call setFormat() using incorrect index.
    751      */
    752     @TestTargetNew(
    753         level = TestLevel.COMPLETE,
    754         notes = "",
    755         method = "setFormat",
    756         args = {int.class, java.text.Format.class}
    757     )
    758     public void test_setFormatILjava_text_Format() {
    759         try {
    760             // case 1: Compare getFormats() results after calls to setFormat()
    761             MessageFormat f1 = (MessageFormat) format1.clone();
    762             f1.setFormat(0, DateFormat.getTimeInstance());
    763             f1.setFormat(1, DateFormat.getTimeInstance());
    764             f1.setFormat(2, NumberFormat.getInstance());
    765             f1.setFormat(3, new ChoiceFormat("0#off|1#on"));
    766             f1.setFormat(4, new ChoiceFormat("1#few|2#ok|3#a lot"));
    767             f1.setFormat(5, DateFormat.getTimeInstance());
    768 
    769             Format[] formats = f1.getFormats();
    770             formats = f1.getFormats();
    771 
    772             Format[] correctFormats = new Format[] {
    773                     DateFormat.getTimeInstance(), DateFormat.getTimeInstance(),
    774                     NumberFormat.getInstance(), new ChoiceFormat("0#off|1#on"),
    775                     new ChoiceFormat("1#few|2#ok|3#a lot"),
    776                     DateFormat.getTimeInstance() };
    777 
    778             assertEquals("Test1A:Returned wrong number of formats:",
    779                     correctFormats.length, formats.length);
    780             for (int i = 0; i < correctFormats.length; i++) {
    781                 assertEquals(
    782                         "Test1B:wrong format for pattern index " + i + ":",
    783                         correctFormats[i], formats[i]);
    784             }
    785 
    786             // case 2: Try to setFormat using incorrect index
    787             try {
    788                 f1.setFormat(-1, DateFormat.getDateInstance());
    789                 fail("Expected ArrayIndexOutOfBoundsException was not thrown");
    790                 f1.setFormat(f1.getFormats().length, DateFormat
    791                         .getDateInstance());
    792                 fail("Expected ArrayIndexOutOfBoundsException was not thrown");
    793             } catch (ArrayIndexOutOfBoundsException e) {
    794                 // expected
    795             }
    796         } catch (Exception e) {
    797             fail("Unexpected exception " + e.toString());
    798         }
    799     }
    800 
    801     /**
    802      * @tests java.text.MessageFormat#setFormatByArgumentIndex(int,
    803      *        java.text.Format)
    804      */
    805     @TestTargetNew(
    806         level = TestLevel.COMPLETE,
    807         notes = "",
    808         method = "setFormatByArgumentIndex",
    809         args = {int.class, java.text.Format.class}
    810     )
    811     public void test_setFormatByArgumentIndexILjava_text_Format() {
    812         // test for method setFormatByArgumentIndex(int, Format)
    813         MessageFormat f1 = (MessageFormat) format1.clone();
    814         f1.setFormatByArgumentIndex(0, DateFormat.getTimeInstance());
    815         f1.setFormatByArgumentIndex(4, new ChoiceFormat("1#few|2#ok|3#a lot"));
    816 
    817         // test with repeating formats and max argument index < max offset
    818         // compare getFormatsByArgumentIndex() results after calls to
    819         // setFormatByArgumentIndex()
    820         Format[] formats = f1.getFormatsByArgumentIndex();
    821 
    822         Format[] correctFormats = new Format[] { DateFormat.getTimeInstance(),
    823                 new ChoiceFormat("0#off|1#on"), DateFormat.getTimeInstance(),
    824                 NumberFormat.getCurrencyInstance(),
    825                 new ChoiceFormat("1#few|2#ok|3#a lot") };
    826 
    827         assertEquals("Test1A:Returned wrong number of formats:",
    828                 correctFormats.length, formats.length);
    829         for (int i = 0; i < correctFormats.length; i++) {
    830             assertEquals("Test1B:wrong format for argument index " + i + ":",
    831                     correctFormats[i], formats[i]);
    832         }
    833 
    834         // compare getFormats() results after calls to
    835         // setFormatByArgumentIndex()
    836         formats = f1.getFormats();
    837 
    838         correctFormats = new Format[] { NumberFormat.getCurrencyInstance(),
    839                 DateFormat.getTimeInstance(), DateFormat.getTimeInstance(),
    840                 new ChoiceFormat("1#few|2#ok|3#a lot"),
    841                 new ChoiceFormat("0#off|1#on"), DateFormat.getTimeInstance(), };
    842 
    843         assertEquals("Test1C:Returned wrong number of formats:",
    844                 correctFormats.length, formats.length);
    845         for (int i = 0; i < correctFormats.length; i++) {
    846             assertEquals("Test1D:wrong format for pattern index " + i + ":",
    847                     correctFormats[i], formats[i]);
    848         }
    849 
    850         // test setting argumentIndexes that are not used
    851         MessageFormat f2 = (MessageFormat) format2.clone();
    852         f2.setFormatByArgumentIndex(2, NumberFormat.getPercentInstance());
    853         f2.setFormatByArgumentIndex(4, DateFormat.getTimeInstance());
    854 
    855         formats = f2.getFormatsByArgumentIndex();
    856         correctFormats = format2.getFormatsByArgumentIndex();
    857 
    858         assertEquals("Test2A:Returned wrong number of formats:",
    859                 correctFormats.length, formats.length);
    860         for (int i = 0; i < correctFormats.length; i++) {
    861             assertEquals("Test2B:wrong format for argument index " + i + ":",
    862                     correctFormats[i], formats[i]);
    863         }
    864 
    865         formats = f2.getFormats();
    866         correctFormats = format2.getFormats();
    867 
    868         assertEquals("Test2C:Returned wrong number of formats:",
    869                 correctFormats.length, formats.length);
    870         for (int i = 0; i < correctFormats.length; i++) {
    871             assertEquals("Test2D:wrong format for pattern index " + i + ":",
    872                     correctFormats[i], formats[i]);
    873         }
    874 
    875         // test exceeding the argumentIndex number
    876         MessageFormat f3 = (MessageFormat) format3.clone();
    877         f3.setFormatByArgumentIndex(1, NumberFormat.getCurrencyInstance());
    878 
    879         formats = f3.getFormatsByArgumentIndex();
    880         assertEquals("Test3A:Returned wrong number of formats:", 0,
    881                 formats.length);
    882 
    883         formats = f3.getFormats();
    884         assertEquals("Test3B:Returned wrong number of formats:", 0,
    885                 formats.length);
    886     }
    887 
    888     /**
    889      * @tests java.text.MessageFormat#setFormats(Format[]) Test of method
    890      *        java.text.MessageFormat#setFormats(Format[]). Case 1: Test with
    891      *        repeating formats and max argument index < max offset compare
    892      *        getFormats() results after calls to setFormats(Format[]) Case 2:
    893      *        Try to pass null argument to setFormats().
    894      */
    895     @TestTargetNew(
    896         level = TestLevel.COMPLETE,
    897         notes = "",
    898         method = "setFormats",
    899         args = {java.text.Format[].class}
    900     )
    901     public void test_setFormats$Ljava_text_Format() {
    902         try {
    903             MessageFormat f1 = (MessageFormat) format1.clone();
    904 
    905             // case 1: Test with repeating formats and max argument index < max
    906             // offset
    907             // compare getFormats() results after calls to setFormats(Format[])
    908             Format[] correctFormats = new Format[] {
    909                     DateFormat.getTimeInstance(),
    910                     new ChoiceFormat("0#off|1#on"),
    911                     DateFormat.getTimeInstance(),
    912                     NumberFormat.getCurrencyInstance(),
    913                     new ChoiceFormat("1#few|2#ok|3#a lot") };
    914 
    915             f1.setFormats(correctFormats);
    916             Format[] formats = f1.getFormats();
    917 
    918             assertTrue("Test1A:Returned wrong number of formats:",
    919                     correctFormats.length <= formats.length);
    920             for (int i = 0; i < correctFormats.length; i++) {
    921                 assertEquals("Test1B:wrong format for argument index " + i
    922                         + ":", correctFormats[i], formats[i]);
    923             }
    924 
    925             // case 2: Try to pass null argument to setFormats().
    926             try {
    927                 f1.setFormats(null);
    928                 fail("Expected exception NullPointerException was not thrown");
    929             } catch (NullPointerException e) {
    930                 // expected
    931             }
    932         } catch (Exception e) {
    933             fail("Unexpected exception " + e.toString());
    934         }
    935     }
    936 
    937     /**
    938      * @tests java.text.MessageFormat#setFormatsByArgumentIndex(java.text.Format[])
    939      */
    940     @TestTargetNew(
    941         level = TestLevel.COMPLETE,
    942         notes = "",
    943         method = "setFormatsByArgumentIndex",
    944         args = {java.text.Format[].class}
    945     )
    946     public void test_setFormatsByArgumentIndex$Ljava_text_Format() {
    947         // test for method setFormatByArgumentIndex(Format[])
    948         MessageFormat f1 = (MessageFormat) format1.clone();
    949 
    950         // test with repeating formats and max argument index < max offset
    951         // compare getFormatsByArgumentIndex() results after calls to
    952         // setFormatsByArgumentIndex(Format[])
    953         Format[] correctFormats = new Format[] { DateFormat.getTimeInstance(),
    954                 new ChoiceFormat("0#off|1#on"), DateFormat.getTimeInstance(),
    955                 NumberFormat.getCurrencyInstance(),
    956                 new ChoiceFormat("1#few|2#ok|3#a lot") };
    957 
    958         f1.setFormatsByArgumentIndex(correctFormats);
    959         Format[] formats = f1.getFormatsByArgumentIndex();
    960 
    961         assertEquals("Test1A:Returned wrong number of formats:",
    962                 correctFormats.length, formats.length);
    963         for (int i = 0; i < correctFormats.length; i++) {
    964             assertEquals("Test1B:wrong format for argument index " + i + ":",
    965                     correctFormats[i], formats[i]);
    966         }
    967 
    968         // compare getFormats() results after calls to
    969         // setFormatByArgumentIndex()
    970         formats = f1.getFormats();
    971         correctFormats = new Format[] { NumberFormat.getCurrencyInstance(),
    972                 DateFormat.getTimeInstance(), DateFormat.getTimeInstance(),
    973                 new ChoiceFormat("1#few|2#ok|3#a lot"),
    974                 new ChoiceFormat("0#off|1#on"), DateFormat.getTimeInstance(), };
    975 
    976         assertEquals("Test1C:Returned wrong number of formats:",
    977                 correctFormats.length, formats.length);
    978         for (int i = 0; i < correctFormats.length; i++) {
    979             assertEquals("Test1D:wrong format for pattern index " + i + ":",
    980                     correctFormats[i], formats[i]);
    981         }
    982 
    983         // test setting argumentIndexes that are not used
    984         MessageFormat f2 = (MessageFormat) format2.clone();
    985         Format[] inputFormats = new Format[] { DateFormat.getDateInstance(),
    986                 new ChoiceFormat("0#off|1#on"),
    987                 NumberFormat.getPercentInstance(),
    988                 NumberFormat.getCurrencyInstance(),
    989                 DateFormat.getTimeInstance(), null, null, null,
    990                 DateFormat.getTimeInstance() };
    991         f2.setFormatsByArgumentIndex(inputFormats);
    992 
    993         formats = f2.getFormatsByArgumentIndex();
    994         correctFormats = format2.getFormatsByArgumentIndex();
    995 
    996         assertEquals("Test2A:Returned wrong number of formats:",
    997                 correctFormats.length, formats.length);
    998         for (int i = 0; i < correctFormats.length; i++) {
    999             assertEquals("Test2B:wrong format for argument index " + i + ":",
   1000                     correctFormats[i], formats[i]);
   1001         }
   1002 
   1003         formats = f2.getFormats();
   1004         correctFormats = new Format[] { NumberFormat.getCurrencyInstance(),
   1005                 DateFormat.getTimeInstance(), DateFormat.getDateInstance(),
   1006                 null, new ChoiceFormat("0#off|1#on"),
   1007                 DateFormat.getDateInstance() };
   1008 
   1009         assertEquals("Test2C:Returned wrong number of formats:",
   1010                 correctFormats.length, formats.length);
   1011         for (int i = 0; i < correctFormats.length; i++) {
   1012             assertEquals("Test2D:wrong format for pattern index " + i + ":",
   1013                     correctFormats[i], formats[i]);
   1014         }
   1015 
   1016         // test exceeding the argumentIndex number
   1017         MessageFormat f3 = (MessageFormat) format3.clone();
   1018         f3.setFormatsByArgumentIndex(inputFormats);
   1019 
   1020         formats = f3.getFormatsByArgumentIndex();
   1021         assertEquals("Test3A:Returned wrong number of formats:", 0,
   1022                 formats.length);
   1023 
   1024         formats = f3.getFormats();
   1025         assertEquals("Test3B:Returned wrong number of formats:", 0,
   1026                 formats.length);
   1027 
   1028     }
   1029 
   1030     /**
   1031      * @tests java.text.MessageFormat#parse(java.lang.String,
   1032      *        java.text.ParsePosition)
   1033      */
   1034     @TestTargetNew(
   1035         level = TestLevel.COMPLETE,
   1036         notes = "",
   1037         method = "parse",
   1038         args = {java.lang.String.class, java.text.ParsePosition.class}
   1039     )
   1040     public void test_parseLjava_lang_StringLjava_text_ParsePosition() {
   1041         // Test for method java.lang.Object []
   1042         // java.text.MessageFormat.parse(java.lang.String,
   1043         // java.text.ParsePosition)
   1044         MessageFormat format = new MessageFormat("date is {0,date,MMM d, yyyy}");
   1045         ParsePosition pos = new ParsePosition(2);
   1046         Object[] result = (Object[]) format
   1047                 .parse("xxdate is Feb 28, 1999", pos);
   1048         assertTrue("No result: " + result.length, result.length >= 1);
   1049         assertTrue("Wrong answer", ((Date) result[0])
   1050                 .equals(new GregorianCalendar(1999, Calendar.FEBRUARY, 28)
   1051                         .getTime()));
   1052 
   1053         MessageFormat mf = new MessageFormat("vm={0},{1},{2}");
   1054         result = mf.parse("vm=win,foo,bar", new ParsePosition(0));
   1055         assertTrue("Invalid parse", result[0].equals("win")
   1056                 && result[1].equals("foo") && result[2].equals("bar"));
   1057 
   1058         mf = new MessageFormat("{0}; {0}; {0}");
   1059         String parse = "a; b; c";
   1060         result = mf.parse(parse, new ParsePosition(0));
   1061         assertEquals("Wrong variable result", "c", result[0]);
   1062 
   1063         try {
   1064             mf.parse(parse, null);
   1065             fail("NullPointerException was not thrown.");
   1066         } catch(NullPointerException npe) {
   1067             //expected
   1068         }
   1069 
   1070         try {
   1071             mf.parse(null, pos);
   1072         } catch(NullPointerException npe) {
   1073             fail("NullPointerException was thrown.");
   1074         }
   1075     }
   1076 
   1077     /**
   1078      * @tests java.text.MessageFormat#setLocale(java.util.Locale)
   1079      */
   1080     @TestTargetNew(
   1081         level = TestLevel.COMPLETE,
   1082         notes = "",
   1083         method = "setLocale",
   1084         args = {java.util.Locale.class}
   1085     )
   1086     public void test_setLocaleLjava_util_Locale() {
   1087         // Test for method void
   1088         // java.text.MessageFormat.setLocale(java.util.Locale)
   1089         MessageFormat format = new MessageFormat("date {0,date}");
   1090         format.setLocale(Locale.CHINA);
   1091         assertEquals("Wrong locale1", Locale.CHINA, format.getLocale());
   1092         format.applyPattern("{1,date}");
   1093         assertEquals("Wrong locale3", DateFormat.getDateInstance(
   1094                 DateFormat.DEFAULT, Locale.CHINA), format.getFormats()[0]);
   1095     }
   1096 
   1097     /**
   1098      * @tests java.text.MessageFormat#toPattern()
   1099      */
   1100     @TestTargetNew(
   1101         level = TestLevel.COMPLETE,
   1102         notes = "",
   1103         method = "toPattern",
   1104         args = {}
   1105     )
   1106     public void test_toPattern() {
   1107         // Test for method java.lang.String java.text.MessageFormat.toPattern()
   1108         String pattern = "[{0}]";
   1109         MessageFormat mf = new MessageFormat(pattern);
   1110         assertTrue("Wrong pattern", mf.toPattern().equals(pattern));
   1111 
   1112         // Regression for HARMONY-59
   1113         new MessageFormat("CHOICE {1,choice}").toPattern();
   1114     }
   1115 
   1116     /**
   1117      * Sets up the fixture, for example, open a network connection. This method
   1118      * is called before a test is executed.
   1119      */
   1120     protected void setUp() {
   1121         defaultLocale = Locale.getDefault();
   1122         Locale.setDefault(Locale.US);
   1123 
   1124         // test with repeating formats and max argument index < max offset
   1125         String pattern = "A {3, number, currency} B {2, time} C {0, number, percent} D {4}  E {1,choice,0#off|1#on} F {0, date}";
   1126         format1 = new MessageFormat(pattern);
   1127 
   1128         // test with max argument index > max offset
   1129         pattern = "A {3, number, currency} B {8, time} C {0, number, percent} D {6}  E {1,choice,0#off|1#on} F {0, date}";
   1130         format2 = new MessageFormat(pattern);
   1131 
   1132         // test with argument number being zero
   1133         pattern = "A B C D E F";
   1134         format3 = new MessageFormat(pattern);
   1135     }
   1136 
   1137     /**
   1138      * Tears down the fixture, for example, close a network connection. This
   1139      * method is called after a test is executed.
   1140      */
   1141     protected void tearDown() {
   1142         Locale.setDefault(defaultLocale);
   1143     }
   1144 
   1145     /**
   1146      * @tests java.text.MessageFormat(java.util.Locale)
   1147      */
   1148     @TestTargetNew(
   1149         level = TestLevel.PARTIAL_COMPLETE,
   1150         notes = "Verifies IllegalArgumentException.",
   1151         method = "MessageFormat",
   1152         args = {java.lang.String.class, java.util.Locale.class}
   1153     )
   1154     public void test_ConstructorLjava_util_Locale() {
   1155         // Regression for HARMONY-65
   1156         try {
   1157             new MessageFormat("{0,number,integer", Locale.US);
   1158             fail("Assert 0: Failed to detect unmatched brackets.");
   1159         } catch (IllegalArgumentException e) {
   1160             // expected
   1161         }
   1162     }
   1163 
   1164     /**
   1165      * @tests java.text.MessageFormat#parse(java.lang.String) Test of method
   1166      *        java.text.MessageFormat#parse(java.lang.String).
   1167      */
   1168     @TestTargetNew(
   1169             level = TestLevel.COMPLETE,
   1170             notes = "",
   1171             method = "parse",
   1172             args = {java.lang.String.class}
   1173     )
   1174     public void test_parseLjava_lang_String() throws ParseException {
   1175         String pattern = "A {3, number, currency} B {2, time} C {0, number, percent} D {4}  E {1,choice,0#off|1#on} F {0, date}";
   1176         MessageFormat mf = new MessageFormat(pattern);
   1177         String sToParse = "A $12,345.00 B 9:56:07 AM C 3,200% D 1/15/70 9:56 AM  E on F Jan 1, 1970";
   1178         Object[] result;
   1179         try {
   1180             result = mf.parse(sToParse);
   1181 
   1182             assertTrue("No result: " + result.length, result.length == 5);
   1183             assertTrue("Object 0 is not date", result[0] instanceof Date);
   1184             assertEquals("Object 1 is not stringr", result[1].toString(), "1.0");
   1185             assertTrue("Object 2 is not date", result[2] instanceof Date);
   1186             assertEquals("Object 3 is not number", result[3].toString(),
   1187                     "12345");
   1188             assertEquals("Object 4 is not string", result[4].toString(),
   1189                     "1/15/70 9:56 AM");
   1190 
   1191         } catch (java.text.ParseException pe) {
   1192             fail("ParseException is thrown for incorrect string " + sToParse);
   1193         }
   1194 
   1195         sToParse = "xxdate is Feb 28, 1999";
   1196         try {
   1197             result = format1.parse(sToParse);
   1198             fail("ParseException is thrown for incorrect string " + sToParse);
   1199         } catch (java.text.ParseException pe) {
   1200             // expected
   1201         }
   1202 
   1203         sToParse = "vm=Test, @3 4 6, 3   ";
   1204         mf = new MessageFormat("vm={0},{1},{2}");
   1205         try {
   1206             result = mf.parse(sToParse);
   1207             assertTrue("No result: " + result.length, result.length == 3);
   1208             assertEquals("Object 0 is not string", result[0].toString(), "Test");
   1209             assertEquals("Object 1 is not string", result[1].toString(),
   1210                     " @3 4 6");
   1211             assertEquals("Object 2 is not string", result[2].toString(),
   1212                     " 3   ");
   1213         } catch (java.text.ParseException pe) {
   1214             fail("ParseException is thrown for correct string " + sToParse);
   1215         }
   1216 
   1217         try {
   1218             result = mf.parse(null);
   1219             fail("ParseException is not thrown for null " + sToParse);
   1220         } catch (java.text.ParseException pe) {
   1221             // expected
   1222         }
   1223     }
   1224 
   1225     /**
   1226      * @tests java.text.MessageFormat#parseObject(java.lang.String,
   1227      *        java.text.ParsePosition) Test of method
   1228      *        java.text.MessageFormat#parseObject(java.lang.String,
   1229      *        java.text.ParsePosition). Case 1: Parsing of correct data string.
   1230      *        Case 2: Parsing of partial correct data string. Case 3: Try to use
   1231      *        argument ParsePosition as null.
   1232      */
   1233     @TestTargetNew(
   1234             level = TestLevel.COMPLETE,
   1235             notes = "",
   1236             method = "parseObject",
   1237             args = {java.lang.String.class, java.text.ParsePosition.class}
   1238     )
   1239     public void test_parseObjectLjava_lang_StringLjavajava_text_ParsePosition() {
   1240         MessageFormat mf = new MessageFormat("{0,number,#.##}, {0,number,#.#}");
   1241         try {
   1242             // case 1: Try to parse correct data string.
   1243             Object[] objs = { new Double(3.1415) };
   1244             String result = mf.format(objs);
   1245             // result now equals "3.14, 3.1"
   1246             Object[] res = null;
   1247             ParsePosition pp = new ParsePosition(0);
   1248             int parseIndex = pp.getIndex();
   1249             res = (Object[]) mf.parseObject(result, pp);
   1250             assertTrue("Parse operation return null", res != null);
   1251             assertTrue("parse operation return array with incorrect length",
   1252                     1 == res.length);
   1253             assertTrue("ParseIndex is incorrect", pp.getIndex() != parseIndex);
   1254             assertTrue("Result object is incorrect", new Double(3.1)
   1255                     .equals(res[0]));
   1256 
   1257             // case 2: Try to parse partially correct data string.
   1258             pp.setIndex(0);
   1259             char[] cur = result.toCharArray();
   1260             cur[cur.length / 2] = 'Z';
   1261             String partialCorrect = new String(cur);
   1262             res = (Object[]) mf.parseObject(partialCorrect, pp);
   1263             assertTrue("Parse operation return null", res == null);
   1264             assertTrue("ParseIndex is incorrect", pp.getIndex() == 0);
   1265             assertTrue("ParseErrorIndex is incorrect",
   1266                     pp.getErrorIndex() == cur.length / 2);
   1267 
   1268             // case 3: Try to use argument ParsePosition as null.
   1269             try {
   1270                 mf.parseObject(result, null);
   1271                 fail("Expected NullPointerException was not thrown");
   1272             } catch (NullPointerException e) {
   1273                 // expected
   1274             }
   1275         } catch (Exception e) {
   1276             fail("Unexpected exception " + e.toString());
   1277         }
   1278     }
   1279     @TestTargetNew(
   1280             level = TestLevel.PARTIAL,
   1281             notes = "Regression test. Doesn't verifies exception.",
   1282             method = "format",
   1283             args = {java.lang.Object.class}
   1284     )
   1285     public void test_format_Object() {
   1286         // Regression for HARMONY-1875
   1287         Locale.setDefault(Locale.CANADA);
   1288         TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
   1289         String pat = "text here {0,date,yyyyyyyyy} and here";
   1290         Calendar c = Calendar.getInstance();
   1291         String etalon = "text here 00000" + c.get(Calendar.YEAR) + " and here";
   1292         MessageFormat obj = new MessageFormat(pat);
   1293         assertEquals(etalon, obj.format(new Object[] { new Date() }));
   1294     }
   1295 
   1296     /**
   1297      * @tests java.text.MessageFormat#parse(java.lang.String)
   1298      */
   1299     @TestTargetNew(
   1300             level = TestLevel.PARTIAL_COMPLETE,
   1301             notes = "",
   1302             method = "parse",
   1303             args = {java.lang.String.class}
   1304     )
   1305     public void test_parse() throws ParseException {
   1306         // Regression for HARMONY-63
   1307         MessageFormat mf = new MessageFormat("{0,number,#,####}", Locale.US);
   1308         Object[] res = mf.parse("1,00,00");
   1309         assertEquals("Assert 0: incorrect size of parsed data ", 1, res.length);
   1310         assertEquals("Assert 1: parsed value incorrectly", new Long(10000), (Long)res[0]);
   1311     }
   1312 
   1313     @TestTargetNew(
   1314             level = TestLevel.PARTIAL_COMPLETE,
   1315             notes = "",
   1316             method = "format",
   1317             args = {java.lang.String.class, java.lang.Object[].class}
   1318     )
   1319     public void testHARMONY5323() {
   1320         Object []messageArgs = new Object[11];
   1321         for (int i = 0; i < messageArgs.length; i++)
   1322             messageArgs[i] = "dumb"+i;
   1323 
   1324         String res = MessageFormat.format("bgcolor=\"{10}\"", messageArgs);
   1325         assertEquals(res, "bgcolor=\"dumb10\"");
   1326     }
   1327 }
   1328