1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 
27 /*
28  * (C) Copyright Taligent, Inc. 1996 - All Rights Reserved
29  * (C) Copyright IBM Corp. 1996 - All Rights Reserved
30  *
31  *   The original version of this source code and documentation is copyrighted
32  * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
33  * materials are provided under terms of a License Agreement between Taligent
34  * and Sun. This technology is protected by multiple US and International
35  * patents. This notice and attribution to Taligent may not be removed.
36  *   Taligent is a registered trademark of Taligent, Inc.
37  *
38  */
39 
40 package java.text;
41 
42 import java.io.IOException;
43 import java.io.ObjectInputStream;
44 import java.io.ObjectOutputStream;
45 import java.io.Serializable;
46 import java.lang.ref.SoftReference;
47 import java.util.Arrays;
48 import java.util.Locale;
49 import java.util.Objects;
50 import java.util.concurrent.ConcurrentHashMap;
51 import java.util.concurrent.ConcurrentMap;
52 
53 import libcore.icu.ICU;
54 import libcore.icu.LocaleData;
55 import libcore.icu.TimeZoneNames;
56 
57 /**
58  * <code>DateFormatSymbols</code> is a public class for encapsulating
59  * localizable date-time formatting data, such as the names of the
60  * months, the names of the days of the week, and the time zone data.
61  * <code>SimpleDateFormat</code> uses
62  * <code>DateFormatSymbols</code> to encapsulate this information.
63  *
64  * <p>
65  * Typically you shouldn't use <code>DateFormatSymbols</code> directly.
66  * Rather, you are encouraged to create a date-time formatter with the
67  * <code>DateFormat</code> class's factory methods: <code>getTimeInstance</code>,
68  * <code>getDateInstance</code>, or <code>getDateTimeInstance</code>.
69  * These methods automatically create a <code>DateFormatSymbols</code> for
70  * the formatter so that you don't have to. After the
71  * formatter is created, you may modify its format pattern using the
72  * <code>setPattern</code> method. For more information about
73  * creating formatters using <code>DateFormat</code>'s factory methods,
74  * see {@link DateFormat}.
75  *
76  * <p>
77  * If you decide to create a date-time formatter with a specific
78  * format pattern for a specific locale, you can do so with:
79  * <blockquote>
80  * <pre>
81  * new SimpleDateFormat(aPattern, DateFormatSymbols.getInstance(aLocale)).
82  * </pre>
83  * </blockquote>
84  *
85  * <p>
86  * <code>DateFormatSymbols</code> objects are cloneable. When you obtain
87  * a <code>DateFormatSymbols</code> object, feel free to modify the
88  * date-time formatting data. For instance, you can replace the localized
89  * date-time format pattern characters with the ones that you feel easy
90  * to remember. Or you can change the representative cities
91  * to your favorite ones.
92  *
93  * <p>
94  * New <code>DateFormatSymbols</code> subclasses may be added to support
95  * <code>SimpleDateFormat</code> for date-time formatting for additional locales.
96 
97  * @see          DateFormat
98  * @see          SimpleDateFormat
99  * @see          java.util.SimpleTimeZone
100  * @author       Chen-Lieh Huang
101  */
102 public class DateFormatSymbols implements Serializable, Cloneable {
103 
104     // Android-changed: Removed reference to DateFormatSymbolsProvider but suggested getInstance().
105     // be used instead in case Android supports it in future.
106     /**
107      * Construct a DateFormatSymbols object by loading format data from
108      * resources for the default {@link java.util.Locale.Category#FORMAT FORMAT}
109      * locale. It is recommended that the {@link #getInstance(Locale) getInstance} method is used
110      * instead.
111      * <p>This is equivalent to calling
112      * {@link #DateFormatSymbols(Locale)
113      *     DateFormatSymbols(Locale.getDefault(Locale.Category.FORMAT))}.
114      * @see #getInstance()
115      * @see java.util.Locale#getDefault(java.util.Locale.Category)
116      * @see java.util.Locale.Category#FORMAT
117      * @exception  java.util.MissingResourceException
118      *             if the resources for the default locale cannot be
119      *             found or cannot be loaded.
120      */
DateFormatSymbols()121     public DateFormatSymbols()
122     {
123         initializeData(Locale.getDefault(Locale.Category.FORMAT));
124     }
125 
126     // Android-changed: Removed reference to DateFormatSymbolsProvider but suggested getInstance().
127     // be used instead in case Android supports it in future.
128     /**
129      * Construct a DateFormatSymbols object by loading format data from
130      * resources for the given locale. It is recommended that the
131      * {@link #getInstance(Locale) getInstance} method is used instead.
132      *
133      * @param locale the desired locale
134      * @see #getInstance(Locale)
135      * @exception  java.util.MissingResourceException
136      *             if the resources for the specified locale cannot be
137      *             found or cannot be loaded.
138      */
DateFormatSymbols(Locale locale)139     public DateFormatSymbols(Locale locale)
140     {
141         initializeData(locale);
142     }
143 
144     // Android-removed: unused private DateFormatSymbols(boolean) constructor.
145 
146     /**
147      * Era strings. For example: "AD" and "BC".  An array of 2 strings,
148      * indexed by <code>Calendar.BC</code> and <code>Calendar.AD</code>.
149      * @serial
150      */
151     String eras[] = null;
152 
153     /**
154      * Month strings. For example: "January", "February", etc.  An array
155      * of 13 strings (some calendars have 13 months), indexed by
156      * <code>Calendar.JANUARY</code>, <code>Calendar.FEBRUARY</code>, etc.
157      * @serial
158      */
159     String months[] = null;
160 
161     /**
162      * Short month strings. For example: "Jan", "Feb", etc.  An array of
163      * 13 strings (some calendars have 13 months), indexed by
164      * <code>Calendar.JANUARY</code>, <code>Calendar.FEBRUARY</code>, etc.
165 
166      * @serial
167      */
168     String shortMonths[] = null;
169 
170     /**
171      * Weekday strings. For example: "Sunday", "Monday", etc.  An array
172      * of 8 strings, indexed by <code>Calendar.SUNDAY</code>,
173      * <code>Calendar.MONDAY</code>, etc.
174      * The element <code>weekdays[0]</code> is ignored.
175      * @serial
176      */
177     String weekdays[] = null;
178 
179     /**
180      * Short weekday strings. For example: "Sun", "Mon", etc.  An array
181      * of 8 strings, indexed by <code>Calendar.SUNDAY</code>,
182      * <code>Calendar.MONDAY</code>, etc.
183      * The element <code>shortWeekdays[0]</code> is ignored.
184      * @serial
185      */
186     String shortWeekdays[] = null;
187 
188     /**
189      * AM and PM strings. For example: "AM" and "PM".  An array of
190      * 2 strings, indexed by <code>Calendar.AM</code> and
191      * <code>Calendar.PM</code>.
192      * @serial
193      */
194     String ampms[] = null;
195 
196     /**
197      * Localized names of time zones in this locale.  This is a
198      * two-dimensional array of strings of size <em>n</em> by <em>m</em>,
199      * where <em>m</em> is at least 5.  Each of the <em>n</em> rows is an
200      * entry containing the localized names for a single <code>TimeZone</code>.
201      * Each such row contains (with <code>i</code> ranging from
202      * 0..<em>n</em>-1):
203      * <ul>
204      * <li><code>zoneStrings[i][0]</code> - time zone ID</li>
205      * <li><code>zoneStrings[i][1]</code> - long name of zone in standard
206      * time</li>
207      * <li><code>zoneStrings[i][2]</code> - short name of zone in
208      * standard time</li>
209      * <li><code>zoneStrings[i][3]</code> - long name of zone in daylight
210      * saving time</li>
211      * <li><code>zoneStrings[i][4]</code> - short name of zone in daylight
212      * saving time</li>
213      * </ul>
214      * The zone ID is <em>not</em> localized; it's one of the valid IDs of
215      * the {@link java.util.TimeZone TimeZone} class that are not
216      * <a href="../java/util/TimeZone.html#CustomID">custom IDs</a>.
217      * All other entries are localized names.
218      * @see java.util.TimeZone
219      * @serial
220      */
221     String zoneStrings[][] = null;
222 
223     /**
224      * Indicates that zoneStrings is set externally with setZoneStrings() method.
225      */
226     transient boolean isZoneStringsSet = false;
227 
228     /**
229      * Unlocalized date-time pattern characters. For example: 'y', 'd', etc.
230      * All locales use the same these unlocalized pattern characters.
231      */
232     // Android-changed: Add 'c' (standalone day of week), 'b' (day period),.
233     //   'B' (flexible day period)
234     static final String  patternChars = "GyMdkHmsSEDFwWahKzZYuXLcbB";
235 
236     static final int PATTERN_ERA                  =  0; // G
237     static final int PATTERN_YEAR                 =  1; // y
238     static final int PATTERN_MONTH                =  2; // M
239     static final int PATTERN_DAY_OF_MONTH         =  3; // d
240     static final int PATTERN_HOUR_OF_DAY1         =  4; // k
241     static final int PATTERN_HOUR_OF_DAY0         =  5; // H
242     static final int PATTERN_MINUTE               =  6; // m
243     static final int PATTERN_SECOND               =  7; // s
244     static final int PATTERN_MILLISECOND          =  8; // S
245     static final int PATTERN_DAY_OF_WEEK          =  9; // E
246     static final int PATTERN_DAY_OF_YEAR          = 10; // D
247     static final int PATTERN_DAY_OF_WEEK_IN_MONTH = 11; // F
248     static final int PATTERN_WEEK_OF_YEAR         = 12; // w
249     static final int PATTERN_WEEK_OF_MONTH        = 13; // W
250     static final int PATTERN_AM_PM                = 14; // a
251     static final int PATTERN_HOUR1                = 15; // h
252     static final int PATTERN_HOUR0                = 16; // K
253     static final int PATTERN_ZONE_NAME            = 17; // z
254     static final int PATTERN_ZONE_VALUE           = 18; // Z
255     static final int PATTERN_WEEK_YEAR            = 19; // Y
256     static final int PATTERN_ISO_DAY_OF_WEEK      = 20; // u
257     static final int PATTERN_ISO_ZONE             = 21; // X
258     static final int PATTERN_MONTH_STANDALONE     = 22; // L
259     // Android-added: Constant for standalone day of week.
260     static final int PATTERN_STANDALONE_DAY_OF_WEEK = 23; // c
261     // Android-added: Constant for pattern letter 'b', 'B'.
262     static final int PATTERN_DAY_PERIOD = 24; // b
263     static final int PATTERN_FLEXIBLE_DAY_PERIOD = 25; // B
264 
265     /**
266      * Localized date-time pattern characters. For example, a locale may
267      * wish to use 'u' rather than 'y' to represent years in its date format
268      * pattern strings.
269      * This string must be exactly 18 characters long, with the index of
270      * the characters described by <code>DateFormat.ERA_FIELD</code>,
271      * <code>DateFormat.YEAR_FIELD</code>, etc.  Thus, if the string were
272      * "Xz...", then localized patterns would use 'X' for era and 'z' for year.
273      * @serial
274      */
275     String  localPatternChars = null;
276 
277     /**
278      * The locale which is used for initializing this DateFormatSymbols object.
279      *
280      * @since 1.6
281      * @serial
282      */
283     Locale locale = null;
284 
285     /* use serialVersionUID from JDK 1.1.4 for interoperability */
286     static final long serialVersionUID = -5987973545549424702L;
287 
288     // BEGIN Android-added: Android specific serialization code.
289     // the internal serial version which says which version was written
290     // - 0 (default) for version up to JDK 1.1.4
291     // - 1 Android version that contains a whole bunch of new fields.
292     static final int currentSerialVersion = 1;
293 
294     /**
295      * The version of the serialized data on the stream.  Possible values:
296      * <ul>
297      * <li><b>0</b> or not present on stream: JDK 1.1.4.
298      * <li><b>1</b> Android:
299      * </ul>
300      * When streaming out this class, the most recent format
301      * and the highest allowable <code>serialVersionOnStream</code>
302      * is written.
303      * @serial
304      * @since JDK1.1.4
305      */
306     private int serialVersionOnStream = currentSerialVersion;
307     // END Android-added: Android specific serialization code.
308 
309     // BEGIN Android-added: Support for tiny and standalone field names.
310     /**
311      * Tiny month strings; "J", "F", "M" etc.
312      *
313      * @serial
314      */
315     private String[] tinyMonths;
316 
317     /**
318      * Tiny weekday strings: "M", "F", "W" etc.
319      *
320      * @serial
321      */
322     private String[] tinyWeekdays;
323 
324     /**
325      * Standalone month strings; "January", "February", "March" etc.
326      *
327      * @serial
328      */
329     private String[] standAloneMonths;
330 
331     /**
332      * Short standalone month strings: "Jan", "Feb", "Mar" etc.
333      *
334      * @serial
335      */
336     private String[] shortStandAloneMonths;
337 
338     /**
339      * Tiny standalone month strings: "J", "F", "M" etc.
340      *
341      * @serial
342      */
343     private String[] tinyStandAloneMonths;
344 
345     /**
346      * Standalone weekday strings; "Monday", "Tuesday", "Wednesday" etc.
347      *
348      * @serial
349      */
350     private String[] standAloneWeekdays;
351 
352     /**
353      * Short standalone weekday strings; "Mon", "Tue", "Wed" etc.
354      *
355      * @serial
356      */
357     private String[] shortStandAloneWeekdays;
358 
359     /**
360      * Tiny standalone weekday strings; "M", "T", "W" etc.
361      *
362      * @serial
363      */
364     private String[] tinyStandAloneWeekdays;
365     // END Android-added: Support for tiny and standalone field names.
366 
367     // Android-changed: Removed reference to DateFormatSymbolsProvider.
368     /**
369      * Returns an array of all locales for which the
370      * <code>getInstance</code> methods of this class can return
371      * localized instances.
372      *
373      * @return An array of locales for which localized
374      *         <code>DateFormatSymbols</code> instances are available.
375      * @since 1.6
376      */
getAvailableLocales()377     public static Locale[] getAvailableLocales() {
378         // Android-changed: No support for DateFormatSymbolsProvider.
379         return ICU.getAvailableLocales();
380     }
381 
382     // Android-changed: Removed reference to DateFormatSymbolsProvider.
383     /**
384      * Gets the <code>DateFormatSymbols</code> instance for the default
385      * locale.
386      * <p>This is equivalent to calling {@link #getInstance(Locale)
387      *     getInstance(Locale.getDefault(Locale.Category.FORMAT))}.
388      * @see java.util.Locale#getDefault(java.util.Locale.Category)
389      * @see java.util.Locale.Category#FORMAT
390      * @return a <code>DateFormatSymbols</code> instance.
391      * @since 1.6
392      */
getInstance()393     public static final DateFormatSymbols getInstance() {
394         return getInstance(Locale.getDefault(Locale.Category.FORMAT));
395     }
396 
397     // Android-changed: Removed reference to DateFormatSymbolsProvider.
398     /**
399      * Gets the <code>DateFormatSymbols</code> instance for the specified
400      * locale.
401      * @param locale the given locale.
402      * @return a <code>DateFormatSymbols</code> instance.
403      * @exception NullPointerException if <code>locale</code> is null
404      * @since 1.6
405      */
getInstance(Locale locale)406     public static final DateFormatSymbols getInstance(Locale locale) {
407         // Android-changed: Removed used of DateFormatSymbolsProvider.
408         return (DateFormatSymbols) getCachedInstance(locale).clone();
409     }
410 
411     /**
412      * Returns a DateFormatSymbols provided by a provider or found in
413      * the cache. Note that this method returns a cached instance,
414      * not its clone. Therefore, the instance should never be given to
415      * an application.
416      */
getInstanceRef(Locale locale)417     static final DateFormatSymbols getInstanceRef(Locale locale) {
418         // Android-changed: Removed used of DateFormatSymbolsProvider.
419         return getCachedInstance(locale);
420     }
421 
422     // BEGIN Android-changed: Replace getProviderInstance() with getCachedInstance().
423     // Android removed support for DateFormatSymbolsProviders, but still caches DFS.
424     // App compat change for b/159514442.
425     /**
426      * Returns a cached DateFormatSymbols if it's found in the
427      * cache. Otherwise, this method returns a newly cached instance
428      * for the given locale.
429      */
getCachedInstance(Locale locale)430     private static DateFormatSymbols getCachedInstance(Locale locale) {
431         Locale cacheKey = LocaleData.getCompatibleLocaleForBug159514442(locale);
432         SoftReference<DateFormatSymbols> ref = cachedInstances.get(cacheKey);
433         DateFormatSymbols dfs;
434         if (ref == null || (dfs = ref.get()) == null) {
435             dfs = new DateFormatSymbols(locale);
436             ref = new SoftReference<>(dfs);
437             SoftReference<DateFormatSymbols> x = cachedInstances.putIfAbsent(cacheKey, ref);
438             if (x != null) {
439                 DateFormatSymbols y = x.get();
440                 if (y != null) {
441                     dfs = y;
442                 } else {
443                     // Replace the empty SoftReference with ref.
444                     cachedInstances.put(cacheKey, ref);
445                 }
446             }
447         }
448         return dfs;
449     }
450     // END Android-changed: Replace getProviderInstance() with getCachedInstance().
451 
452     /**
453      * Gets era strings. For example: "AD" and "BC".
454      * @return the era strings.
455      */
getEras()456     public String[] getEras() {
457         return Arrays.copyOf(eras, eras.length);
458     }
459 
460     /**
461      * Sets era strings. For example: "AD" and "BC".
462      * @param newEras the new era strings.
463      */
setEras(String[] newEras)464     public void setEras(String[] newEras) {
465         eras = Arrays.copyOf(newEras, newEras.length);
466         cachedHashCode = 0;
467     }
468 
469     /**
470      * Gets month strings. For example: "January", "February", etc.
471      *
472      * <p>If the language requires different forms for formatting and
473      * stand-alone usages, this method returns month names in the
474      * formatting form. For example, the preferred month name for
475      * January in the Czech language is <em>ledna</em> in the
476      * formatting form, while it is <em>leden</em> in the stand-alone
477      * form. This method returns {@code "ledna"} in this case. Refer
478      * to the <a href="http://unicode.org/reports/tr35/#Calendar_Elements">
479      * Calendar Elements in the Unicode Locale Data Markup Language
480      * (LDML) specification</a> for more details.
481      *
482      * @return the month strings.
483      */
getMonths()484     public String[] getMonths() {
485         return Arrays.copyOf(months, months.length);
486     }
487 
488     /**
489      * Sets month strings. For example: "January", "February", etc.
490      * @param newMonths the new month strings.
491      */
setMonths(String[] newMonths)492     public void setMonths(String[] newMonths) {
493         months = Arrays.copyOf(newMonths, newMonths.length);
494         cachedHashCode = 0;
495     }
496 
497     /**
498      * Gets short month strings. For example: "Jan", "Feb", etc.
499      *
500      * <p>If the language requires different forms for formatting and
501      * stand-alone usages, This method returns short month names in
502      * the formatting form. For example, the preferred abbreviation
503      * for January in the Catalan language is <em>de gen.</em> in the
504      * formatting form, while it is <em>gen.</em> in the stand-alone
505      * form. This method returns {@code "de gen."} in this case. Refer
506      * to the <a href="http://unicode.org/reports/tr35/#Calendar_Elements">
507      * Calendar Elements in the Unicode Locale Data Markup Language
508      * (LDML) specification</a> for more details.
509      *
510      * @return the short month strings.
511      */
getShortMonths()512     public String[] getShortMonths() {
513         return Arrays.copyOf(shortMonths, shortMonths.length);
514     }
515 
516     /**
517      * Sets short month strings. For example: "Jan", "Feb", etc.
518      * @param newShortMonths the new short month strings.
519      */
setShortMonths(String[] newShortMonths)520     public void setShortMonths(String[] newShortMonths) {
521         shortMonths = Arrays.copyOf(newShortMonths, newShortMonths.length);
522         cachedHashCode = 0;
523     }
524 
525     /**
526      * Gets weekday strings. For example: "Sunday", "Monday", etc.
527      * @return the weekday strings. Use <code>Calendar.SUNDAY</code>,
528      * <code>Calendar.MONDAY</code>, etc. to index the result array.
529      */
getWeekdays()530     public String[] getWeekdays() {
531         return Arrays.copyOf(weekdays, weekdays.length);
532     }
533 
534     /**
535      * Sets weekday strings. For example: "Sunday", "Monday", etc.
536      * @param newWeekdays the new weekday strings. The array should
537      * be indexed by <code>Calendar.SUNDAY</code>,
538      * <code>Calendar.MONDAY</code>, etc.
539      */
setWeekdays(String[] newWeekdays)540     public void setWeekdays(String[] newWeekdays) {
541         weekdays = Arrays.copyOf(newWeekdays, newWeekdays.length);
542         cachedHashCode = 0;
543     }
544 
545     /**
546      * Gets short weekday strings. For example: "Sun", "Mon", etc.
547      * @return the short weekday strings. Use <code>Calendar.SUNDAY</code>,
548      * <code>Calendar.MONDAY</code>, etc. to index the result array.
549      */
getShortWeekdays()550     public String[] getShortWeekdays() {
551         return Arrays.copyOf(shortWeekdays, shortWeekdays.length);
552     }
553 
554     /**
555      * Sets short weekday strings. For example: "Sun", "Mon", etc.
556      * @param newShortWeekdays the new short weekday strings. The array should
557      * be indexed by <code>Calendar.SUNDAY</code>,
558      * <code>Calendar.MONDAY</code>, etc.
559      */
setShortWeekdays(String[] newShortWeekdays)560     public void setShortWeekdays(String[] newShortWeekdays) {
561         shortWeekdays = Arrays.copyOf(newShortWeekdays, newShortWeekdays.length);
562         cachedHashCode = 0;
563     }
564 
565     /**
566      * Gets ampm strings. For example: "AM" and "PM".
567      * @return the ampm strings.
568      */
getAmPmStrings()569     public String[] getAmPmStrings() {
570         return Arrays.copyOf(ampms, ampms.length);
571     }
572 
573     /**
574      * Sets ampm strings. For example: "AM" and "PM".
575      * @param newAmpms the new ampm strings.
576      */
setAmPmStrings(String[] newAmpms)577     public void setAmPmStrings(String[] newAmpms) {
578         ampms = Arrays.copyOf(newAmpms, newAmpms.length);
579         cachedHashCode = 0;
580     }
581 
582     // Android-changed: Removed reference to TimeZoneNameProvider.
583     /**
584      * Gets time zone strings.  Use of this method is discouraged; use
585      * {@link java.util.TimeZone#getDisplayName() TimeZone.getDisplayName()}
586      * instead.
587      * <p>
588      * The value returned is a
589      * two-dimensional array of strings of size <em>n</em> by <em>m</em>,
590      * where <em>m</em> is at least 5.  Each of the <em>n</em> rows is an
591      * entry containing the localized names for a single <code>TimeZone</code>.
592      * Each such row contains (with <code>i</code> ranging from
593      * 0..<em>n</em>-1):
594      * <ul>
595      * <li><code>zoneStrings[i][0]</code> - time zone ID</li>
596      * <li><code>zoneStrings[i][1]</code> - long name of zone in standard
597      * time</li>
598      * <li><code>zoneStrings[i][2]</code> - short name of zone in
599      * standard time</li>
600      * <li><code>zoneStrings[i][3]</code> - long name of zone in daylight
601      * saving time</li>
602      * <li><code>zoneStrings[i][4]</code> - short name of zone in daylight
603      * saving time</li>
604      * </ul>
605      * The zone ID is <em>not</em> localized; it's one of the valid IDs of
606      * the {@link java.util.TimeZone TimeZone} class that are not
607      * <a href="../util/TimeZone.html#CustomID">custom IDs</a>.
608      * All other entries are localized names.  If a zone does not implement
609      * daylight saving time, the daylight saving time names should not be used.
610      * <p>
611      * If {@link #setZoneStrings(String[][]) setZoneStrings} has been called
612      * on this <code>DateFormatSymbols</code> instance, then the strings
613      * provided by that call are returned. Otherwise, the returned array
614      * contains names provided by the runtime.
615      *
616      * @return the time zone strings.
617      * @see #setZoneStrings(String[][])
618      */
getZoneStrings()619     public String[][] getZoneStrings() {
620         return getZoneStringsImpl(true);
621     }
622 
623     /**
624      * Sets time zone strings.  The argument must be a
625      * two-dimensional array of strings of size <em>n</em> by <em>m</em>,
626      * where <em>m</em> is at least 5.  Each of the <em>n</em> rows is an
627      * entry containing the localized names for a single <code>TimeZone</code>.
628      * Each such row contains (with <code>i</code> ranging from
629      * 0..<em>n</em>-1):
630      * <ul>
631      * <li><code>zoneStrings[i][0]</code> - time zone ID</li>
632      * <li><code>zoneStrings[i][1]</code> - long name of zone in standard
633      * time</li>
634      * <li><code>zoneStrings[i][2]</code> - short name of zone in
635      * standard time</li>
636      * <li><code>zoneStrings[i][3]</code> - long name of zone in daylight
637      * saving time</li>
638      * <li><code>zoneStrings[i][4]</code> - short name of zone in daylight
639      * saving time</li>
640      * </ul>
641      * The zone ID is <em>not</em> localized; it's one of the valid IDs of
642      * the {@link java.util.TimeZone TimeZone} class that are not
643      * <a href="../util/TimeZone.html#CustomID">custom IDs</a>.
644      * All other entries are localized names.
645      *
646      * @param newZoneStrings the new time zone strings.
647      * @exception IllegalArgumentException if the length of any row in
648      *    <code>newZoneStrings</code> is less than 5
649      * @exception NullPointerException if <code>newZoneStrings</code> is null
650      * @see #getZoneStrings()
651      */
setZoneStrings(String[][] newZoneStrings)652     public void setZoneStrings(String[][] newZoneStrings) {
653         String[][] aCopy = new String[newZoneStrings.length][];
654         for (int i = 0; i < newZoneStrings.length; ++i) {
655             int len = newZoneStrings[i].length;
656             if (len < 5) {
657                 throw new IllegalArgumentException();
658             }
659             aCopy[i] = Arrays.copyOf(newZoneStrings[i], len);
660         }
661         zoneStrings = aCopy;
662         isZoneStringsSet = true;
663         // Android-changed: don't include zone strings in hashCode to avoid populating it.
664         // cachedHashCode = 0;
665     }
666 
667     /**
668      * Gets localized date-time pattern characters. For example: 'u', 't', etc.
669      * @return the localized date-time pattern characters.
670      */
getLocalPatternChars()671     public String getLocalPatternChars() {
672         return localPatternChars;
673     }
674 
675     /**
676      * Sets localized date-time pattern characters. For example: 'u', 't', etc.
677      * @param newLocalPatternChars the new localized date-time
678      * pattern characters.
679      */
setLocalPatternChars(String newLocalPatternChars)680     public void setLocalPatternChars(String newLocalPatternChars) {
681         // Call toString() to throw an NPE in case the argument is null
682         localPatternChars = newLocalPatternChars.toString();
683         cachedHashCode = 0;
684     }
685 
686     // BEGIN Android-added: Support for tiny and standalone field names.
getTinyMonths()687     String[] getTinyMonths() {
688         return tinyMonths;
689     }
690 
getStandAloneMonths()691     String[] getStandAloneMonths() {
692         return standAloneMonths;
693     }
694 
getShortStandAloneMonths()695     String[] getShortStandAloneMonths() {
696         return shortStandAloneMonths;
697     }
698 
getTinyStandAloneMonths()699     String[] getTinyStandAloneMonths() {
700         return tinyStandAloneMonths;
701     }
702 
getTinyWeekdays()703     String[] getTinyWeekdays() {
704         return tinyWeekdays;
705     }
706 
getStandAloneWeekdays()707     String[] getStandAloneWeekdays() {
708         return standAloneWeekdays;
709     }
710 
getShortStandAloneWeekdays()711     String[] getShortStandAloneWeekdays() {
712         return shortStandAloneWeekdays;
713     }
714 
getTinyStandAloneWeekdays()715     String[] getTinyStandAloneWeekdays() {
716         return tinyStandAloneWeekdays;
717     }
718     // END Android-added: Support for tiny and standalone field names.
719 
720     /**
721      * Overrides Cloneable
722      */
clone()723     public Object clone()
724     {
725         try
726         {
727             DateFormatSymbols other = (DateFormatSymbols)super.clone();
728             copyMembers(this, other);
729             return other;
730         } catch (CloneNotSupportedException e) {
731             throw new InternalError(e);
732         }
733     }
734 
735     /**
736      * Override hashCode.
737      * Generates a hash code for the DateFormatSymbols object.
738      */
739     @Override
hashCode()740     public int hashCode() {
741         int hashCode = cachedHashCode;
742         if (hashCode == 0) {
743             hashCode = 5;
744             hashCode = 11 * hashCode + Arrays.hashCode(eras);
745             hashCode = 11 * hashCode + Arrays.hashCode(months);
746             hashCode = 11 * hashCode + Arrays.hashCode(shortMonths);
747             hashCode = 11 * hashCode + Arrays.hashCode(weekdays);
748             hashCode = 11 * hashCode + Arrays.hashCode(shortWeekdays);
749             hashCode = 11 * hashCode + Arrays.hashCode(ampms);
750             // Android-changed: Don't include zone strings in hashCode to avoid populating it.
751             // hashCode = 11 * hashCode + Arrays.deepHashCode(getZoneStringsWrapper());
752             hashCode = 11 * hashCode + Objects.hashCode(localPatternChars);
753             cachedHashCode = hashCode;
754         }
755 
756         return hashCode;
757     }
758 
759     /**
760      * Override equals
761      */
equals(Object obj)762     public boolean equals(Object obj)
763     {
764         if (this == obj) return true;
765         if (obj == null || getClass() != obj.getClass()) return false;
766         DateFormatSymbols that = (DateFormatSymbols) obj;
767         // BEGIN Android-changed: Avoid populating zoneStrings just for the comparison, add fields.
768         if (!(Arrays.equals(eras, that.eras)
769                 && Arrays.equals(months, that.months)
770                 && Arrays.equals(shortMonths, that.shortMonths)
771                 && Arrays.equals(tinyMonths, that.tinyMonths)
772                 && Arrays.equals(weekdays, that.weekdays)
773                 && Arrays.equals(shortWeekdays, that.shortWeekdays)
774                 && Arrays.equals(tinyWeekdays, that.tinyWeekdays)
775                 && Arrays.equals(standAloneMonths, that.standAloneMonths)
776                 && Arrays.equals(shortStandAloneMonths, that.shortStandAloneMonths)
777                 && Arrays.equals(tinyStandAloneMonths, that.tinyStandAloneMonths)
778                 && Arrays.equals(standAloneWeekdays, that.standAloneWeekdays)
779                 && Arrays.equals(shortStandAloneWeekdays, that.shortStandAloneWeekdays)
780                 && Arrays.equals(tinyStandAloneWeekdays, that.tinyStandAloneWeekdays)
781                 && Arrays.equals(ampms, that.ampms)
782                 && ((localPatternChars != null
783                   && localPatternChars.equals(that.localPatternChars))
784                  || (localPatternChars == null
785                   && that.localPatternChars == null)))) {
786             return false;
787         }
788         if (!isZoneStringsSet && !that.isZoneStringsSet && Objects.equals(locale, that.locale)) {
789             return true;
790         }
791         return Arrays.deepEquals(getZoneStringsWrapper(), that.getZoneStringsWrapper());
792         // END Android-changed: Avoid populating zoneStrings just for the comparison, add fields.
793     }
794 
795     // =======================privates===============================
796 
797     /**
798      * Useful constant for defining time zone offsets.
799      */
800     static final int millisPerHour = 60*60*1000;
801 
802     /**
803      * Cache to hold DateFormatSymbols instances per Locale.
804      */
805     private static final ConcurrentMap<Locale, SoftReference<DateFormatSymbols>> cachedInstances
806         = new ConcurrentHashMap<>(3);
807 
808     private transient int lastZoneIndex = 0;
809 
810     /**
811      * Cached hash code
812      */
813     transient volatile int cachedHashCode = 0;
814 
815     // Android-changed: update comment to describe local modification.
816     /**
817      * Initializes this DateFormatSymbols with the locale data. This method uses
818      * a cached DateFormatSymbols instance for the given locale if available. If
819      * there's no cached one, this method populates this objects fields from an
820      * appropriate LocaleData object. Note: zoneStrings isn't initialized in this method.
821      */
initializeData(Locale locale)822     private void initializeData(Locale locale) {
823         // Android-changed: App compat change for b/159514442.
824         Locale cacheKey = LocaleData.getCompatibleLocaleForBug159514442(locale);
825         SoftReference<DateFormatSymbols> ref = cachedInstances.get(cacheKey);
826         DateFormatSymbols dfs;
827         // Android-changed: invert cache presence check to simplify code flow.
828         if (ref != null && (dfs = ref.get()) != null) {
829             copyMembers(dfs, this);
830             return;
831         }
832 
833         // BEGIN Android-changed: Use ICU data and move cache handling to getCachedInstance().
834         locale = LocaleData.mapInvalidAndNullLocales(locale);
835         LocaleData localeData = LocaleData.get(locale);
836 
837         this.locale = locale;
838         eras = localeData.eras;
839         months = localeData.longMonthNames;
840         shortMonths = localeData.shortMonthNames;
841         ampms = localeData.amPm;
842         localPatternChars = patternChars;
843 
844         weekdays = localeData.longWeekdayNames;
845         shortWeekdays = localeData.shortWeekdayNames;
846 
847         initializeSupplementaryData(localeData);
848         // END Android-changed: Use ICU data and move cache handling to getCachedInstance().
849     }
850 
851     // Android-removed: toOneBasedArray(String[]).
852 
853     // BEGIN Android-added: initializeSupplementaryData(LocaleData) for tiny and standalone fields.
initializeSupplementaryData(LocaleData localeData)854     private void initializeSupplementaryData(LocaleData localeData) {
855         // Tiny weekdays and months.
856         tinyMonths = localeData.tinyMonthNames;
857         tinyWeekdays = localeData.tinyWeekdayNames;
858 
859         // Standalone month names.
860         standAloneMonths = localeData.longStandAloneMonthNames;
861         shortStandAloneMonths = localeData.shortStandAloneMonthNames;
862         tinyStandAloneMonths = localeData.tinyStandAloneMonthNames;
863 
864         // Standalone weekdays.
865         standAloneWeekdays = localeData.longStandAloneWeekdayNames;
866         shortStandAloneWeekdays = localeData.shortStandAloneWeekdayNames;
867         tinyStandAloneWeekdays = localeData.tinyStandAloneWeekdayNames;
868     }
869     // END Android-added: initializeSupplementaryData(LocaleData) for tiny and standalone fields.
870 
871     /**
872      * Package private: used by SimpleDateFormat
873      * Gets the index for the given time zone ID to obtain the time zone
874      * strings for formatting. The time zone ID is just for programmatic
875      * lookup. NOT LOCALIZED!!!
876      * @param ID the given time zone ID.
877      * @return the index of the given time zone ID.  Returns -1 if
878      * the given time zone ID can't be located in the DateFormatSymbols object.
879      * @see java.util.SimpleTimeZone
880      */
getZoneIndex(String ID)881     final int getZoneIndex(String ID) {
882         String[][] zoneStrings = getZoneStringsWrapper();
883 
884         /*
885          * getZoneIndex has been re-written for performance reasons. instead of
886          * traversing the zoneStrings array every time, we cache the last used zone
887          * index
888          */
889         if (lastZoneIndex < zoneStrings.length && ID.equals(zoneStrings[lastZoneIndex][0])) {
890             return lastZoneIndex;
891         }
892 
893         /* slow path, search entire list */
894         for (int index = 0; index < zoneStrings.length; index++) {
895             if (ID.equals(zoneStrings[index][0])) {
896                 lastZoneIndex = index;
897                 return index;
898             }
899         }
900 
901         return -1;
902     }
903 
904     /**
905      * Wrapper method to the getZoneStrings(), which is called from inside
906      * the java.text package and not to mutate the returned arrays, so that
907      * it does not need to create a defensive copy.
908      */
getZoneStringsWrapper()909     final String[][] getZoneStringsWrapper() {
910         if (isSubclassObject()) {
911             return getZoneStrings();
912         } else {
913             return getZoneStringsImpl(false);
914         }
915     }
916 
917     // BEGIN Android-changed: extract initialization of zoneStrings to separate method.
internalZoneStrings()918     private synchronized String[][] internalZoneStrings() {
919         if (zoneStrings == null) {
920             zoneStrings = TimeZoneNames.getZoneStrings(locale);
921         }
922         return zoneStrings;
923     }
924     // END Android-changed: extract initialization of zoneStrings to separate method.
925 
getZoneStringsImpl(boolean needsCopy)926     private String[][] getZoneStringsImpl(boolean needsCopy) {
927         // Android-changed: use helper method to initialize zoneStrings.
928         String[][] zoneStrings = internalZoneStrings();
929 
930         if (!needsCopy) {
931             return zoneStrings;
932         }
933 
934         int len = zoneStrings.length;
935         String[][] aCopy = new String[len][];
936         for (int i = 0; i < len; i++) {
937             aCopy[i] = Arrays.copyOf(zoneStrings[i], zoneStrings[i].length);
938         }
939         return aCopy;
940     }
941 
isSubclassObject()942     private boolean isSubclassObject() {
943         return !getClass().getName().equals("java.text.DateFormatSymbols");
944     }
945 
946     /**
947      * Clones all the data members from the source DateFormatSymbols to
948      * the target DateFormatSymbols.
949      *
950      * @param src the source DateFormatSymbols.
951      * @param dst the target DateFormatSymbols.
952      */
copyMembers(DateFormatSymbols src, DateFormatSymbols dst)953     private void copyMembers(DateFormatSymbols src, DateFormatSymbols dst)
954     {
955         dst.locale = src.locale;
956         dst.eras = Arrays.copyOf(src.eras, src.eras.length);
957         dst.months = Arrays.copyOf(src.months, src.months.length);
958         dst.shortMonths = Arrays.copyOf(src.shortMonths, src.shortMonths.length);
959         dst.weekdays = Arrays.copyOf(src.weekdays, src.weekdays.length);
960         dst.shortWeekdays = Arrays.copyOf(src.shortWeekdays, src.shortWeekdays.length);
961         dst.ampms = Arrays.copyOf(src.ampms, src.ampms.length);
962         if (src.zoneStrings != null) {
963             dst.zoneStrings = src.getZoneStringsImpl(true);
964         } else {
965             dst.zoneStrings = null;
966         }
967         dst.localPatternChars = src.localPatternChars;
968         dst.cachedHashCode = 0;
969 
970         // BEGIN Android-added: Support for tiny and standalone field names.
971         dst.tinyMonths = src.tinyMonths;
972         dst.tinyWeekdays = src.tinyWeekdays;
973 
974         dst.standAloneMonths = src.standAloneMonths;
975         dst.shortStandAloneMonths = src.shortStandAloneMonths;
976         dst.tinyStandAloneMonths = src.tinyStandAloneMonths;
977 
978         dst.standAloneWeekdays = src.standAloneWeekdays;
979         dst.shortStandAloneWeekdays = src.shortStandAloneWeekdays;
980         dst.tinyStandAloneWeekdays = src.tinyStandAloneWeekdays;
981         // END Android-added: Support for tiny and standalone field names.
982     }
983 
984     // BEGIN Android-added: support reading non-Android serialized DFS.
readObject(ObjectInputStream stream)985     private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
986         stream.defaultReadObject();
987 
988         if (serialVersionOnStream < 1) {
989             LocaleData localeData = LocaleData.get(locale);
990             initializeSupplementaryData(localeData);
991         }
992 
993         serialVersionOnStream = currentSerialVersion;
994     }
995     // END Android-added: support reading non-Android serialized DFS.
996 
997     /**
998      * Write out the default serializable data, after ensuring the
999      * <code>zoneStrings</code> field is initialized in order to make
1000      * sure the backward compatibility.
1001      *
1002      * @since 1.6
1003      */
writeObject(ObjectOutputStream stream)1004     private void writeObject(ObjectOutputStream stream) throws IOException {
1005         // Android-changed: extract initialization of zoneStrings to separate method.
1006         internalZoneStrings();
1007         stream.defaultWriteObject();
1008     }
1009 }
1010