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