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