1 /*
   2  * Copyright (c) 1996, 2012, 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.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  * (C) Copyright Taligent, Inc. 1996 - All Rights Reserved
  28  * (C) Copyright IBM Corp. 1996 - All Rights Reserved
  29  *
  30  *   The original version of this source code and documentation is copyrighted
  31  * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
  32  * materials are provided under terms of a License Agreement between Taligent
  33  * and Sun. This technology is protected by multiple US and International
  34  * patents. This notice and attribution to Taligent may not be removed.
  35  *   Taligent is a registered trademark of Taligent, Inc.
  36  *
  37  */
  38 
  39 package java.util;
  40 
  41 import java.io.Serializable;
  42 import java.lang.ref.SoftReference;
  43 import java.security.AccessController;
  44 import java.security.PrivilegedAction;
  45 import java.util.concurrent.ConcurrentHashMap;
  46 import sun.misc.JavaAWTAccess;
  47 import sun.misc.SharedSecrets;
  48 import sun.security.action.GetPropertyAction;
  49 import sun.util.calendar.ZoneInfo;
  50 import sun.util.calendar.ZoneInfoFile;
  51 import sun.util.locale.provider.TimeZoneNameUtility;
  52 
  53 /**
  54  * <code>TimeZone</code> represents a time zone offset, and also figures out daylight
  55  * savings.
  56  *
  57  * <p>
  58  * Typically, you get a <code>TimeZone</code> using <code>getDefault</code>
  59  * which creates a <code>TimeZone</code> based on the time zone where the program
  60  * is running. For example, for a program running in Japan, <code>getDefault</code>
  61  * creates a <code>TimeZone</code> object based on Japanese Standard Time.
  62  *
  63  * <p>
  64  * You can also get a <code>TimeZone</code> using <code>getTimeZone</code>
  65  * along with a time zone ID. For instance, the time zone ID for the
  66  * U.S. Pacific Time zone is "America/Los_Angeles". So, you can get a
  67  * U.S. Pacific Time <code>TimeZone</code> object with:
  68  * <blockquote><pre>
  69  * TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
  70  * </pre></blockquote>
  71  * You can use the <code>getAvailableIDs</code> method to iterate through
  72  * all the supported time zone IDs. You can then choose a
  73  * supported ID to get a <code>TimeZone</code>.
  74  * If the time zone you want is not represented by one of the
  75  * supported IDs, then a custom time zone ID can be specified to
  76  * produce a TimeZone. The syntax of a custom time zone ID is:
  77  *
  78  * <blockquote><pre>
  79  * <a name="CustomID"><i>CustomID:</i></a>
  80  *         <code>GMT</code> <i>Sign</i> <i>Hours</i> <code>:</code> <i>Minutes</i>
  81  *         <code>GMT</code> <i>Sign</i> <i>Hours</i> <i>Minutes</i>
  82  *         <code>GMT</code> <i>Sign</i> <i>Hours</i>
  83  * <i>Sign:</i> one of
  84  *         <code>+ -</code>
  85  * <i>Hours:</i>
  86  *         <i>Digit</i>
  87  *         <i>Digit</i> <i>Digit</i>
  88  * <i>Minutes:</i>
  89  *         <i>Digit</i> <i>Digit</i>
  90  * <i>Digit:</i> one of
  91  *         <code>0 1 2 3 4 5 6 7 8 9</code>
  92  * </pre></blockquote>
  93  *
  94  * <i>Hours</i> must be between 0 to 23 and <i>Minutes</i> must be
  95  * between 00 to 59.  For example, "GMT+10" and "GMT+0010" mean ten
  96  * hours and ten minutes ahead of GMT, respectively.
  97  * <p>
  98  * The format is locale independent and digits must be taken from the
  99  * Basic Latin block of the Unicode standard. No daylight saving time
 100  * transition schedule can be specified with a custom time zone ID. If
 101  * the specified string doesn't match the syntax, <code>"GMT"</code>
 102  * is used.
 103  * <p>
 104  * When creating a <code>TimeZone</code>, the specified custom time
 105  * zone ID is normalized in the following syntax:
 106  * <blockquote><pre>
 107  * <a name="NormalizedCustomID"><i>NormalizedCustomID:</i></a>
 108  *         <code>GMT</code> <i>Sign</i> <i>TwoDigitHours</i> <code>:</code> <i>Minutes</i>
 109  * <i>Sign:</i> one of
 110  *         <code>+ -</code>
 111  * <i>TwoDigitHours:</i>
 112  *         <i>Digit</i> <i>Digit</i>
 113  * <i>Minutes:</i>
 114  *         <i>Digit</i> <i>Digit</i>
 115  * <i>Digit:</i> one of
 116  *         <code>0 1 2 3 4 5 6 7 8 9</code>
 117  * </pre></blockquote>
 118  * For example, TimeZone.getTimeZone("GMT-8").getID() returns "GMT-08:00".
 119  *
 120  * <h4>Three-letter time zone IDs</h4>
 121  *
 122  * For compatibility with JDK 1.1.x, some other three-letter time zone IDs
 123  * (such as "PST", "CTT", "AST") are also supported. However, <strong>their
 124  * use is deprecated</strong> because the same abbreviation is often used
 125  * for multiple time zones (for example, "CST" could be U.S. "Central Standard
 126  * Time" and "China Standard Time"), and the Java platform can then only
 127  * recognize one of them.
 128  *
 129  *
 130  * @see          Calendar
 131  * @see          GregorianCalendar
 132  * @see          SimpleTimeZone
 133  * @author       Mark Davis, David Goldsmith, Chen-Lieh Huang, Alan Liu
 134  * @since        JDK1.1
 135  */
 136 abstract public class TimeZone implements Serializable, Cloneable {
 137     /**
 138      * Sole constructor.  (For invocation by subclass constructors, typically
 139      * implicit.)
 140      */
 141     public TimeZone() {
 142     }
 143 
 144     /**
 145      * A style specifier for <code>getDisplayName()</code> indicating
 146      * a short name, such as "PST."
 147      * @see #LONG
 148      * @since 1.2
 149      */
 150     public static final int SHORT = 0;
 151 
 152     /**
 153      * A style specifier for <code>getDisplayName()</code> indicating
 154      * a long name, such as "Pacific Standard Time."
 155      * @see #SHORT
 156      * @since 1.2
 157      */
 158     public static final int LONG  = 1;
 159 
 160     // Constants used internally; unit is milliseconds
 161     private static final int ONE_MINUTE = 60*1000;
 162     private static final int ONE_HOUR   = 60*ONE_MINUTE;
 163     private static final int ONE_DAY    = 24*ONE_HOUR;
 164 
 165     // Proclaim serialization compatibility with JDK 1.1
 166     static final long serialVersionUID = 3581463369166924961L;
 167 
 168     /**
 169      * Gets the time zone offset, for current date, modified in case of
 170      * daylight savings. This is the offset to add to UTC to get local time.
 171      * <p>
 172      * This method returns a historically correct offset if an
 173      * underlying <code>TimeZone</code> implementation subclass
 174      * supports historical Daylight Saving Time schedule and GMT
 175      * offset changes.
 176      *
 177      * @param era the era of the given date.
 178      * @param year the year in the given date.
 179      * @param month the month in the given date.
 180      * Month is 0-based. e.g., 0 for January.
 181      * @param day the day-in-month of the given date.
 182      * @param dayOfWeek the day-of-week of the given date.
 183      * @param milliseconds the milliseconds in day in <em>standard</em>
 184      * local time.
 185      *
 186      * @return the offset in milliseconds to add to GMT to get local time.
 187      *
 188      * @see Calendar#ZONE_OFFSET
 189      * @see Calendar#DST_OFFSET
 190      */
 191     public abstract int getOffset(int era, int year, int month, int day,
 192                                   int dayOfWeek, int milliseconds);
 193 
 194     /**
 195      * Returns the offset of this time zone from UTC at the specified
 196      * date. If Daylight Saving Time is in effect at the specified
 197      * date, the offset value is adjusted with the amount of daylight
 198      * saving.
 199      * <p>
 200      * This method returns a historically correct offset value if an
 201      * underlying TimeZone implementation subclass supports historical
 202      * Daylight Saving Time schedule and GMT offset changes.
 203      *
 204      * @param date the date represented in milliseconds since January 1, 1970 00:00:00 GMT
 205      * @return the amount of time in milliseconds to add to UTC to get local time.
 206      *
 207      * @see Calendar#ZONE_OFFSET
 208      * @see Calendar#DST_OFFSET
 209      * @since 1.4
 210      */
 211     public int getOffset(long date) {
 212         if (inDaylightTime(new Date(date))) {
 213             return getRawOffset() + getDSTSavings();
 214         }
 215         return getRawOffset();
 216     }
 217 
 218     /**
 219      * Gets the raw GMT offset and the amount of daylight saving of this
 220      * time zone at the given time.
 221      * @param date the milliseconds (since January 1, 1970,
 222      * 00:00:00.000 GMT) at which the time zone offset and daylight
 223      * saving amount are found
 224      * @param offsets an array of int where the raw GMT offset
 225      * (offset[0]) and daylight saving amount (offset[1]) are stored,
 226      * or null if those values are not needed. The method assumes that
 227      * the length of the given array is two or larger.
 228      * @return the total amount of the raw GMT offset and daylight
 229      * saving at the specified date.
 230      *
 231      * @see Calendar#ZONE_OFFSET
 232      * @see Calendar#DST_OFFSET
 233      */
 234     int getOffsets(long date, int[] offsets) {
 235         int rawoffset = getRawOffset();
 236         int dstoffset = 0;
 237         if (inDaylightTime(new Date(date))) {
 238             dstoffset = getDSTSavings();
 239         }
 240         if (offsets != null) {
 241             offsets[0] = rawoffset;
 242             offsets[1] = dstoffset;
 243         }
 244         return rawoffset + dstoffset;
 245     }
 246 
 247     /**
 248      * Sets the base time zone offset to GMT.
 249      * This is the offset to add to UTC to get local time.
 250      * <p>
 251      * If an underlying <code>TimeZone</code> implementation subclass
 252      * supports historical GMT offset changes, the specified GMT
 253      * offset is set as the latest GMT offset and the difference from
 254      * the known latest GMT offset value is used to adjust all
 255      * historical GMT offset values.
 256      *
 257      * @param offsetMillis the given base time zone offset to GMT.
 258      */
 259     abstract public void setRawOffset(int offsetMillis);
 260 
 261     /**
 262      * Returns the amount of time in milliseconds to add to UTC to get
 263      * standard time in this time zone. Because this value is not
 264      * affected by daylight saving time, it is called <I>raw
 265      * offset</I>.
 266      * <p>
 267      * If an underlying <code>TimeZone</code> implementation subclass
 268      * supports historical GMT offset changes, the method returns the
 269      * raw offset value of the current date. In Honolulu, for example,
 270      * its raw offset changed from GMT-10:30 to GMT-10:00 in 1947, and
 271      * this method always returns -36000000 milliseconds (i.e., -10
 272      * hours).
 273      *
 274      * @return the amount of raw offset time in milliseconds to add to UTC.
 275      * @see Calendar#ZONE_OFFSET
 276      */
 277     public abstract int getRawOffset();
 278 
 279     /**
 280      * Gets the ID of this time zone.
 281      * @return the ID of this time zone.
 282      */
 283     public String getID()
 284     {
 285         return ID;
 286     }
 287 
 288     /**
 289      * Sets the time zone ID. This does not change any other data in
 290      * the time zone object.
 291      * @param ID the new time zone ID.
 292      */
 293     public void setID(String ID)
 294     {
 295         if (ID == null) {
 296             throw new NullPointerException();
 297         }
 298         this.ID = ID;
 299     }
 300 
 301     /**
 302      * Returns a long standard time name of this {@code TimeZone} suitable for
 303      * presentation to the user in the default locale.
 304      *
 305      * <p>This method is equivalent to:
 306      * <pre><blockquote>
 307      * getDisplayName(false, {@link #LONG},
 308      *                Locale.getDefault({@link Locale.Category#DISPLAY}))
 309      * </blockquote></pre>
 310      *
 311      * @return the human-readable name of this time zone in the default locale.
 312      * @since 1.2
 313      * @see #getDisplayName(boolean, int, Locale)
 314      * @see Locale#getDefault(Locale.Category)
 315      * @see Locale.Category
 316      */
 317     public final String getDisplayName() {
 318         return getDisplayName(false, LONG,
 319                               Locale.getDefault(Locale.Category.DISPLAY));
 320     }
 321 
 322     /**
 323      * Returns a long standard time name of this {@code TimeZone} suitable for
 324      * presentation to the user in the specified {@code locale}.
 325      *
 326      * <p>This method is equivalent to:
 327      * <pre><blockquote>
 328      * getDisplayName(false, {@link #LONG}, locale)
 329      * </blockquote></pre>
 330      *
 331      * @param locale the locale in which to supply the display name.
 332      * @return the human-readable name of this time zone in the given locale.
 333      * @exception NullPointerException if {@code locale} is {@code null}.
 334      * @since 1.2
 335      * @see #getDisplayName(boolean, int, Locale)
 336      */
 337     public final String getDisplayName(Locale locale) {
 338         return getDisplayName(false, LONG, locale);
 339     }
 340 
 341     /**
 342      * Returns a name in the specified {@code style} of this {@code TimeZone}
 343      * suitable for presentation to the user in the default locale. If the
 344      * specified {@code daylight} is {@code true}, a Daylight Saving Time name
 345      * is returned (even if this {@code TimeZone} doesn't observe Daylight Saving
 346      * Time). Otherwise, a Standard Time name is returned.
 347      *
 348      * <p>This method is equivalent to:
 349      * <pre><blockquote>
 350      * getDisplayName(daylight, style,
 351      *                Locale.getDefault({@link Locale.Category#DISPLAY}))
 352      * </blockquote></pre>
 353      *
 354      * @param daylight {@code true} specifying a Daylight Saving Time name, or
 355      *                 {@code false} specifying a Standard Time name
 356      * @param style either {@link #LONG} or {@link #SHORT}
 357      * @return the human-readable name of this time zone in the default locale.
 358      * @exception IllegalArgumentException if {@code style} is invalid.
 359      * @since 1.2
 360      * @see #getDisplayName(boolean, int, Locale)
 361      * @see Locale#getDefault(Locale.Category)
 362      * @see Locale.Category
 363      * @see java.text.DateFormatSymbols#getZoneStrings()
 364      */
 365     public final String getDisplayName(boolean daylight, int style) {
 366         return getDisplayName(daylight, style,
 367                               Locale.getDefault(Locale.Category.DISPLAY));
 368     }
 369 
 370     /**
 371      * Returns a name in the specified {@code style} of this {@code TimeZone}
 372      * suitable for presentation to the user in the specified {@code
 373      * locale}. If the specified {@code daylight} is {@code true}, a Daylight
 374      * Saving Time name is returned (even if this {@code TimeZone} doesn't
 375      * observe Daylight Saving Time). Otherwise, a Standard Time name is
 376      * returned.
 377      *
 378      * <p>When looking up a time zone name, the {@linkplain
 379      * ResourceBundle.Control#getCandidateLocales(String,Locale) default
 380      * <code>Locale</code> search path of <code>ResourceBundle</code>} derived
 381      * from the specified {@code locale} is used. (No {@linkplain
 382      * ResourceBundle.Control#getFallbackLocale(String,Locale) fallback
 383      * <code>Locale</code>} search is performed.) If a time zone name in any
 384      * {@code Locale} of the search path, including {@link Locale#ROOT}, is
 385      * found, the name is returned. Otherwise, a string in the
 386      * <a href="#NormalizedCustomID">normalized custom ID format</a> is returned.
 387      *
 388      * @param daylight {@code true} specifying a Daylight Saving Time name, or
 389      *                 {@code false} specifying a Standard Time name
 390      * @param style either {@link #LONG} or {@link #SHORT}
 391      * @param locale   the locale in which to supply the display name.
 392      * @return the human-readable name of this time zone in the given locale.
 393      * @exception IllegalArgumentException if {@code style} is invalid.
 394      * @exception NullPointerException if {@code locale} is {@code null}.
 395      * @since 1.2
 396      * @see java.text.DateFormatSymbols#getZoneStrings()
 397      */
 398     public String getDisplayName(boolean daylight, int style, Locale locale) {
 399         if (style != SHORT && style != LONG) {
 400             throw new IllegalArgumentException("Illegal style: " + style);
 401         }
 402         String id = getID();
 403         String name = TimeZoneNameUtility.retrieveDisplayName(id, daylight, style, locale);
 404         if (name != null) {
 405             return name;
 406         }
 407 
 408         if (id.startsWith("GMT") && id.length() > 3) {
 409             char sign = id.charAt(3);
 410             if (sign == '+' || sign == '-') {
 411                 return id;
 412             }
 413         }
 414         int offset = getRawOffset();
 415         if (daylight) {
 416             offset += getDSTSavings();
 417         }
 418         return ZoneInfoFile.toCustomID(offset);
 419     }
 420 
 421     private static class DisplayNames {
 422         // Cache for managing display names per timezone per locale
 423         // The structure is:
 424         //   Map(key=id, value=SoftReference(Map(key=locale, value=displaynames)))
 425         private static final Map<String, SoftReference<Map<Locale, String[]>>> CACHE =
 426             new ConcurrentHashMap<>();
 427 
 428         private DisplayNames() {
 429         }
 430     }
 431 
 432     private static String[] getDisplayNames(String id, Locale locale) {
 433         return TimeZoneNameUtility.retrieveDisplayNames(id, locale);
 434     }
 435 
 436     /**
 437      * Returns the amount of time to be added to local standard time
 438      * to get local wall clock time.
 439      *
 440      * <p>The default implementation returns 3600000 milliseconds
 441      * (i.e., one hour) if a call to {@link #useDaylightTime()}
 442      * returns {@code true}. Otherwise, 0 (zero) is returned.
 443      *
 444      * <p>If an underlying {@code TimeZone} implementation subclass
 445      * supports historical and future Daylight Saving Time schedule
 446      * changes, this method returns the amount of saving time of the
 447      * last known Daylight Saving Time rule that can be a future
 448      * prediction.
 449      *
 450      * <p>If the amount of saving time at any given time stamp is
 451      * required, construct a {@link Calendar} with this {@code
 452      * TimeZone} and the time stamp, and call {@link Calendar#get(int)
 453      * Calendar.get}{@code (}{@link Calendar#DST_OFFSET}{@code )}.
 454      *
 455      * @return the amount of saving time in milliseconds
 456      * @since 1.4
 457      * @see #inDaylightTime(Date)
 458      * @see #getOffset(long)
 459      * @see #getOffset(int,int,int,int,int,int)
 460      * @see Calendar#ZONE_OFFSET
 461      */
 462     public int getDSTSavings() {
 463         if (useDaylightTime()) {
 464             return 3600000;
 465         }
 466         return 0;
 467     }
 468 
 469     /**
 470      * Queries if this {@code TimeZone} uses Daylight Saving Time.
 471      *
 472      * <p>If an underlying {@code TimeZone} implementation subclass
 473      * supports historical and future Daylight Saving Time schedule
 474      * changes, this method refers to the last known Daylight Saving Time
 475      * rule that can be a future prediction and may not be the same as
 476      * the current rule. Consider calling {@link #observesDaylightTime()}
 477      * if the current rule should also be taken into account.
 478      *
 479      * @return {@code true} if this {@code TimeZone} uses Daylight Saving Time,
 480      *         {@code false}, otherwise.
 481      * @see #inDaylightTime(Date)
 482      * @see Calendar#DST_OFFSET
 483      */
 484     public abstract boolean useDaylightTime();
 485 
 486     /**
 487      * Returns {@code true} if this {@code TimeZone} is currently in
 488      * Daylight Saving Time, or if a transition from Standard Time to
 489      * Daylight Saving Time occurs at any future time.
 490      *
 491      * <p>The default implementation returns {@code true} if
 492      * {@code useDaylightTime()} or {@code inDaylightTime(new Date())}
 493      * returns {@code true}.
 494      *
 495      * @return {@code true} if this {@code TimeZone} is currently in
 496      * Daylight Saving Time, or if a transition from Standard Time to
 497      * Daylight Saving Time occurs at any future time; {@code false}
 498      * otherwise.
 499      * @since 1.7
 500      * @see #useDaylightTime()
 501      * @see #inDaylightTime(Date)
 502      * @see Calendar#DST_OFFSET
 503      */
 504     public boolean observesDaylightTime() {
 505         return useDaylightTime() || inDaylightTime(new Date());
 506     }
 507 
 508     /**
 509      * Queries if the given {@code date} is in Daylight Saving Time in
 510      * this time zone.
 511      *
 512      * @param date the given Date.
 513      * @return {@code true} if the given date is in Daylight Saving Time,
 514      *         {@code false}, otherwise.
 515      */
 516     abstract public boolean inDaylightTime(Date date);
 517 
 518     /**
 519      * Gets the <code>TimeZone</code> for the given ID.
 520      *
 521      * @param ID the ID for a <code>TimeZone</code>, either an abbreviation
 522      * such as "PST", a full name such as "America/Los_Angeles", or a custom
 523      * ID such as "GMT-8:00". Note that the support of abbreviations is
 524      * for JDK 1.1.x compatibility only and full names should be used.
 525      *
 526      * @return the specified <code>TimeZone</code>, or the GMT zone if the given ID
 527      * cannot be understood.
 528      */
 529     public static synchronized TimeZone getTimeZone(String ID) {
 530         return getTimeZone(ID, true);
 531     }
 532 
 533     private static TimeZone getTimeZone(String ID, boolean fallback) {
 534         TimeZone tz = ZoneInfo.getTimeZone(ID);
 535         if (tz == null) {
 536             tz = parseCustomTimeZone(ID);
 537             if (tz == null && fallback) {
 538                 tz = new ZoneInfo(GMT_ID, 0);
 539             }
 540         }
 541         return tz;
 542     }
 543 
 544     /**
 545      * Gets the available IDs according to the given time zone offset in milliseconds.
 546      *
 547      * @param rawOffset the given time zone GMT offset in milliseconds.
 548      * @return an array of IDs, where the time zone for that ID has
 549      * the specified GMT offset. For example, "America/Phoenix" and "America/Denver"
 550      * both have GMT-07:00, but differ in daylight saving behavior.
 551      * @see #getRawOffset()
 552      */
 553     public static synchronized String[] getAvailableIDs(int rawOffset) {
 554         return ZoneInfo.getAvailableIDs(rawOffset);
 555     }
 556 
 557     /**
 558      * Gets all the available IDs supported.
 559      * @return an array of IDs.
 560      */
 561     public static synchronized String[] getAvailableIDs() {
 562         return ZoneInfo.getAvailableIDs();
 563     }
 564 
 565     /**
 566      * Gets the platform defined TimeZone ID.
 567      **/
 568     private static native String getSystemTimeZoneID(String javaHome,
 569                                                      String country);
 570 
 571     /**
 572      * Gets the custom time zone ID based on the GMT offset of the
 573      * platform. (e.g., "GMT+08:00")
 574      */
 575     private static native String getSystemGMTOffsetID();
 576 
 577     /**
 578      * Gets the default <code>TimeZone</code> for this host.
 579      * The source of the default <code>TimeZone</code>
 580      * may vary with implementation.
 581      * @return a default <code>TimeZone</code>.
 582      * @see #setDefault
 583      */
 584     public static TimeZone getDefault() {
 585         return (TimeZone) getDefaultRef().clone();
 586     }
 587 
 588     /**
 589      * Returns the reference to the default TimeZone object. This
 590      * method doesn't create a clone.
 591      */
 592     static TimeZone getDefaultRef() {
 593         TimeZone defaultZone = getDefaultInAppContext();
 594         if (defaultZone == null) {
 595             defaultZone = defaultTimeZone;
 596             if (defaultZone == null) {
 597                 // Need to initialize the default time zone.
 598                 defaultZone = setDefaultZone();
 599                 assert defaultZone != null;
 600             }
 601         }
 602         // Don't clone here.
 603         return defaultZone;
 604     }
 605 
 606     private static synchronized TimeZone setDefaultZone() {
 607         TimeZone tz;
 608         // get the time zone ID from the system properties
 609         String zoneID = AccessController.doPrivileged(
 610                 new GetPropertyAction("user.timezone"));
 611 
 612         // if the time zone ID is not set (yet), perform the
 613         // platform to Java time zone ID mapping.
 614         if (zoneID == null || zoneID.isEmpty()) {
 615             String country = AccessController.doPrivileged(
 616                     new GetPropertyAction("user.country"));
 617             String javaHome = AccessController.doPrivileged(
 618                     new GetPropertyAction("java.home"));
 619             try {
 620                 zoneID = getSystemTimeZoneID(javaHome, country);
 621                 if (zoneID == null) {
 622                     zoneID = GMT_ID;
 623                 }
 624             } catch (NullPointerException e) {
 625                 zoneID = GMT_ID;
 626             }
 627         }
 628 
 629         // Get the time zone for zoneID. But not fall back to
 630         // "GMT" here.
 631         tz = getTimeZone(zoneID, false);
 632 
 633         if (tz == null) {
 634             // If the given zone ID is unknown in Java, try to
 635             // get the GMT-offset-based time zone ID,
 636             // a.k.a. custom time zone ID (e.g., "GMT-08:00").
 637             String gmtOffsetID = getSystemGMTOffsetID();
 638             if (gmtOffsetID != null) {
 639                 zoneID = gmtOffsetID;
 640             }
 641             tz = getTimeZone(zoneID, true);
 642         }
 643         assert tz != null;
 644 
 645         final String id = zoneID;
 646         AccessController.doPrivileged(new PrivilegedAction<Void>() {
 647             @Override
 648                 public Void run() {
 649                     System.setProperty("user.timezone", id);
 650                     return null;
 651                 }
 652             });
 653 
 654         defaultTimeZone = tz;
 655         return tz;
 656     }
 657 
 658     private static boolean hasPermission() {
 659         boolean hasPermission = true;
 660         SecurityManager sm = System.getSecurityManager();
 661         if (sm != null) {
 662             try {
 663                 sm.checkPermission(new PropertyPermission
 664                                    ("user.timezone", "write"));
 665             } catch (SecurityException e) {
 666                 hasPermission = false;
 667             }
 668         }
 669         return hasPermission;
 670     }
 671 
 672     /**
 673      * Sets the <code>TimeZone</code> that is
 674      * returned by the <code>getDefault</code> method.  If <code>zone</code>
 675      * is null, reset the default to the value it had originally when the
 676      * VM first started.
 677      * @param zone the new default time zone
 678      * @see #getDefault
 679      */
 680     public static void setDefault(TimeZone zone)
 681     {
 682         if (hasPermission()) {
 683             synchronized (TimeZone.class) {
 684                 defaultTimeZone = zone;
 685                 setDefaultInAppContext(null);
 686             }
 687         } else {
 688             setDefaultInAppContext(zone);
 689         }
 690     }
 691 
 692     /**
 693      * Returns the default TimeZone in an AppContext if any AppContext
 694      * has ever used. null is returned if any AppContext hasn't been
 695      * used or if the AppContext doesn't have the default TimeZone.
 696      *
 697      * Note that javaAWTAccess may be null if sun.awt.AppContext class hasn't
 698      * been loaded. If so, it implies that AWTSecurityManager is not our
 699      * SecurityManager and we can use a local static variable.
 700      * This works around a build time issue.
 701      */
 702     private static TimeZone getDefaultInAppContext() {
 703         // JavaAWTAccess provides access implementation-private methods without using reflection.
 704         JavaAWTAccess javaAWTAccess = SharedSecrets.getJavaAWTAccess();
 705 
 706         if (javaAWTAccess == null) {
 707             return mainAppContextDefault;
 708         } else {
 709             if (!javaAWTAccess.isDisposed()) {
 710                 TimeZone tz = (TimeZone)
 711                     javaAWTAccess.get(TimeZone.class);
 712                 if (tz == null && javaAWTAccess.isMainAppContext()) {
 713                     return mainAppContextDefault;
 714                 } else {
 715                     return tz;
 716                 }
 717             }
 718         }
 719         return null;
 720     }
 721 
 722     /**
 723      * Sets the default TimeZone in the AppContext to the given
 724      * tz. null is handled special: do nothing if any AppContext
 725      * hasn't been used, remove the default TimeZone in the
 726      * AppContext otherwise.
 727      *
 728      * Note that javaAWTAccess may be null if sun.awt.AppContext class hasn't
 729      * been loaded. If so, it implies that AWTSecurityManager is not our
 730      * SecurityManager and we can use a local static variable.
 731      * This works around a build time issue.
 732      */
 733     private static void setDefaultInAppContext(TimeZone tz) {
 734         // JavaAWTAccess provides access implementation-private methods without using reflection.
 735         JavaAWTAccess javaAWTAccess = SharedSecrets.getJavaAWTAccess();
 736 
 737         if (javaAWTAccess == null) {
 738             mainAppContextDefault = tz;
 739         } else {
 740             if (!javaAWTAccess.isDisposed()) {
 741                 javaAWTAccess.put(TimeZone.class, tz);
 742                 if (javaAWTAccess.isMainAppContext()) {
 743                     mainAppContextDefault = null;
 744                 }
 745             }
 746         }
 747     }
 748 
 749     /**
 750      * Returns true if this zone has the same rule and offset as another zone.
 751      * That is, if this zone differs only in ID, if at all.  Returns false
 752      * if the other zone is null.
 753      * @param other the <code>TimeZone</code> object to be compared with
 754      * @return true if the other zone is not null and is the same as this one,
 755      * with the possible exception of the ID
 756      * @since 1.2
 757      */
 758     public boolean hasSameRules(TimeZone other) {
 759         return other != null && getRawOffset() == other.getRawOffset() &&
 760             useDaylightTime() == other.useDaylightTime();
 761     }
 762 
 763     /**
 764      * Creates a copy of this <code>TimeZone</code>.
 765      *
 766      * @return a clone of this <code>TimeZone</code>
 767      */
 768     public Object clone()
 769     {
 770         try {
 771             TimeZone other = (TimeZone) super.clone();
 772             other.ID = ID;
 773             return other;
 774         } catch (CloneNotSupportedException e) {
 775             throw new InternalError(e);
 776         }
 777     }
 778 
 779     /**
 780      * The null constant as a TimeZone.
 781      */
 782     static final TimeZone NO_TIMEZONE = null;
 783 
 784     // =======================privates===============================
 785 
 786     /**
 787      * The string identifier of this <code>TimeZone</code>.  This is a
 788      * programmatic identifier used internally to look up <code>TimeZone</code>
 789      * objects from the system table and also to map them to their localized
 790      * display names.  <code>ID</code> values are unique in the system
 791      * table but may not be for dynamically created zones.
 792      * @serial
 793      */
 794     private String           ID;
 795     private static volatile TimeZone defaultTimeZone;
 796 
 797     static final String         GMT_ID        = "GMT";
 798     private static final int    GMT_ID_LENGTH = 3;
 799 
 800     // a static TimeZone we can reference if no AppContext is in place
 801     private static volatile TimeZone mainAppContextDefault;
 802 
 803     /**
 804      * Parses a custom time zone identifier and returns a corresponding zone.
 805      * This method doesn't support the RFC 822 time zone format. (e.g., +hhmm)
 806      *
 807      * @param id a string of the <a href="#CustomID">custom ID form</a>.
 808      * @return a newly created TimeZone with the given offset and
 809      * no daylight saving time, or null if the id cannot be parsed.
 810      */
 811     private static final TimeZone parseCustomTimeZone(String id) {
 812         int length;
 813 
 814         // Error if the length of id isn't long enough or id doesn't
 815         // start with "GMT".
 816         if ((length = id.length()) < (GMT_ID_LENGTH + 2) ||
 817             id.indexOf(GMT_ID) != 0) {
 818             return null;
 819         }
 820 
 821         ZoneInfo zi;
 822 
 823         // First, we try to find it in the cache with the given
 824         // id. Even the id is not normalized, the returned ZoneInfo
 825         // should have its normalized id.
 826         zi = ZoneInfoFile.getZoneInfo(id);
 827         if (zi != null) {
 828             return zi;
 829         }
 830 
 831         int index = GMT_ID_LENGTH;
 832         boolean negative = false;
 833         char c = id.charAt(index++);
 834         if (c == '-') {
 835             negative = true;
 836         } else if (c != '+') {
 837             return null;
 838         }
 839 
 840         int hours = 0;
 841         int num = 0;
 842         int countDelim = 0;
 843         int len = 0;
 844         while (index < length) {
 845             c = id.charAt(index++);
 846             if (c == ':') {
 847                 if (countDelim > 0) {
 848                     return null;
 849                 }
 850                 if (len > 2) {
 851                     return null;
 852                 }
 853                 hours = num;
 854                 countDelim++;
 855                 num = 0;
 856                 len = 0;
 857                 continue;
 858             }
 859             if (c < '0' || c > '9') {
 860                 return null;
 861             }
 862             num = num * 10 + (c - '0');
 863             len++;
 864         }
 865         if (index != length) {
 866             return null;
 867         }
 868         if (countDelim == 0) {
 869             if (len <= 2) {
 870                 hours = num;
 871                 num = 0;
 872             } else {
 873                 hours = num / 100;
 874                 num %= 100;
 875             }
 876         } else {
 877             if (len != 2) {
 878                 return null;
 879             }
 880         }
 881         if (hours > 23 || num > 59) {
 882             return null;
 883         }
 884         int gmtOffset =  (hours * 60 + num) * 60 * 1000;
 885 
 886         if (gmtOffset == 0) {
 887             zi = ZoneInfoFile.getZoneInfo(GMT_ID);
 888             if (negative) {
 889                 zi.setID("GMT-00:00");
 890             } else {
 891                 zi.setID("GMT+00:00");
 892             }
 893         } else {
 894             zi = ZoneInfoFile.getCustomTimeZone(id, negative ? -gmtOffset : gmtOffset);
 895         }
 896         return zi;
 897     }
 898 }