1 /*
  2  * Copyright (c) 2000, 2023, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  */
 23 
 24 /**
 25  * @test
 26  * @bug 4018937
 27  * @build FormatIteratorTest PParser
 28  * @run junit/othervm FormatIteratorTest
 29  * @summary Tests the formatToCharacterIterator method of SimpleDateFormat,
 30  *          MessageFormat and DecimalFormat.
 31  */
 32 
 33 import java.io.*;
 34 import java.lang.reflect.*;
 35 import java.text.*;
 36 import java.util.*;
 37 import java.util.concurrent.atomic.AtomicInteger;
 38 import java.util.concurrent.atomic.AtomicLong;
 39 import java.text.AttributedCharacterIterator.Attribute;
 40 
 41 import org.junit.jupiter.api.Test;
 42 import org.junit.jupiter.api.BeforeAll;
 43 
 44 import static org.junit.jupiter.api.Assertions.fail;
 45 
 46 /**
 47  * FormatTester creates Formats, and tests the resulting FieldPositions
 48  * and AttributedCharacterIterator based on a file. The file is a hierarchical
 49  * set of key/value pairs, where each value can also be an array or map. The
 50  * top map must contain a tests entry, which will be an array consisting
 51  * of pairs of maps. The first map specifies the Format that
 52  * should be created, and consists of:
 53  * <pre>
 54  *   class = className
 55  *   args = (arg1 arg2 ...)
 56  *   valueClass = className
 57  *   valueArgs = (arg1 arg2 ...)
 58  * </pre>
 59  * The second map dictates what to test, and should consist of the following:
 60  * <pre>
 61  *   length = lengthOfFormattedString
 62  *   text = Result of Formatting
 63  *   0...lengthOfFormattedString = (arg1 arg2 ...)
 64  *   limits = ( range1 range2 ...)
 65  *   fieldPositions = ( fp1 fp2 ...)
 66  * </pre>
 67  * <code>lengthOfFormattedString</code> indicate the total length of formatted
 68  * string. <code>text</code> indicates the resulting string.
 69  * <code>0...x</code> where x == <code>lengthOfFormattedString - 1</code> is
 70  * an array of the attributes that should exist at the particular
 71  * location. <code>limits</code> is an array of maps, where each map
 72  * can be used to test the bounds of a set of attributes. Each map will
 73  * consist of:
 74  * <pre>
 75  *   attributes = array of attributes
 76  *   begin = start location
 77  *   begin2 = second start location
 78  *   end = limit location
 79  *   end2 = second limit location
 80  * </pre>
 81  * These are tested by iterating from begin to end in the CharacterIterator
 82  * and doing the following at each index:
 83  * <pre>
 84  *   getRunStart() == begin
 85  *   getRunStart(attributes) == begin2
 86  *   getRunLimit() == end
 87  *   getRunLimit(attributes) == end2
 88  * </pre>
 89  * <code>fieldPositions</code> is used to test the results of invoking
 90  * <code>format</code> with a <code>FieldPosition</code>.
 91  * <code>fieldPositions</code> is an array of maps, where each map contains
 92  * the following:
 93  * <pre>
 94  *   field = Integer field reference (optional)
 95  *   fieldID = Object reference
 96  *   begin = begin index of FieldPosition after formatting
 97  *   end = end index of FieldPosition after formatting
 98  * </pre>
 99  * Any lines starting with {@code '#'} are comment lines and ignored.
100  */
101 public class FormatIteratorTest {
102 
103     /*
104      * Change JVM default Locale and TimeZone.
105      * The current tests are only appropriate for US. If tests are
106      * added for other locales are added, then a property should be
107      * added to each file (test) to be able to specify the locale.
108      */
109     @BeforeAll
110     static void initAll() {
111         Locale.setDefault(Locale.US);
112         TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
113     }
114 
115     private Format format;
116     private Object value;
117     private String text;
118 
119     public FormatIteratorTest() {
120     }
121 
122     @Test
123     public void testDecimalFormat() {
124         _test(new File(System.getProperty("test.src", "."),
125                        "decimalFormat.props"));
126     }
127 
128     @Test
129     public void testMessageFormat() {
130         _test(new File(System.getProperty("test.src", "."),
131                        "messageFormat.props"));
132     }
133 
134     @Test
135     public void testDateFormat() {
136         _test(new File(System.getProperty("test.src", "."),
137                        "dateFormat.props"));
138     }
139 
140     @SuppressWarnings("unchecked")
141     private void _test(File file) {
142         try {
143             System.out.println("testing: " + file);
144             PParser parser = new PParser();
145             Map<String,Object> contents = parser.parse(new BufferedReader(
146                 new FileReader(file)));
147             List<Object> test = (List)contents.get("tests");
148 
149             for (int counter = 0; counter < test.size(); counter++) {
150                 System.out.println("creating: " + (counter / 2));
151 
152                 AttributedCharacterIterator iterator =
153                     create((Map)test.get(counter));
154 
155                 System.out.println("verifying: " + (counter / 2));
156                 verify(iterator, (Map)test.get(++counter));
157             }
158         } catch (IOException ioe) {
159             fail("Error reading: " + ioe);
160         }
161     }
162 
163     @SuppressWarnings("unchecked")
164     public void verify(AttributedCharacterIterator iterator,Map<String,Object> table) {
165         int length = Integer.parseInt((String)table.get("length"));
166 
167         // Verify the text
168         if (!getText(iterator).equals(
169                 escapeIfNecessary((String)table.get("text")))) {
170             String text = getText(iterator);
171 
172             fail("text doesn't match, got: " + getText(iterator));
173         }
174         if (iterator.getBeginIndex() != 0) {
175             fail("Bogus start: " + iterator.getBeginIndex());
176         }
177         if (iterator.getEndIndex() != length) {
178             fail("Bogus end: " + iterator.getEndIndex());
179         }
180         for (int counter = 0; counter < length; counter++) {
181             iterator.setIndex(counter);
182             if (!verifyAttributes(iterator.getAttributes().keySet(),
183                     makeAttributes((List)table.get(Integer.
184                                                       toString(counter))))) {
185                 fail("Attributes don't match at " + counter + " expecting " +
186                       makeAttributes((List)table.get(Integer.toString
187                                                        (counter))) + " got " +
188                       iterator.getAttributes().keySet());
189             }
190         }
191         for (int counter = length - 1; counter >= 0; counter--) {
192             iterator.setIndex(counter);
193             if (!verifyAttributes(iterator.getAttributes().keySet(),
194                     makeAttributes((List)table.get(Integer.
195                                                       toString(counter))))) {
196                 fail("Attributes don't match at " + counter + " expecting " +
197                       makeAttributes((List)table.get(Integer.toString
198                                                        (counter))) + " got " +
199                       iterator.getAttributes().keySet());
200             }
201         }
202         verifyLimits(iterator, table);
203 
204         text = escapeIfNecessary((String)table.get("text"));
205         List<Object> fps = (List)table.get("fieldPositions");
206 
207         if (fps != null) {
208             for (int counter = 0; counter < fps.size(); counter++) {
209                 verifyFieldPosition(counter,(Map)fps.get(counter));
210             }
211         }
212     }
213 
214     @SuppressWarnings("unchecked")
215     private void verifyLimits(AttributedCharacterIterator iterator,
216                               Map<String,Object> table) {
217         List<Object> limits = (List)table.get("limits");
218 
219         if (limits != null) {
220             for (int counter = 0; counter < limits.size(); counter++) {
221                 verifyLimit(iterator, (Map)limits.get(counter));
222             }
223         }
224     }
225 
226     private void verifyLimit(AttributedCharacterIterator iterator,
227                              Map<String,Object> table) {
228         int begin = Integer.parseInt((String)table.get("begin"));
229         int end = Integer.parseInt((String)table.get("end"));
230         @SuppressWarnings("unchecked")
231         Set<Attribute> attrs = makeAttributes((List)table.get("attributes"));
232         String begin2S = (String)table.get("begin2");
233         int begin2 = (begin2S != null) ? Integer.parseInt(begin2S) : begin;
234         String end2S = (String)table.get("end2");
235         int end2 = (end2S != null) ? Integer.parseInt(end2S) : end;
236 
237         for (int counter = begin; counter < end; counter++) {
238             iterator.setIndex(counter);
239             if (iterator.getRunStart() != begin) {
240                 fail("Begin doesn't match want " + begin + " got " +
241                       iterator.getRunStart() + " at " + counter + " attrs " +
242                       attrs);
243             }
244             if (iterator.getRunStart(attrs) != begin2) {
245                 fail("Begin2 doesn't match want " + begin2 + " got " +
246                       iterator.getRunStart(attrs) + " at " + counter +
247                       " attrs " + attrs);
248             }
249             if (iterator.getRunLimit() != end) {
250                 fail("End doesn't match want " + end + " got " +
251                       iterator.getRunLimit() + " at " + counter + " attrs " +
252                       attrs);
253             }
254             if (iterator.getRunLimit(attrs) != end2) {
255                 fail("End2 doesn't match want " + end2 + " got " +
256                       iterator.getRunLimit(attrs) + " at " + counter +
257                       " attrs " + attrs);
258             }
259         }
260     }
261 
262     private boolean verifyAttributes(Set<Attribute> a, Set<Attribute> b) {
263         boolean aEmpty = a.isEmpty();
264         boolean bEmpty = b.isEmpty();
265 
266         if (aEmpty && bEmpty) {
267             return true;
268         }
269         else if (aEmpty || bEmpty) {
270             return false;
271         }
272         return a.equals(b);
273     }
274 
275     private String getText(AttributedCharacterIterator iterator) {
276         StringBuffer buffer = new StringBuffer();
277 
278         for (int counter = 0; counter < iterator.getEndIndex(); counter++) {
279             buffer.append(iterator.setIndex(counter));
280         }
281         return buffer.toString();
282     }
283 
284     private void verifyFieldPosition(int index, Map<String,Object> table) {
285         Object o = table.get("field");
286         int begin = Integer.parseInt((String)table.get("begin"));
287         int end = Integer.parseInt((String)table.get("end"));
288 
289         if (o != null) {
290             FieldPosition fp = new FieldPosition(((Integer)
291                                           lookupField((String)o)));
292 
293             verifyFieldPosition(fp, begin, end, index);
294         }
295         o = table.get("fieldID");
296         if (o != null) {
297             FieldPosition fp = new FieldPosition((Format.Field)
298                                                  lookupField((String)o));
299             verifyFieldPosition(fp, begin, end, index);
300         }
301     }
302 
303     private void verifyFieldPosition(FieldPosition fp, int begin, int end,
304                                      int index) {
305         StringBuffer buffer = new StringBuffer();
306 
307         format.format(value, buffer, fp);
308         if (fp.getBeginIndex() != begin) {
309             fail("bogus begin want " + begin + " got " + fp.getBeginIndex() +
310                   " for " + fp + " at " + index);
311         }
312         if (fp.getEndIndex() != end) {
313             fail("bogus end want " + end + " got " + fp.getEndIndex() +
314                   " for " + fp + " at " + index);
315         }
316         if (!buffer.toString().equals(text)) {
317             fail("Text does not match, want !" + buffer.toString() +
318                   "! got !" + text + "!");
319         }
320     }
321 
322     public AttributedCharacterIterator create(Map<String,Object> table) {
323         format = (Format)createInstance((String)table.get("class"),
324                                         ((List)table.get("args")).toArray());
325         value = createInstance((String)table.get("valueClass"),
326                                ((List)table.get("valueArgs")).toArray());
327 
328         System.out.println("Created format: " + format + " value " + value);
329         AttributedCharacterIterator aci = format.
330                            formatToCharacterIterator(value);
331 
332         System.out.println("Obtained Iterator: " + aci);
333         return aci;
334     }
335 
336     public Format.Field makeAttribute(String name) {
337         return (Format.Field)lookupField(name);
338     }
339 
340     private Object createInstance(String className, Object[] args) {
341         if (className.equals("java.lang.reflect.Array")) {
342             for (int counter = 0; counter < args.length; counter++) {
343                 if (args[counter] instanceof List) {
344                     @SuppressWarnings("unchecked")
345                     List<Object> v = (List<Object>)args[counter];
346 
347                     args[counter] = createInstance((String)v.get(0),
348                                                ((List)v.get(1)).toArray());
349                 }
350             }
351             return args;
352         }
353         for (int counter = 0; counter < args.length; counter++) {
354             args[counter] = escapeIfNecessary((String)args[counter]);
355         }
356         try {
357             if (className.equals("java.util.concurrent.atomic.AtomicInteger")) {
358                 return new AtomicInteger(Integer.valueOf((String)args[0]));
359             } else if (className.equals("java.util.concurrent.atomic.AtomicLong")) {
360                 return new AtomicLong(Long.valueOf((String)args[0]));
361             } else {
362                 Class<?> klass = lookupClass(className);
363                 Constructor<?> cons = klass.getConstructor(
364                     new Class<?>[] { String.class });
365                 Object value = cons.newInstance(args);
366 
367                 return value;
368             }
369         } catch (Throwable th) {
370             fail("Error creating instance " + th);
371             return null;
372         }
373     }
374 
375     private  Class<?> lookupClass(String name) throws ClassNotFoundException {
376         try {
377             Class<?> klass = Class.forName(name);
378 
379             return klass;
380         } catch (ClassNotFoundException e1) {}
381 
382         try {
383             Class<?> klass = Class.forName("java.lang." + name);
384 
385             return klass;
386         } catch (ClassNotFoundException e1) {}
387 
388         Class<?> klass = Class.forName("java.text." + name);
389 
390         return klass;
391     }
392 
393     private Object lookupField(String name) {
394         Throwable error = null;
395 
396         try {
397             int dotIndex = name.indexOf('.');
398             Class<?> klass = lookupClass(name.substring(0, dotIndex));
399             String fieldName = name.substring(dotIndex + 1);
400             Field[] fields = klass.getFields();
401 
402             for (int counter = fields.length - 1; counter >= 0; counter--) {
403                 if (fields[counter].getName().equals(fieldName)) {
404                     return fields[counter].get(null);
405                 }
406             }
407         } catch (Throwable th) {
408             error = th;
409         }
410         fail("Could not lookup field " + name + " " + error);
411         return null;
412     }
413 
414     protected String escapeIfNecessary(String string) {
415         if (string != null) {
416             int index;
417 
418             if ((index = string.indexOf("\\u")) != -1) {
419                 StringBuffer sb = new StringBuffer(string.substring(0, index));
420 
421                 sb.append((char)Integer.parseInt(
422                     string.substring(index + 2, index + 6), 16));
423                 sb.append(string.substring(index + 6));
424                 string = sb.toString();
425             }
426         }
427         return string;
428     }
429 
430     public Set<Attribute> makeAttributes(List<Object> names) {
431         Set<Attribute> set = HashSet.newHashSet(names.size());
432 
433         for (int counter = 0; counter < names.size(); counter++) {
434             set.add(makeAttribute((String)names.get(counter)));
435         }
436         return set;
437     }
438 }