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  * Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos
  28  *
  29  * All rights reserved.
  30  *
  31  * Redistribution and use in source and binary forms, with or without
  32  * modification, are permitted provided that the following conditions are met:
  33  *
  34  *  * Redistributions of source code must retain the above copyright notice,
  35  *    this list of conditions and the following disclaimer.
  36  *
  37  *  * Redistributions in binary form must reproduce the above copyright notice,
  38  *    this list of conditions and the following disclaimer in the documentation
  39  *    and/or other materials provided with the distribution.
  40  *
  41  *  * Neither the name of JSR-310 nor the names of its contributors
  42  *    may be used to endorse or promote products derived from this software
  43  *    without specific prior written permission.
  44  *
  45  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  46  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  47  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  48  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  49  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  50  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  51  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  52  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  53  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  54  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  55  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  56  */
  57 package java.time;
  58 
  59 import java.io.DataInput;
  60 import java.io.DataOutput;
  61 import java.io.IOException;
  62 import java.io.InvalidObjectException;
  63 import java.io.ObjectStreamException;
  64 import java.io.Serializable;
  65 import java.time.zone.ZoneRules;
  66 import java.time.zone.ZoneRulesException;
  67 import java.time.zone.ZoneRulesProvider;
  68 import java.util.Objects;
  69 import java.util.regex.Pattern;
  70 
  71 /**
  72  * A geographical region where the same time-zone rules apply.
  73  * <p>
  74  * Time-zone information is categorized as a set of rules defining when and
  75  * how the offset from UTC/Greenwich changes. These rules are accessed using
  76  * identifiers based on geographical regions, such as countries or states.
  77  * The most common region classification is the Time Zone Database (TZDB),
  78  * which defines regions such as 'Europe/Paris' and 'Asia/Tokyo'.
  79  * <p>
  80  * The region identifier, modeled by this class, is distinct from the
  81  * underlying rules, modeled by {@link ZoneRules}.
  82  * The rules are defined by governments and change frequently.
  83  * By contrast, the region identifier is well-defined and long-lived.
  84  * This separation also allows rules to be shared between regions if appropriate.
  85  *
  86  * <h3>Specification for implementors</h3>
  87  * This class is immutable and thread-safe.
  88  *
  89  * @since 1.8
  90  */
  91 final class ZoneRegion extends ZoneId implements Serializable {
  92 
  93     /**
  94      * Serialization version.
  95      */
  96     private static final long serialVersionUID = 8386373296231747096L;
  97     /**
  98      * The regex pattern for region IDs.
  99      */
 100     private static final Pattern PATTERN = Pattern.compile("[A-Za-z][A-Za-z0-9~/._+-]+");
 101 
 102     /**
 103      * The time-zone ID, not null.
 104      */
 105     private final String id;
 106     /**
 107      * The time-zone rules, null if zone ID was loaded leniently.
 108      */
 109     private final transient ZoneRules rules;
 110 
 111     /**
 112      * Obtains an instance of {@code ZoneRegion} from an identifier without checking
 113      * if the time-zone has available rules.
 114      * <p>
 115      * This method parses the ID and applies any appropriate normalization.
 116      * It does not validate the ID against the known set of IDsfor which rules are available.
 117      * <p>
 118      * This method is intended for advanced use cases.
 119      * For example, consider a system that always retrieves time-zone rules from a remote server.
 120      * Using this factory would allow a {@code ZoneRegion}, and thus a {@code ZonedDateTime},
 121      * to be created without loading the rules from the remote server.
 122      *
 123      * @param zoneId  the time-zone ID, not null
 124      * @return the zone ID, not null
 125      * @throws DateTimeException if the ID format is invalid
 126      */
 127     private static ZoneRegion ofLenient(String zoneId) {
 128         return ofId(zoneId, false);
 129     }
 130 
 131     /**
 132      * Obtains an instance of {@code ZoneId} from an identifier.
 133      *
 134      * @param zoneId  the time-zone ID, not null
 135      * @param checkAvailable  whether to check if the zone ID is available
 136      * @return the zone ID, not null
 137      * @throws DateTimeException if the ID format is invalid
 138      * @throws DateTimeException if checking availability and the ID cannot be found
 139      */
 140     static ZoneRegion ofId(String zoneId, boolean checkAvailable) {
 141         Objects.requireNonNull(zoneId, "zoneId");
 142         if (zoneId.length() < 2 || zoneId.startsWith("UTC") ||
 143                 zoneId.startsWith("GMT") || (PATTERN.matcher(zoneId).matches() == false)) {
 144             throw new DateTimeException("ZoneId format is not a valid region format");
 145         }
 146         ZoneRules rules = null;
 147         try {
 148             // always attempt load for better behavior after deserialization
 149             rules = ZoneRulesProvider.getRules(zoneId);
 150         } catch (ZoneRulesException ex) {
 151             if (checkAvailable) {
 152                 throw ex;
 153             }
 154         }
 155         return new ZoneRegion(zoneId, rules);
 156     }
 157 
 158     //-------------------------------------------------------------------------
 159     /**
 160      * Constructor.
 161      *
 162      * @param id  the time-zone ID, not null
 163      * @param rules  the rules, null for lazy lookup
 164      */
 165     ZoneRegion(String id, ZoneRules rules) {
 166         this.id = id;
 167         this.rules = rules;
 168     }
 169 
 170     //-----------------------------------------------------------------------
 171     @Override
 172     public String getId() {
 173         return id;
 174     }
 175 
 176     @Override
 177     public ZoneRules getRules() {
 178         // additional query for group provider when null allows for possibility
 179         // that the provider was added after the ZoneId was created
 180         return (rules != null ? rules : ZoneRulesProvider.getRules(id));
 181     }
 182 
 183     //-----------------------------------------------------------------------
 184     /**
 185      * Writes the object using a
 186      * <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>.
 187      * <pre>
 188      *  out.writeByte(7);  // identifies this as a ZoneId (not ZoneOffset)
 189      *  out.writeUTF(zoneId);
 190      * </pre>
 191      *
 192      * @return the instance of {@code Ser}, not null
 193      */
 194     private Object writeReplace() {
 195         return new Ser(Ser.ZONE_REGION_TYPE, this);
 196     }
 197 
 198     /**
 199      * Defend against malicious streams.
 200      * @return never
 201      * @throws InvalidObjectException always
 202      */
 203     private Object readResolve() throws ObjectStreamException {
 204         throw new InvalidObjectException("Deserialization via serialization delegate");
 205     }
 206 
 207     @Override
 208     void write(DataOutput out) throws IOException {
 209         out.writeByte(Ser.ZONE_REGION_TYPE);
 210         writeExternal(out);
 211     }
 212 
 213     void writeExternal(DataOutput out) throws IOException {
 214         out.writeUTF(id);
 215     }
 216 
 217     static ZoneId readExternal(DataInput in) throws IOException {
 218         String id = in.readUTF();
 219         return ofLenient(id);
 220     }
 221 
 222 }