View Javadoc
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  package org.apache.commons.lang3.text;
18  
19  import org.junit.Test;
20  import org.junit.Before;
21  import static org.junit.Assert.*;
22  import static org.apache.commons.lang3.JavaVersion.JAVA_1_4;
23  
24  import java.text.ChoiceFormat;
25  import java.text.DateFormat;
26  import java.text.FieldPosition;
27  import java.text.Format;
28  import java.text.MessageFormat;
29  import java.text.NumberFormat;
30  import java.text.ParsePosition;
31  import java.util.Arrays;
32  import java.util.Calendar;
33  import java.util.Collections;
34  import java.util.HashMap;
35  import java.util.HashSet;
36  import java.util.Locale;
37  import java.util.Map;
38  
39  import org.apache.commons.lang3.SystemUtils;
40  
41  /**
42   * Test case for {@link ExtendedMessageFormat}.
43   *
44   * @since 2.4
45   * @version $Id: ExtendedMessageFormatTest.java 1582699 2014-03-28 11:15:32Z sebb $
46   */
47  public class ExtendedMessageFormatTest {
48  
49      private final Map<String, FormatFactory> registry = new HashMap<String, FormatFactory>();
50  
51      @Before
52      public void setUp() throws Exception {
53          registry.put("lower", new LowerCaseFormatFactory());
54          registry.put("upper", new UpperCaseFormatFactory());
55      }
56  
57      /**
58       * Test extended formats.
59       */
60      @Test
61      public void testExtendedFormats() {
62          final String pattern = "Lower: {0,lower} Upper: {1,upper}";
63          final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
64          assertPatternsEqual("TOPATTERN", pattern, emf.toPattern());
65          assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"foo", "bar"}));
66          assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"Foo", "Bar"}));
67          assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"FOO", "BAR"}));
68          assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"FOO", "bar"}));
69          assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"foo", "BAR"}));
70      }
71  
72      /**
73       * Test Bug LANG-477 - out of memory error with escaped quote
74       */
75      @Test
76      public void testEscapedQuote_LANG_477() {
77          final String pattern = "it''s a {0,lower} 'test'!";
78          final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
79          assertEquals("it's a dummy test!", emf.format(new Object[] {"DUMMY"}));
80      }
81  
82      /**
83       * Test Bug LANG-917 - IndexOutOfBoundsException and/or infinite loop when using a choice pattern
84       */
85      @Test
86      public void testEmbeddedPatternInChoice() {
87          final String pattern = "Hi {0,lower}, got {1,choice,0#none|1#one|1<{1,number}}, {2,upper}!";
88          final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
89          assertEquals(emf.format(new Object[] {"there", 3, "great"}), "Hi there, got 3, GREAT!");
90      }
91  
92      /**
93       * Test extended and built in formats.
94       */
95      @Test
96      public void testExtendedAndBuiltInFormats() {
97          final Calendar cal = Calendar.getInstance();
98          cal.set(2007, Calendar.JANUARY, 23, 18, 33, 05);
99          final Object[] args = new Object[] {"John Doe", cal.getTime(), Double.valueOf("12345.67")};
100         final String builtinsPattern = "DOB: {1,date,short} Salary: {2,number,currency}";
101         final String extendedPattern = "Name: {0,upper} ";
102         final String pattern = extendedPattern + builtinsPattern;
103 
104         final HashSet<Locale> testLocales = new HashSet<Locale>();
105         testLocales.addAll(Arrays.asList(DateFormat.getAvailableLocales()));
106         testLocales.retainAll(Arrays.asList(NumberFormat.getAvailableLocales()));
107         testLocales.add(null);
108 
109         for (final Locale locale : testLocales) {
110             final MessageFormat builtins = createMessageFormat(builtinsPattern, locale);
111             final String expectedPattern = extendedPattern + builtins.toPattern();
112             DateFormat df = null;
113             NumberFormat nf = null;
114             ExtendedMessageFormat emf = null;
115             if (locale == null) {
116                 df = DateFormat.getDateInstance(DateFormat.SHORT);
117                 nf = NumberFormat.getCurrencyInstance();
118                 emf = new ExtendedMessageFormat(pattern, registry);
119             } else {
120                 df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
121                 nf = NumberFormat.getCurrencyInstance(locale);
122                 emf = new ExtendedMessageFormat(pattern, locale, registry);
123             }
124             final StringBuilder expected = new StringBuilder();
125             expected.append("Name: ");
126             expected.append(args[0].toString().toUpperCase());
127             expected.append(" DOB: ");
128             expected.append(df.format(args[1]));
129             expected.append(" Salary: ");
130             expected.append(nf.format(args[2]));
131             assertPatternsEqual("pattern comparison for locale " + locale, expectedPattern, emf.toPattern());
132             assertEquals(String.valueOf(locale), expected.toString(), emf.format(args));
133         }
134     }
135 
136 //    /**
137 //     * Test extended formats with choice format.
138 //     *
139 //     * NOTE: FAILING - currently sub-formats not supported
140 //     */
141 //    public void testExtendedWithChoiceFormat() {
142 //        String pattern = "Choice: {0,choice,1.0#{1,lower}|2.0#{1,upper}}";
143 //        ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
144 //        assertPatterns(null, pattern, emf.toPattern());
145 //        try {
146 //            assertEquals("one", emf.format(new Object[] {Integer.valueOf(1), "ONE"}));
147 //            assertEquals("TWO", emf.format(new Object[] {Integer.valueOf(2), "two"}));
148 //        } catch (IllegalArgumentException e) {
149 //            // currently sub-formats not supported
150 //        }
151 //    }
152 
153 //    /**
154 //     * Test mixed extended and built-in formats with choice format.
155 //     *
156 //     * NOTE: FAILING - currently sub-formats not supported
157 //     */
158 //    public void testExtendedAndBuiltInWithChoiceFormat() {
159 //        String pattern = "Choice: {0,choice,1.0#{0} {1,lower} {2,number}|2.0#{0} {1,upper} {2,number,currency}}";
160 //        Object[] lowArgs  = new Object[] {Integer.valueOf(1), "Low",  Double.valueOf("1234.56")};
161 //        Object[] highArgs = new Object[] {Integer.valueOf(2), "High", Double.valueOf("9876.54")};
162 //        Locale[] availableLocales = ChoiceFormat.getAvailableLocales();
163 //        Locale[] testLocales = new Locale[availableLocales.length + 1];
164 //        testLocales[0] = null;
165 //        System.arraycopy(availableLocales, 0, testLocales, 1, availableLocales.length);
166 //        for (int i = 0; i < testLocales.length; i++) {
167 //            NumberFormat nf = null;
168 //            NumberFormat cf = null;
169 //            ExtendedMessageFormat emf = null;
170 //            if (testLocales[i] == null) {
171 //                nf = NumberFormat.getNumberInstance();
172 //                cf = NumberFormat.getCurrencyInstance();
173 //                emf = new ExtendedMessageFormat(pattern, registry);
174 //            } else {
175 //                nf = NumberFormat.getNumberInstance(testLocales[i]);
176 //                cf = NumberFormat.getCurrencyInstance(testLocales[i]);
177 //                emf = new ExtendedMessageFormat(pattern, testLocales[i], registry);
178 //            }
179 //            assertPatterns(null, pattern, emf.toPattern());
180 //            try {
181 //                String lowExpected = lowArgs[0] + " low "    + nf.format(lowArgs[2]);
182 //                String highExpected = highArgs[0] + " HIGH "  + cf.format(highArgs[2]);
183 //                assertEquals(lowExpected,  emf.format(lowArgs));
184 //                assertEquals(highExpected, emf.format(highArgs));
185 //            } catch (IllegalArgumentException e) {
186 //                // currently sub-formats not supported
187 //            }
188 //        }
189 //    }
190 
191     /**
192      * Test the built in choice format.
193      */
194     @Test
195     public void testBuiltInChoiceFormat() {
196         final Object[] values = new Number[] {Integer.valueOf(1), Double.valueOf("2.2"), Double.valueOf("1234.5")};
197         String choicePattern = null;
198         final Locale[] availableLocales = ChoiceFormat.getAvailableLocales();
199 
200         choicePattern = "{0,choice,1#One|2#Two|3#Many {0,number}}";
201         for (final Object value : values) {
202             checkBuiltInFormat(value + ": " + choicePattern, new Object[] {value}, availableLocales);
203         }
204 
205         choicePattern = "{0,choice,1#''One''|2#\"Two\"|3#''{Many}'' {0,number}}";
206         for (final Object value : values) {
207             checkBuiltInFormat(value + ": " + choicePattern, new Object[] {value}, availableLocales);
208         }
209     }
210 
211     /**
212      * Test the built in date/time formats
213      */
214     @Test
215     public void testBuiltInDateTimeFormat() {
216         final Calendar cal = Calendar.getInstance();
217         cal.set(2007, Calendar.JANUARY, 23, 18, 33, 05);
218         final Object[] args = new Object[] {cal.getTime()};
219         final Locale[] availableLocales = DateFormat.getAvailableLocales();
220 
221         checkBuiltInFormat("1: {0,date,short}",    args, availableLocales);
222         checkBuiltInFormat("2: {0,date,medium}",   args, availableLocales);
223         checkBuiltInFormat("3: {0,date,long}",     args, availableLocales);
224         checkBuiltInFormat("4: {0,date,full}",     args, availableLocales);
225         checkBuiltInFormat("5: {0,date,d MMM yy}", args, availableLocales);
226         checkBuiltInFormat("6: {0,time,short}",    args, availableLocales);
227         checkBuiltInFormat("7: {0,time,medium}",   args, availableLocales);
228         checkBuiltInFormat("8: {0,time,long}",     args, availableLocales);
229         checkBuiltInFormat("9: {0,time,full}",     args, availableLocales);
230         checkBuiltInFormat("10: {0,time,HH:mm}",   args, availableLocales);
231         checkBuiltInFormat("11: {0,date}",         args, availableLocales);
232         checkBuiltInFormat("12: {0,time}",         args, availableLocales);
233     }
234 
235     @Test
236     public void testOverriddenBuiltinFormat() {
237         final Calendar cal = Calendar.getInstance();
238         cal.set(2007, Calendar.JANUARY, 23);
239         final Object[] args = new Object[] {cal.getTime()};
240         final Locale[] availableLocales = DateFormat.getAvailableLocales();
241         final Map<String, ? extends FormatFactory> dateRegistry = Collections.singletonMap("date", new OverrideShortDateFormatFactory());
242 
243         //check the non-overridden builtins:
244         checkBuiltInFormat("1: {0,date}", dateRegistry,          args, availableLocales);
245         checkBuiltInFormat("2: {0,date,medium}", dateRegistry,   args, availableLocales);
246         checkBuiltInFormat("3: {0,date,long}", dateRegistry,     args, availableLocales);
247         checkBuiltInFormat("4: {0,date,full}", dateRegistry,     args, availableLocales);
248         checkBuiltInFormat("5: {0,date,d MMM yy}", dateRegistry, args, availableLocales);
249 
250         //check the overridden format:
251         for (int i = -1; i < availableLocales.length; i++) {
252             final Locale locale = i < 0 ? null : availableLocales[i];
253             final MessageFormat dateDefault = createMessageFormat("{0,date}", locale);
254             final String pattern = "{0,date,short}";
255             final ExtendedMessageFormat dateShort = new ExtendedMessageFormat(pattern, locale, dateRegistry);
256             assertEquals("overridden date,short format", dateDefault.format(args), dateShort.format(args));
257             assertEquals("overridden date,short pattern", pattern, dateShort.toPattern());
258         }
259     }
260 
261     /**
262      * Test the built in number formats.
263      */
264     @Test
265     public void testBuiltInNumberFormat() {
266         final Object[] args = new Object[] {Double.valueOf("6543.21")};
267         final Locale[] availableLocales = NumberFormat.getAvailableLocales();
268         checkBuiltInFormat("1: {0,number}",            args, availableLocales);
269         checkBuiltInFormat("2: {0,number,integer}",    args, availableLocales);
270         checkBuiltInFormat("3: {0,number,currency}",   args, availableLocales);
271         checkBuiltInFormat("4: {0,number,percent}",    args, availableLocales);
272         checkBuiltInFormat("5: {0,number,00000.000}",  args, availableLocales);
273     }
274 
275     /**
276      * Test equals() and hashcode.
277      */
278     @Test
279     public void testEqualsHashcode() {
280         final Map<String, ? extends FormatFactory> fmtRegistry = Collections.singletonMap("testfmt", new LowerCaseFormatFactory());
281         final Map<String, ? extends FormatFactory> otherRegitry = Collections.singletonMap("testfmt", new UpperCaseFormatFactory());
282 
283         final String pattern = "Pattern: {0,testfmt}";
284         final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, Locale.US, fmtRegistry);
285 
286         ExtendedMessageFormat other = null;
287 
288         // Same object
289         assertTrue("same, equals()",   emf.equals(emf));
290         assertTrue("same, hashcode()", emf.hashCode() == emf.hashCode());
291 
292         // Equal Object
293         other = new ExtendedMessageFormat(pattern, Locale.US, fmtRegistry);
294         assertTrue("equal, equals()",   emf.equals(other));
295         assertTrue("equal, hashcode()", emf.hashCode() == other.hashCode());
296 
297         // Different Class
298         other = new OtherExtendedMessageFormat(pattern, Locale.US, fmtRegistry);
299         assertFalse("class, equals()",  emf.equals(other));
300         assertTrue("class, hashcode()", emf.hashCode() == other.hashCode()); // same hashcode
301         
302         // Different pattern
303         other = new ExtendedMessageFormat("X" + pattern, Locale.US, fmtRegistry);
304         assertFalse("pattern, equals()",   emf.equals(other));
305         assertFalse("pattern, hashcode()", emf.hashCode() == other.hashCode());
306 
307         // Different registry
308         other = new ExtendedMessageFormat(pattern, Locale.US, otherRegitry);
309         assertFalse("registry, equals()",   emf.equals(other));
310         assertFalse("registry, hashcode()", emf.hashCode() == other.hashCode());
311 
312         // Different Locale
313         other = new ExtendedMessageFormat(pattern, Locale.FRANCE, fmtRegistry);
314         assertFalse("locale, equals()",  emf.equals(other));
315         assertTrue("locale, hashcode()", emf.hashCode() == other.hashCode()); // same hashcode
316     }
317 
318     /**
319      * Test a built in format for the specified Locales, plus <code>null</code> Locale.
320      * @param pattern MessageFormat pattern
321      * @param args MessageFormat arguments
322      * @param locales to test
323      */
324     private void checkBuiltInFormat(final String pattern, final Object[] args, final Locale[] locales) {
325         checkBuiltInFormat(pattern, null, args, locales);
326     }
327 
328     /**
329      * Test a built in format for the specified Locales, plus <code>null</code> Locale.
330      * @param pattern MessageFormat pattern
331      * @param fmtRegistry FormatFactory registry to use
332      * @param args MessageFormat arguments
333      * @param locales to test
334      */
335     private void checkBuiltInFormat(final String pattern, final Map<String, ?> fmtRegistry, final Object[] args, final Locale[] locales) {
336         checkBuiltInFormat(pattern, fmtRegistry, args, (Locale) null);
337         for (final Locale locale : locales) {
338             checkBuiltInFormat(pattern, fmtRegistry, args, locale);
339         }
340     }
341 
342     /**
343      * Create an ExtendedMessageFormat for the specified pattern and locale and check the
344      * formated output matches the expected result for the parameters.
345      * @param pattern string
346      * @param registryUnused map (currently unused)
347      * @param args Object[]
348      * @param locale Locale
349      */
350     private void checkBuiltInFormat(final String pattern, final Map<String, ?> registryUnused, final Object[] args, final Locale locale) {
351         final StringBuilder buffer = new StringBuilder();
352         buffer.append("Pattern=[");
353         buffer.append(pattern);
354         buffer.append("], locale=[");
355         buffer.append(locale);
356         buffer.append("]");
357         final MessageFormat mf = createMessageFormat(pattern, locale);
358         // System.out.println(buffer + ", result=[" + mf.format(args) +"]");
359         ExtendedMessageFormat emf = null;
360         if (locale == null) {
361             emf = new ExtendedMessageFormat(pattern);
362         } else {
363             emf = new ExtendedMessageFormat(pattern, locale);
364         }
365         assertEquals("format "    + buffer.toString(), mf.format(args), emf.format(args));
366         assertPatternsEqual("toPattern " + buffer.toString(), mf.toPattern(),  emf.toPattern());
367     }
368 
369     //can't trust what MessageFormat does with toPattern() pre 1.4:
370     private void assertPatternsEqual(final String message, final String expected, final String actual) {
371         if (SystemUtils.isJavaVersionAtLeast(JAVA_1_4)) {
372             assertEquals(message, expected, actual);
373         }
374     }
375 
376     /**
377      * Replace MessageFormat(String, Locale) constructor (not available until JDK 1.4).
378      * @param pattern string
379      * @param locale Locale
380      * @return MessageFormat
381      */
382     private MessageFormat createMessageFormat(final String pattern, final Locale locale) {
383         final MessageFormat result = new MessageFormat(pattern);
384         if (locale != null) {
385             result.setLocale(locale);
386             result.applyPattern(pattern);
387         }
388         return result;
389     }
390 
391     // ------------------------ Test Formats ------------------------
392 
393     /**
394      * {@link Format} implementation which converts to lower case.
395      */
396     private static class LowerCaseFormat extends Format {
397         private static final long serialVersionUID = 1L;
398 
399         @Override
400         public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) {
401             return toAppendTo.append(((String)obj).toLowerCase());
402         }
403         @Override
404         public Object parseObject(final String source, final ParsePosition pos) {throw new UnsupportedOperationException();}
405     }
406 
407     /**
408      * {@link Format} implementation which converts to upper case.
409      */
410     private static class UpperCaseFormat extends Format {
411         private static final long serialVersionUID = 1L;
412 
413         @Override
414         public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) {
415             return toAppendTo.append(((String)obj).toUpperCase());
416         }
417         @Override
418         public Object parseObject(final String source, final ParsePosition pos) {throw new UnsupportedOperationException();}
419     }
420 
421 
422     // ------------------------ Test Format Factories ---------------
423     /**
424      * {@link FormatFactory} implementation for lower case format.
425      */
426     private static class LowerCaseFormatFactory implements FormatFactory {
427         private static final Format LOWER_INSTANCE = new LowerCaseFormat();
428         @Override
429         public Format getFormat(final String name, final String arguments, final Locale locale) {
430             return LOWER_INSTANCE;
431         }
432     }
433     /**
434      * {@link FormatFactory} implementation for upper case format.
435      */
436     private static class UpperCaseFormatFactory implements FormatFactory {
437         private static final Format UPPER_INSTANCE = new UpperCaseFormat();
438         @Override
439         public Format getFormat(final String name, final String arguments, final Locale locale) {
440             return UPPER_INSTANCE;
441         }
442     }
443     /**
444      * {@link FormatFactory} implementation to override date format "short" to "default".
445      */
446     private static class OverrideShortDateFormatFactory implements FormatFactory {
447         @Override
448         public Format getFormat(final String name, final String arguments, final Locale locale) {
449             return !"short".equals(arguments) ? null
450                     : locale == null ? DateFormat
451                             .getDateInstance(DateFormat.DEFAULT) : DateFormat
452                             .getDateInstance(DateFormat.DEFAULT, locale);
453         }
454     }
455 
456     /**
457      * Alternative ExtendedMessageFormat impl.
458      */
459     private static class OtherExtendedMessageFormat extends ExtendedMessageFormat {
460         private static final long serialVersionUID = 1L;
461 
462         public OtherExtendedMessageFormat(final String pattern, final Locale locale,
463                 final Map<String, ? extends FormatFactory> registry) {
464             super(pattern, locale, registry);
465         }
466         
467     }
468 
469 }