1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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 import static org.junit.jupiter.api.Assertions.assertThrowsExactly;
22
23 import java.text.DateFormat;
24 import java.text.FieldPosition;
25 import java.text.Format;
26 import java.text.MessageFormat;
27 import java.text.NumberFormat;
28 import java.text.ParsePosition;
29 import java.util.Arrays;
30 import java.util.Calendar;
31 import java.util.Collections;
32 import java.util.HashMap;
33 import java.util.HashSet;
34 import java.util.Locale;
35 import java.util.Map;
36
37 import org.apache.commons.lang3.AbstractLangTest;
38 import org.junit.jupiter.api.BeforeEach;
39 import org.junit.jupiter.api.Test;
40 import org.junit.jupiter.params.ParameterizedTest;
41 import org.junit.jupiter.params.provider.MethodSource;
42 import org.junit.jupiter.params.provider.ValueSource;
43 import org.junitpioneer.jupiter.cartesian.ArgumentSets;
44 import org.junitpioneer.jupiter.cartesian.CartesianTest;
45
46
47
48
49 @Deprecated
50 class ExtendedMessageFormatTest extends AbstractLangTest {
51
52
53
54
55 private static final class LowerCaseFormat extends Format {
56 private static final long serialVersionUID = 1L;
57
58 @Override
59 public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) {
60 return toAppendTo.append(((String) obj).toLowerCase(Locale.ROOT));
61 }
62 @Override
63 public Object parseObject(final String source, final ParsePosition pos) {
64 throw new UnsupportedOperationException();
65 }
66 }
67
68
69
70
71 private static final class LowerCaseFormatFactory implements FormatFactory {
72 private static final Format LOWER_INSTANCE = new LowerCaseFormat();
73
74 @Override
75 public Format getFormat(final String name, final String arguments, final Locale locale) {
76 return LOWER_INSTANCE;
77 }
78 }
79
80
81
82
83 private static final class OtherExtendedMessageFormat extends ExtendedMessageFormat {
84 private static final long serialVersionUID = 1L;
85
86 OtherExtendedMessageFormat(final String pattern, final Locale locale,
87 final Map<String, ? extends FormatFactory> registry) {
88 super(pattern, locale, registry);
89 }
90
91 }
92
93
94
95
96 private static final class OverrideShortDateFormatFactory implements FormatFactory {
97
98 @Override
99 public Format getFormat(final String name, final String arguments, final Locale locale) {
100 return !"short".equals(arguments) ? null
101 : locale == null ? DateFormat
102 .getDateInstance(DateFormat.DEFAULT) : DateFormat
103 .getDateInstance(DateFormat.DEFAULT, locale);
104 }
105 }
106
107
108
109
110 private static final class UpperCaseFormat extends Format {
111 private static final long serialVersionUID = 1L;
112
113 @Override
114 public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) {
115 return toAppendTo.append(((String) obj).toUpperCase(Locale.ROOT));
116 }
117
118 @Override
119 public Object parseObject(final String source, final ParsePosition pos) {
120 throw new UnsupportedOperationException();
121 }
122 }
123
124
125
126
127 private static final class UpperCaseFormatFactory implements FormatFactory {
128 private static final Format UPPER_INSTANCE = new UpperCaseFormat();
129
130 @Override
131 public Format getFormat(final String name, final String arguments, final Locale locale) {
132 return UPPER_INSTANCE;
133 }
134 }
135
136 static ArgumentSets testBuiltInChoiceFormatFactory() {
137
138 return ArgumentSets
139 .argumentsForFirstParameter(Integer.valueOf(1), Double.valueOf("2.2"), Double.valueOf("1234.5"))
140 .argumentsForNextParameter(DateFormat.getAvailableLocales());
141
142 }
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199 static ArgumentSets testBuiltInDateTimeFormatFactory() {
200
201 return ArgumentSets
202 .argumentsForFirstParameter(
203 "1: {0,date,short}",
204 "2: {0,date,medium}",
205 "3: {0,date,long}",
206 "4: {0,date,full}",
207 "5: {0,date,d MMM yy}",
208 "6: {0,time,short}",
209 "7: {0,time,medium}",
210 "8: {0,time,long}",
211 "9: {0,time,full}",
212 "10: {0,time,HH:mm}",
213 "11: {0,date}", "12: {0,time}")
214 .argumentsForNextParameter(DateFormat.getAvailableLocales());
215
216 }
217
218 static ArgumentSets testBuiltInNumberFormatFactory() {
219
220 return ArgumentSets
221 .argumentsForFirstParameter(
222 "1: {0,number}",
223 "2: {0,number,integer}",
224 "3: {0,number,currency}",
225 "4: {0,number,percent}",
226 "5: {0,number,00000.000}")
227 .argumentsForNextParameter(DateFormat.getAvailableLocales());
228
229 }
230
231 static ArgumentSets testOverriddenBuiltinFormatFactory() {
232
233 return ArgumentSets
234 .argumentsForFirstParameter(
235 "1: {0,date}",
236 "2: {0,date,medium}",
237 "3: {0,date,long}",
238 "4: {0,date,full}",
239 "5: {0,date,d MMM yy}")
240 .argumentsForNextParameter(DateFormat.getAvailableLocales());
241
242 }
243
244 private final Map<String, FormatFactory> registry = new HashMap<>();
245
246
247
248
249
250
251
252
253
254 private void checkBuiltInFormat(final String pattern, final Map<String, ?> registryUnused, final Object[] args, final Locale locale) {
255 final StringBuilder buffer = new StringBuilder();
256 buffer.append("Pattern=[");
257 buffer.append(pattern);
258 buffer.append("], locale=[");
259 buffer.append(locale);
260 buffer.append("]");
261 final MessageFormat mf = createMessageFormat(pattern, locale);
262 final ExtendedMessageFormat emf;
263 if (locale == null) {
264 emf = new ExtendedMessageFormat(pattern);
265 } else {
266 emf = new ExtendedMessageFormat(pattern, locale);
267 }
268 assertEquals(mf.format(args), emf.format(args), "format " + buffer);
269 assertEquals(mf.toPattern(), emf.toPattern(), "toPattern " + buffer);
270 }
271
272
273
274
275
276
277
278 private MessageFormat createMessageFormat(final String pattern, final Locale locale) {
279 final MessageFormat result = new MessageFormat(pattern);
280 if (locale != null) {
281 result.setLocale(locale);
282 result.applyPattern(pattern);
283 }
284 return result;
285 }
286
287 @BeforeEach
288 public void setUp() {
289 registry.put("lower", new LowerCaseFormatFactory());
290 registry.put("upper", new UpperCaseFormatFactory());
291 }
292
293 @Test
294 void testArgumentIndexTrailingWhitespaceAtEnd() {
295 assertThrowsExactly(IllegalArgumentException.class, () -> new ExtendedMessageFormat("{0 ", new HashMap<>()));
296 }
297
298
299
300
301 @CartesianTest
302 @CartesianTest.MethodFactory("testBuiltInChoiceFormatFactory")
303 void testBuiltInChoiceFormat(final Object value, final Locale locale) {
304 String choicePattern;
305 choicePattern = "{0,choice,1#One|2#Two|3#Many {0,number}}";
306 checkBuiltInFormat(value + ": " + choicePattern, null, new Object[] { value }, (Locale) null);
307 checkBuiltInFormat(value + ": " + choicePattern, null, new Object[] { value }, locale);
308
309 choicePattern = "{0,choice,1#''One''|2#\"Two\"|3#''{Many}'' {0,number}}";
310 checkBuiltInFormat(value + ": " + choicePattern, null, new Object[] { value }, (Locale) null);
311 checkBuiltInFormat(value + ": " + choicePattern, null, new Object[] { value }, locale);
312 }
313
314
315
316
317 @CartesianTest
318 @CartesianTest.MethodFactory("testBuiltInDateTimeFormatFactory")
319 void testBuiltInDateTimeFormat(final String pattern, final Locale locale) {
320 final Calendar cal = Calendar.getInstance();
321 cal.set(2007, Calendar.JANUARY, 23, 18, 33, 5);
322 final Object[] args = { cal.getTime() };
323 checkBuiltInFormat(pattern, null, args, (Locale) null);
324 checkBuiltInFormat(pattern, null, args, locale);
325 }
326
327
328
329
330 @CartesianTest
331 @CartesianTest.MethodFactory("testBuiltInNumberFormatFactory")
332 void testBuiltInNumberFormat(final String pattern, final Locale locale) {
333 final Object[] args = { Double.valueOf("6543.21") };
334 checkBuiltInFormat(pattern, null, args, (Locale) null);
335 checkBuiltInFormat(pattern, null, args, locale);
336 }
337
338
339
340
341 @Test
342 void testEmbeddedPatternInChoice() {
343 final String pattern = "Hi {0,lower}, got {1,choice,0#none|1#one|1<{1,number}}, {2,upper}!";
344 final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
345 assertEquals(emf.format(new Object[] {"there", 3, "great"}), "Hi there, got 3, GREAT!");
346 }
347
348
349
350
351 @Test
352 void testEqualsHashcode() {
353 final Map<String, ? extends FormatFactory> fmtRegistry = Collections.singletonMap("testfmt", new LowerCaseFormatFactory());
354 final Map<String, ? extends FormatFactory> otherRegistry = Collections.singletonMap("testfmt", new UpperCaseFormatFactory());
355
356 final String pattern = "Pattern: {0,testfmt}";
357 final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, Locale.US, fmtRegistry);
358
359 ExtendedMessageFormat other;
360
361
362 assertEquals(emf, emf, "same, equals()");
363 assertEquals(emf.hashCode(), emf.hashCode(), "same, hashCode()");
364
365
366 other = new ExtendedMessageFormat(pattern, Locale.US, fmtRegistry);
367 assertEquals(emf, other, "equal, equals()");
368 assertEquals(emf.hashCode(), other.hashCode(), "equal, hashCode()");
369
370
371 other = new OtherExtendedMessageFormat(pattern, Locale.US, fmtRegistry);
372 assertNotEquals(emf, other, "class, equals()");
373 assertEquals(emf.hashCode(), other.hashCode(), "class, hashCode()");
374
375
376 other = new ExtendedMessageFormat("X" + pattern, Locale.US, fmtRegistry);
377 assertNotEquals(emf, other, "pattern, equals()");
378 assertNotEquals(emf.hashCode(), other.hashCode(), "pattern, hashCode()");
379
380
381 other = new ExtendedMessageFormat(pattern, Locale.US, otherRegistry);
382 assertNotEquals(emf, other, "registry, equals()");
383 assertNotEquals(emf.hashCode(), other.hashCode(), "registry, hashCode()");
384
385
386 other = new ExtendedMessageFormat(pattern, Locale.FRANCE, fmtRegistry);
387 assertNotEquals(emf, other, "locale, equals()");
388 assertEquals(emf.hashCode(), other.hashCode(), "locale, hashCode()");
389 }
390
391
392
393
394 @Test
395 void testEscapedBraces_LANG_948() {
396
397 final String pattern = "Message without placeholders '{}'";
398 final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
399 assertEquals("Message without placeholders {}", emf.format(new Object[] {"DUMMY"}));
400
401
402 final String pattern2 = "Message with placeholder ''{0}''";
403 final ExtendedMessageFormat emf2 = new ExtendedMessageFormat(pattern2, registry);
404 assertEquals("Message with placeholder 'DUMMY'", emf2.format(new Object[] {"DUMMY"}));
405 }
406
407
408
409
410 @Test
411 void testEscapedQuote_LANG_477() {
412 final String pattern = "it''s a {0,lower} 'test'!";
413 final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
414 assertEquals("it's a dummy test!", emf.format(new Object[] {"DUMMY"}));
415 }
416
417
418
419
420 @Test
421 void testExtendedAndBuiltInFormatsWithAvailableLocales() {
422 final String extendedPattern = "Name: {0,upper} ";
423 final String builtinsPattern = "DOB: {1,date,short} Salary: {2,number,currency}";
424 final String pattern = extendedPattern + builtinsPattern;
425
426 final Calendar cal = Calendar.getInstance();
427 cal.set(2007, Calendar.JANUARY, 23, 18, 33, 5);
428 final Object[] args = {"John Doe", cal.getTime(), Double.valueOf("12345.67")};
429
430 final HashSet<Locale> testLocales = new HashSet<>(Arrays.asList(DateFormat.getAvailableLocales()));
431 testLocales.retainAll(Arrays.asList(NumberFormat.getAvailableLocales()));
432
433 for (final Locale locale : testLocales) {
434 final MessageFormat builtins = createMessageFormat(builtinsPattern, locale);
435 final String expectedPattern = extendedPattern + builtins.toPattern();
436 final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, locale, registry);
437 assertEquals(expectedPattern, emf.toPattern(), "pattern comparison for locale " + locale);
438
439 final DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
440 final NumberFormat nf = NumberFormat.getCurrencyInstance(locale);
441 final StringBuilder expected = new StringBuilder();
442 expected.append("Name: ");
443 expected.append(args[0].toString().toUpperCase(locale));
444 expected.append(" DOB: ");
445 expected.append(df.format(args[1]));
446 expected.append(" Salary: ");
447 expected.append(nf.format(args[2]));
448 assertEquals(expected.toString(), emf.format(args), String.valueOf(locale));
449 }
450 }
451
452
453
454
455 @Test
456 void testExtendedAndBuiltInFormatsWithDefaultLocale() {
457 final String extendedPattern = "Name: {0,upper} ";
458 final String builtinsPattern = "DOB: {1,date,short} Salary: {2,number,currency}";
459 final String pattern = extendedPattern + builtinsPattern;
460
461 final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
462 final MessageFormat builtins = createMessageFormat(builtinsPattern, null);
463 final String expectedPattern = extendedPattern + builtins.toPattern();
464 assertEquals(expectedPattern, emf.toPattern(), "pattern comparison for default locale");
465
466 final Calendar cal = Calendar.getInstance();
467 cal.set(2007, Calendar.JANUARY, 23, 18, 33, 5);
468 final Object[] args = {"John Doe", cal.getTime(), Double.valueOf("12345.67")};
469 final DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
470 final NumberFormat nf = NumberFormat.getCurrencyInstance();
471 final StringBuilder expected = new StringBuilder();
472 expected.append("Name: ");
473 expected.append(args[0].toString().toUpperCase());
474 expected.append(" DOB: ");
475 expected.append(df.format(args[1]));
476 expected.append(" Salary: ");
477 expected.append(nf.format(args[2]));
478 assertEquals(expected.toString(), emf.format(args));
479 }
480
481
482
483
484 @Test
485 void testExtendedFormats() {
486 final String pattern = "Lower: {0,lower} Upper: {1,upper}";
487 final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
488 assertEquals(pattern, emf.toPattern(), "TOPATTERN");
489 assertEquals(emf.format(new Object[] {"foo", "bar"}), "Lower: foo Upper: BAR");
490 assertEquals(emf.format(new Object[] {"Foo", "Bar"}), "Lower: foo Upper: BAR");
491 assertEquals(emf.format(new Object[] {"FOO", "BAR"}), "Lower: foo Upper: BAR");
492 assertEquals(emf.format(new Object[] {"FOO", "bar"}), "Lower: foo Upper: BAR");
493 assertEquals(emf.format(new Object[] {"foo", "BAR"}), "Lower: foo Upper: BAR");
494 }
495
496 @CartesianTest
497 @CartesianTest.MethodFactory("testOverriddenBuiltinFormatFactory")
498 void testOverriddenBuiltinFormat(final String pattern, final Locale locale) {
499 final Calendar cal = Calendar.getInstance();
500 cal.set(2007, Calendar.JANUARY, 23);
501 final Object[] args = { cal.getTime() };
502
503 checkBuiltInFormat(pattern, null, args, (Locale) null);
504 checkBuiltInFormat(pattern, null, args, locale);
505 }
506
507 @ParameterizedTest
508 @MethodSource("java.text.DateFormat#getAvailableLocales")
509 void testOverriddenBuiltinFormat2(final Locale locale) {
510 final Calendar cal = Calendar.getInstance();
511 cal.set(2007, Calendar.JANUARY, 23);
512 final Object[] args = { cal.getTime() };
513 final Map<String, ? extends FormatFactory> dateRegistry = Collections.singletonMap("date", new OverrideShortDateFormatFactory());
514
515 final MessageFormat dateDefault = createMessageFormat("{0,date}", locale);
516 final String pattern = "{0,date,short}";
517 final ExtendedMessageFormat dateShort = new ExtendedMessageFormat(pattern, locale, dateRegistry);
518 assertEquals(dateDefault.format(args), dateShort.format(args), "overridden date,short format");
519 assertEquals(pattern, dateShort.toPattern(), "overridden date,short pattern");
520 }
521
522
523
524
525
526
527 @Test
528 void testQuotedLiteralAtEndOfFormatElement() {
529 assertEquals("ABC", new ExtendedMessageFormat("{0,upper,'x'}", registry).format(new Object[] {"abc"}));
530 assertEquals("ABC", new ExtendedMessageFormat("{0,upper,'}'}", registry).format(new Object[] {"abc"}));
531
532 assertEquals("5%", new ExtendedMessageFormat("{0,number,0'%'}", registry).format(new Object[] {Integer.valueOf(5)}));
533 }
534
535 @Test
536 void testTruncatedFormatElementWithRegistry() {
537
538 assertThrowsExactly(IllegalArgumentException.class, () -> new MessageFormat("{"));
539 assertThrowsExactly(IllegalArgumentException.class, () -> new MessageFormat("{0,"));
540 assertThrowsExactly(IllegalArgumentException.class, () -> new MessageFormat("{0}extra{"));
541
542
543
544
545 assertThrowsExactly(IllegalArgumentException.class, () -> new ExtendedMessageFormat("{", new HashMap<>()));
546 assertThrowsExactly(IllegalArgumentException.class, () -> new ExtendedMessageFormat("{0,", new HashMap<>()));
547 assertThrowsExactly(IllegalArgumentException.class, () -> new ExtendedMessageFormat("{0}extra{", new HashMap<>()));
548 }
549
550
551
552
553
554 @Test
555 void testUnmatchedQuote() {
556 final ExtendedMessageFormat emf = new ExtendedMessageFormat("it's a {0,lower} test!", registry);
557 assertEquals("its a {0,lower} test!", emf.format(new Object[] {"DUMMY"}));
558 assertEquals(emf.format(new Object[] {"DUMMY"}),
559 new ExtendedMessageFormat(emf.toPattern(), registry).format(new Object[] {"DUMMY"}));
560
561 final ExtendedMessageFormat emf2 = new ExtendedMessageFormat("Don{0,upper}t panic: '", registry);
562 assertEquals("DonDUMMYt panic: ", emf2.format(new Object[] {"Dummy"}));
563 assertEquals("Don{0,upper}t panic: ", emf2.toPattern());
564 assertEquals(emf2.format(new Object[] {"Dummy"}),
565 new ExtendedMessageFormat(emf2.toPattern(), registry).format(new Object[] {"Dummy"}));
566 }
567
568
569
570
571
572
573 @ParameterizedTest
574 @ValueSource(strings = {"{0,number,0'foo}", "{0,date,yyyy'foo}", "{0,choice,0#'foo}", "{0,upper,'foo}"})
575 void testUnmatchedQuoteInFormatDescription(final String pattern) {
576 assertThrowsExactly(IllegalArgumentException.class, () -> new ExtendedMessageFormat(pattern, registry));
577 }
578
579
580
581
582
583
584 @ParameterizedTest
585 @ValueSource(strings = {"Don't panic {0}", "'", "'''", "prefix '", "'{0}", "{0} suffix '{1}"})
586 void testUnmatchedQuoteWithEmptyRegistry(final String pattern) {
587 final Object[] args = {"Dummy", "Other"};
588 final MessageFormat expected = new MessageFormat(pattern, Locale.ROOT);
589 final ExtendedMessageFormat actual = new ExtendedMessageFormat(pattern, Locale.ROOT, Collections.emptyMap());
590 assertEquals(expected.format(args), actual.format(args));
591 assertEquals(expected.toPattern(), actual.toPattern());
592 final ExtendedMessageFormat reconstructed = new ExtendedMessageFormat(actual.toPattern(), Locale.ROOT, Collections.emptyMap());
593 assertEquals(actual.format(args), reconstructed.format(args));
594 }
595
596 }