1 /*
   2  * Copyright (c) 2012, 2013, 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  * This file is available under and governed by the GNU General Public
  28  * License version 2 only, as published by the Free Software Foundation.
  29  * However, the following notice accompanied the original version of this
  30  * file:
  31  *
  32  * Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos
  33  *
  34  * All rights reserved.
  35  *
  36  * Redistribution and use in source and binary forms, with or without
  37  * modification, are permitted provided that the following conditions are met:
  38  *
  39  *  * Redistributions of source code must retain the above copyright notice,
  40  *    this list of conditions and the following disclaimer.
  41  *
  42  *  * Redistributions in binary form must reproduce the above copyright notice,
  43  *    this list of conditions and the following disclaimer in the documentation
  44  *    and/or other materials provided with the distribution.
  45  *
  46  *  * Neither the name of JSR-310 nor the names of its contributors
  47  *    may be used to endorse or promote products derived from this software
  48  *    without specific prior written permission.
  49  *
  50  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  51  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  52  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  53  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  54  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  55  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  56  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  57  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  58  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  59  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  60  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  61  */
  62 package java.time;
  63 
  64 import java.io.DataOutput;
  65 import java.io.IOException;
  66 import java.io.Serializable;
  67 import java.time.format.DateTimeFormatterBuilder;
  68 import java.time.format.TextStyle;
  69 import java.time.temporal.Queries;
  70 import java.time.temporal.TemporalAccessor;
  71 import java.time.temporal.TemporalField;
  72 import java.time.temporal.TemporalQuery;
  73 import java.time.zone.ZoneRules;
  74 import java.time.zone.ZoneRulesProvider;
  75 import java.util.Collections;
  76 import java.util.HashMap;
  77 import java.util.Locale;
  78 import java.util.Map;
  79 import java.util.Objects;
  80 import java.util.TimeZone;
  81 
  82 /**
  83  * A time-zone ID, such as {@code Europe/Paris}.
  84  * <p>
  85  * A {@code ZoneId} is used to identify the rules used to convert between
  86  * an {@link Instant} and a {@link LocalDateTime}.
  87  * There are two distinct types of ID:
  88  * <p><ul>
  89  * <li>Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses
  90  *  the same offset for all local date-times
  91  * <li>Geographical regions - an area where a specific set of rules for finding
  92  *  the offset from UTC/Greenwich apply
  93  * </ul><p>
  94  * Most fixed offsets are represented by {@link ZoneOffset}.
  95  * <p>
  96  * The actual rules, describing when and how the offset changes, are defined by {@link ZoneRules}.
  97  * This class is simply an ID used to obtain the underlying rules.
  98  * This approach is taken because rules are defined by governments and change
  99  * frequently, whereas the ID is stable.
 100  * <p>
 101  * The distinction has other effects. Serializing the {@code ZoneId} will only send
 102  * the ID, whereas serializing the rules sends the entire data set.
 103  * Similarly, a comparison of two IDs only examines the ID, whereas
 104  * a comparison of two rules examines the entire data set.
 105  * <p>
 106  * The code supports loading a {@code ZoneId} on a JVM which does not have available rules
 107  * for that ID. This allows the date-time object, such as {@link ZonedDateTime},
 108  * to still be queried.
 109  *
 110  * <h3>Time-zone IDs</h3>
 111  * The ID is unique within the system.
 112  * The formats for offset and region IDs differ.
 113  * <p>
 114  * An ID is parsed as an offset ID if it starts with 'UTC', 'GMT', '+' or '-', or
 115  * is a single letter.
 116  * For example, 'Z', '+02:00', '-05:00', 'UTC+05' and 'GMT-6' are all valid offset IDs.
 117  * Note that some IDs, such as 'D' or '+ABC' meet the criteria, but are invalid.
 118  * <p>
 119  * All other IDs are considered to be region IDs.
 120  * <p>
 121  * Region IDs are defined by configuration, which can be thought of as a {@code Map}
 122  * from region ID to {@code ZoneRules}, see {@link ZoneRulesProvider}.
 123  * <p>
 124  * Time-zones are defined by governments and change frequently. There are a number of
 125  * organizations, known here as groups, that monitor time-zone changes and collate them.
 126  * The default group is the IANA Time Zone Database (TZDB).
 127  * Other organizations include IATA (the airline industry body) and Microsoft.
 128  * <p>
 129  * Each group defines its own format for region ID.
 130  * The TZDB group defines IDs such as 'Europe/London' or 'America/New_York'.
 131  * TZDB IDs take precedence over other groups.
 132  * <p>
 133  * It is strongly recommended that the group name is included in all Ids supplied by
 134  * groups other than TZDB to avoid conflicts. For example, IATA airline time-zone
 135  * region IDs are typically the same as the three letter airport code.
 136  * However, the airport of Utrecht has the code 'UTC', which is obviously a conflict.
 137  * The recommended format for region IDs from groups other than TZDB is 'group~region'.
 138  * Thus if IATA data were defined, Utrecht airport would be 'IATA~UTC'.
 139  *
 140  * <h3>Specification for implementors</h3>
 141  * This abstract class has two implementations, both of which are immutable and thread-safe.
 142  * One implementation models region-based IDs, the other is {@code ZoneOffset} modelling
 143  * offset-based IDs.
 144  *
 145  * @since 1.8
 146  */
 147 public abstract class ZoneId implements Serializable {
 148 
 149     /**
 150      * A map of zone overrides to enable the older US time-zone names to be used.
 151      * <p>
 152      * This maps as follows:
 153      * <p><ul>
 154      * <li>EST - America/Indianapolis</li>
 155      * <li>MST - America/Phoenix</li>
 156      * <li>HST - Pacific/Honolulu</li>
 157      * <li>ACT - Australia/Darwin</li>
 158      * <li>AET - Australia/Sydney</li>
 159      * <li>AGT - America/Argentina/Buenos_Aires</li>
 160      * <li>ART - Africa/Cairo</li>
 161      * <li>AST - America/Anchorage</li>
 162      * <li>BET - America/Sao_Paulo</li>
 163      * <li>BST - Asia/Dhaka</li>
 164      * <li>CAT - Africa/Harare</li>
 165      * <li>CNT - America/St_Johns</li>
 166      * <li>CST - America/Chicago</li>
 167      * <li>CTT - Asia/Shanghai</li>
 168      * <li>EAT - Africa/Addis_Ababa</li>
 169      * <li>ECT - Europe/Paris</li>
 170      * <li>IET - America/Indiana/Indianapolis</li>
 171      * <li>IST - Asia/Kolkata</li>
 172      * <li>JST - Asia/Tokyo</li>
 173      * <li>MIT - Pacific/Apia</li>
 174      * <li>NET - Asia/Yerevan</li>
 175      * <li>NST - Pacific/Auckland</li>
 176      * <li>PLT - Asia/Karachi</li>
 177      * <li>PNT - America/Phoenix</li>
 178      * <li>PRT - America/Puerto_Rico</li>
 179      * <li>PST - America/Los_Angeles</li>
 180      * <li>SST - Pacific/Guadalcanal</li>
 181      * <li>VST - Asia/Ho_Chi_Minh</li>
 182      * </ul><p>
 183      * The map is unmodifiable.
 184      */
 185     public static final Map<String, String> OLD_IDS_PRE_2005;
 186     /**
 187      * A map of zone overrides to enable the older US time-zone names to be used.
 188      * <p>
 189      * This maps as follows:
 190      * <p><ul>
 191      * <li>EST - -05:00</li>
 192      * <li>HST - -10:00</li>
 193      * <li>MST - -07:00</li>
 194      * <li>ACT - Australia/Darwin</li>
 195      * <li>AET - Australia/Sydney</li>
 196      * <li>AGT - America/Argentina/Buenos_Aires</li>
 197      * <li>ART - Africa/Cairo</li>
 198      * <li>AST - America/Anchorage</li>
 199      * <li>BET - America/Sao_Paulo</li>
 200      * <li>BST - Asia/Dhaka</li>
 201      * <li>CAT - Africa/Harare</li>
 202      * <li>CNT - America/St_Johns</li>
 203      * <li>CST - America/Chicago</li>
 204      * <li>CTT - Asia/Shanghai</li>
 205      * <li>EAT - Africa/Addis_Ababa</li>
 206      * <li>ECT - Europe/Paris</li>
 207      * <li>IET - America/Indiana/Indianapolis</li>
 208      * <li>IST - Asia/Kolkata</li>
 209      * <li>JST - Asia/Tokyo</li>
 210      * <li>MIT - Pacific/Apia</li>
 211      * <li>NET - Asia/Yerevan</li>
 212      * <li>NST - Pacific/Auckland</li>
 213      * <li>PLT - Asia/Karachi</li>
 214      * <li>PNT - America/Phoenix</li>
 215      * <li>PRT - America/Puerto_Rico</li>
 216      * <li>PST - America/Los_Angeles</li>
 217      * <li>SST - Pacific/Guadalcanal</li>
 218      * <li>VST - Asia/Ho_Chi_Minh</li>
 219      * </ul><p>
 220      * The map is unmodifiable.
 221      */
 222     public static final Map<String, String> OLD_IDS_POST_2005;
 223     static {
 224         Map<String, String> base = new HashMap<>();
 225         base.put("ACT", "Australia/Darwin");
 226         base.put("AET", "Australia/Sydney");
 227         base.put("AGT", "America/Argentina/Buenos_Aires");
 228         base.put("ART", "Africa/Cairo");
 229         base.put("AST", "America/Anchorage");
 230         base.put("BET", "America/Sao_Paulo");
 231         base.put("BST", "Asia/Dhaka");
 232         base.put("CAT", "Africa/Harare");
 233         base.put("CNT", "America/St_Johns");
 234         base.put("CST", "America/Chicago");
 235         base.put("CTT", "Asia/Shanghai");
 236         base.put("EAT", "Africa/Addis_Ababa");
 237         base.put("ECT", "Europe/Paris");
 238         base.put("IET", "America/Indiana/Indianapolis");
 239         base.put("IST", "Asia/Kolkata");
 240         base.put("JST", "Asia/Tokyo");
 241         base.put("MIT", "Pacific/Apia");
 242         base.put("NET", "Asia/Yerevan");
 243         base.put("NST", "Pacific/Auckland");
 244         base.put("PLT", "Asia/Karachi");
 245         base.put("PNT", "America/Phoenix");
 246         base.put("PRT", "America/Puerto_Rico");
 247         base.put("PST", "America/Los_Angeles");
 248         base.put("SST", "Pacific/Guadalcanal");
 249         base.put("VST", "Asia/Ho_Chi_Minh");
 250         Map<String, String> pre = new HashMap<>(base);
 251         pre.put("EST", "America/Indianapolis");
 252         pre.put("MST", "America/Phoenix");
 253         pre.put("HST", "Pacific/Honolulu");
 254         OLD_IDS_PRE_2005 = Collections.unmodifiableMap(pre);
 255         Map<String, String> post = new HashMap<>(base);
 256         post.put("EST", "-05:00");
 257         post.put("MST", "-07:00");
 258         post.put("HST", "-10:00");
 259         OLD_IDS_POST_2005 = Collections.unmodifiableMap(post);
 260     }
 261     /**
 262      * Serialization version.
 263      */
 264     private static final long serialVersionUID = 8352817235686L;
 265 
 266     //-----------------------------------------------------------------------
 267     /**
 268      * Gets the system default time-zone.
 269      * <p>
 270      * This queries {@link TimeZone#getDefault()} to find the default time-zone
 271      * and converts it to a {@code ZoneId}. If the system default time-zone is changed,
 272      * then the result of this method will also change.
 273      *
 274      * @return the zone ID, not null
 275      * @throws DateTimeException if the converted zone ID has an invalid format
 276      * @throws java.time.zone.ZoneRulesException if the converted zone region ID cannot be found
 277      */
 278     public static ZoneId systemDefault() {
 279         return ZoneId.of(TimeZone.getDefault().getID(), OLD_IDS_POST_2005);
 280     }
 281 
 282     //-----------------------------------------------------------------------
 283     /**
 284      * Obtains an instance of {@code ZoneId} using its ID using a map
 285      * of aliases to supplement the standard zone IDs.
 286      * <p>
 287      * Many users of time-zones use short abbreviations, such as PST for
 288      * 'Pacific Standard Time' and PDT for 'Pacific Daylight Time'.
 289      * These abbreviations are not unique, and so cannot be used as IDs.
 290      * This method allows a map of string to time-zone to be setup and reused
 291      * within an application.
 292      *
 293      * @param zoneId  the time-zone ID, not null
 294      * @param aliasMap  a map of alias zone IDs (typically abbreviations) to real zone IDs, not null
 295      * @return the zone ID, not null
 296      * @throws DateTimeException if the zone ID has an invalid format
 297      * @throws java.time.zone.ZoneRulesException if the zone region ID cannot be found
 298      */
 299     public static ZoneId of(String zoneId, Map<String, String> aliasMap) {
 300         Objects.requireNonNull(zoneId, "zoneId");
 301         Objects.requireNonNull(aliasMap, "aliasMap");
 302         String id = aliasMap.get(zoneId);
 303         id = (id != null ? id : zoneId);
 304         return of(id);
 305     }
 306 
 307     /**
 308      * Obtains an instance of {@code ZoneId} from an ID ensuring that the
 309      * ID is valid and available for use.
 310      * <p>
 311      * This method parses the ID, applies any appropriate normalization, and validates it
 312      * against the known set of IDs for which rules are available.
 313      * <p>
 314      * An ID is parsed as though it is an offset ID if it starts with 'UTC', 'GMT', '+'
 315      * or '-', or if it has less then two letters.
 316      * The offset of {@link ZoneOffset#UTC zero} may be represented in multiple ways,
 317      * including 'Z', 'UTC', 'GMT', 'UTC0' 'GMT0', '+00:00', '-00:00' and 'UTC+00:00'.
 318      * <p>
 319      * Eight forms of ID are recognized, where '{offset}' means to parse using {@link ZoneOffset#of(String)}:
 320      * <p><ul>
 321      * <li><code>{offset}</code> - a {@link ZoneOffset} ID, such as 'Z' or '+02:00'
 322      * <li><code>UTC</code> - alternate form of a {@code ZoneOffset} ID equal to 'Z'
 323      * <li><code>UTC0</code> - alternate form of a {@code ZoneOffset} ID equal to 'Z'
 324      * <li><code>UTC{offset}</code> - alternate form of a {@code ZoneOffset} ID equal to '{offset}'
 325      * <li><code>GMT</code> - alternate form of a {@code ZoneOffset} ID equal to 'Z'
 326      * <li><code>GMT0</code> - alternate form of a {@code ZoneOffset} ID equal to 'Z'
 327      * <li><code>GMT{offset}</code> - alternate form of a {@code ZoneOffset} ID equal to '{offset}'r
 328      * <li><code>{regionID}</code> - full region ID, loaded from configuration
 329      * </ul><p>
 330      * Region IDs must match the regular expression <code>[A-Za-z][A-Za-z0-9~/._+-]+</code>.
 331      * <p>
 332      * The detailed format of the region ID depends on the group supplying the data.
 333      * The default set of data is supplied by the IANA Time Zone Database (TZDB)
 334      * This has region IDs of the form '{area}/{city}', such as 'Europe/Paris' or 'America/New_York'.
 335      * This is compatible with most IDs from {@link java.util.TimeZone}.
 336      *
 337      * @param zoneId  the time-zone ID, not null
 338      * @return the zone ID, not null
 339      * @throws DateTimeException if the zone ID has an invalid format
 340      * @throws java.time.zone.ZoneRulesException if the zone region ID cannot be found
 341      */
 342     public static ZoneId of(String zoneId) {
 343         Objects.requireNonNull(zoneId, "zoneId");
 344         if (zoneId.length() <= 1 || zoneId.startsWith("+") || zoneId.startsWith("-")) {
 345             return ZoneOffset.of(zoneId);
 346         } else if (zoneId.startsWith("UTC") || zoneId.startsWith("GMT")) {
 347             if (zoneId.length() == 3 || (zoneId.length() == 4 && zoneId.charAt(3) == '0')) {
 348                 return ZoneOffset.UTC;
 349             }
 350             return ZoneOffset.of(zoneId.substring(3));
 351         }
 352         return ZoneRegion.ofId(zoneId, true);
 353     }
 354 
 355     //-----------------------------------------------------------------------
 356     /**
 357      * Obtains an instance of {@code ZoneId} from a temporal object.
 358      * <p>
 359      * A {@code TemporalAccessor} represents some form of date and time information.
 360      * This factory converts the arbitrary temporal object to an instance of {@code ZoneId}.
 361      * <p>
 362      * The conversion will try to obtain the zone in a way that favours region-based
 363      * zones over offset-based zones using {@link Queries#zone()}.
 364      * <p>
 365      * This method matches the signature of the functional interface {@link TemporalQuery}
 366      * allowing it to be used in queries via method reference, {@code ZoneId::from}.
 367      *
 368      * @param temporal  the temporal object to convert, not null
 369      * @return the zone ID, not null
 370      * @throws DateTimeException if unable to convert to a {@code ZoneId}
 371      */
 372     public static ZoneId from(TemporalAccessor temporal) {
 373         ZoneId obj = temporal.query(Queries.zone());
 374         if (obj == null) {
 375             throw new DateTimeException("Unable to obtain ZoneId from TemporalAccessor: " + temporal.getClass());
 376         }
 377         return obj;
 378     }
 379 
 380     //-----------------------------------------------------------------------
 381     /**
 382      * Constructor only accessible within the package.
 383      */
 384     ZoneId() {
 385         if (getClass() != ZoneOffset.class && getClass() != ZoneRegion.class) {
 386             throw new AssertionError("Invalid subclass");
 387         }
 388     }
 389 
 390     //-----------------------------------------------------------------------
 391     /**
 392      * Gets the unique time-zone ID.
 393      * <p>
 394      * This ID uniquely defines this object.
 395      * The format of an offset based ID is defined by {@link ZoneOffset#getId()}.
 396      *
 397      * @return the time-zone unique ID, not null
 398      */
 399     public abstract String getId();
 400 
 401     //-----------------------------------------------------------------------
 402     /**
 403      * Gets the time-zone rules for this ID allowing calculations to be performed.
 404      * <p>
 405      * The rules provide the functionality associated with a time-zone,
 406      * such as finding the offset for a given instant or local date-time.
 407      * <p>
 408      * A time-zone can be invalid if it is deserialized in a JVM which does not
 409      * have the same rules loaded as the JVM that stored it. In this case, calling
 410      * this method will throw an exception.
 411      * <p>
 412      * The rules are supplied by {@link ZoneRulesProvider}. An advanced provider may
 413      * support dynamic updates to the rules without restarting the JVM.
 414      * If so, then the result of this method may change over time.
 415      * Each individual call will be still remain thread-safe.
 416      * <p>
 417      * {@link ZoneOffset} will always return a set of rules where the offset never changes.
 418      *
 419      * @return the rules, not null
 420      * @throws DateTimeException if no rules are available for this ID
 421      */
 422     public abstract ZoneRules getRules();
 423 
 424     //-----------------------------------------------------------------------
 425     /**
 426      * Gets the textual representation of the zone, such as 'British Time' or
 427      * '+02:00'.
 428      * <p>
 429      * This returns a textual description for the time-zone ID.
 430      * <p>
 431      * If no textual mapping is found then the {@link #getId() full ID} is returned.
 432      *
 433      * @param style  the length of the text required, not null
 434      * @param locale  the locale to use, not null
 435      * @return the text value of the zone, not null
 436      */
 437     public String getText(TextStyle style, Locale locale) {
 438         return new DateTimeFormatterBuilder().appendZoneText(style).toFormatter(locale).print(new TemporalAccessor() {
 439             @Override
 440             public boolean isSupported(TemporalField field) {
 441                 return false;
 442             }
 443             @Override
 444             public long getLong(TemporalField field) {
 445                 throw new DateTimeException("Unsupported field: " + field);
 446             }
 447             @SuppressWarnings("unchecked")
 448             @Override
 449             public <R> R query(TemporalQuery<R> query) {
 450                 if (query == Queries.zoneId()) {
 451                     return (R) ZoneId.this;
 452                 }
 453                 return TemporalAccessor.super.query(query);
 454             }
 455         });
 456     }
 457 
 458     //-----------------------------------------------------------------------
 459     /**
 460      * Checks if this time-zone ID is equal to another time-zone ID.
 461      * <p>
 462      * The comparison is based on the ID.
 463      *
 464      * @param obj  the object to check, null returns false
 465      * @return true if this is equal to the other time-zone ID
 466      */
 467     @Override
 468     public boolean equals(Object obj) {
 469         if (this == obj) {
 470            return true;
 471         }
 472         if (obj instanceof ZoneId) {
 473             ZoneId other = (ZoneId) obj;
 474             return getId().equals(other.getId());
 475         }
 476         return false;
 477     }
 478 
 479     /**
 480      * A hash code for this time-zone ID.
 481      *
 482      * @return a suitable hash code
 483      */
 484     @Override
 485     public int hashCode() {
 486         return getId().hashCode();
 487     }
 488 
 489     //-----------------------------------------------------------------------
 490     /**
 491      * Outputs this zone as a {@code String}, using the ID.
 492      *
 493      * @return a string representation of this time-zone ID, not null
 494      */
 495     @Override
 496     public String toString() {
 497         return getId();
 498     }
 499 
 500     //-----------------------------------------------------------------------
 501     /**
 502      * Writes the object using a
 503      * <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>.
 504      * <pre>
 505      *  out.writeByte(7);  // identifies this as a ZoneId (not ZoneOffset)
 506      *  out.writeUTF(zoneId);
 507      * </pre>
 508      *
 509      * @return the instance of {@code Ser}, not null
 510      */
 511     // this is here for serialization Javadoc
 512     private Object writeReplace() {
 513         return new Ser(Ser.ZONE_REGION_TYPE, this);
 514     }
 515 
 516     abstract void write(DataOutput out) throws IOException;
 517 
 518 }