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.temporal;
  63 
  64 import static java.time.temporal.ChronoUnit.SECONDS;
  65 
  66 import java.io.IOException;
  67 import java.io.InvalidObjectException;
  68 import java.io.ObjectInput;
  69 import java.io.ObjectOutput;
  70 import java.io.ObjectStreamException;
  71 import java.io.Serializable;
  72 import java.time.DateTimeException;
  73 import java.time.Instant;
  74 import java.time.LocalDateTime;
  75 import java.time.ZoneId;
  76 import java.time.ZoneOffset;
  77 import java.time.zone.ZoneOffsetTransition;
  78 import java.time.zone.ZoneRules;
  79 import java.util.List;
  80 import java.util.Objects;
  81 
  82 /**
  83  * A date-time with a time-zone in the calendar neutral API.
  84  * <p>
  85  * {@code ZoneChronoDateTime} is an immutable representation of a date-time with a time-zone.
  86  * This class stores all date and time fields, to a precision of nanoseconds,
  87  * as well as a time-zone and zone offset.
  88  * <p>
  89  * The purpose of storing the time-zone is to distinguish the ambiguous case where
  90  * the local time-line overlaps, typically as a result of the end of daylight time.
  91  * Information about the local-time can be obtained using methods on the time-zone.
  92  *
  93  * <h3>Specification for implementors</h3>
  94  * This class is immutable and thread-safe.
  95  *
  96  * @param <C> the chronology of this date
  97  * @since 1.8
  98  */
  99 final class ChronoZonedDateTimeImpl<C extends Chrono<C>>
 100         implements ChronoZonedDateTime<C>, Serializable {
 101 
 102     /**
 103      * Serialization version.
 104      */
 105     private static final long serialVersionUID = -5261813987200935591L;
 106 
 107     /**
 108      * The local date-time.
 109      */
 110     private final ChronoLocalDateTimeImpl<C> dateTime;
 111     /**
 112      * The zone offset.
 113      */
 114     private final ZoneOffset offset;
 115     /**
 116      * The zone ID.
 117      */
 118     private final ZoneId zone;
 119 
 120     //-----------------------------------------------------------------------
 121     /**
 122      * Obtains an instance from a local date-time using the preferred offset if possible.
 123      *
 124      * @param localDateTime  the local date-time, not null
 125      * @param zone  the zone identifier, not null
 126      * @param preferredOffset  the zone offset, null if no preference
 127      * @return the zoned date-time, not null
 128      */
 129     static <R extends Chrono<R>> ChronoZonedDateTime<R> ofBest(
 130             ChronoLocalDateTimeImpl<R> localDateTime, ZoneId zone, ZoneOffset preferredOffset) {
 131         Objects.requireNonNull(localDateTime, "localDateTime");
 132         Objects.requireNonNull(zone, "zone");
 133         if (zone instanceof ZoneOffset) {
 134             return new ChronoZonedDateTimeImpl<R>(localDateTime, (ZoneOffset) zone, zone);
 135         }
 136         ZoneRules rules = zone.getRules();
 137         LocalDateTime isoLDT = LocalDateTime.from(localDateTime);
 138         List<ZoneOffset> validOffsets = rules.getValidOffsets(isoLDT);
 139         ZoneOffset offset;
 140         if (validOffsets.size() == 1) {
 141             offset = validOffsets.get(0);
 142         } else if (validOffsets.size() == 0) {
 143             ZoneOffsetTransition trans = rules.getTransition(isoLDT);
 144             localDateTime = localDateTime.plusSeconds(trans.getDuration().getSeconds());
 145             offset = trans.getOffsetAfter();
 146         } else {
 147             if (preferredOffset != null && validOffsets.contains(preferredOffset)) {
 148                 offset = preferredOffset;
 149             } else {
 150                 offset = validOffsets.get(0);
 151             }
 152         }
 153         Objects.requireNonNull(offset, "offset");  // protect against bad ZoneRules
 154         return new ChronoZonedDateTimeImpl<R>(localDateTime, offset, zone);
 155     }
 156 
 157     /**
 158      * Obtains an instance from an instant using the specified time-zone.
 159      *
 160      * @param chrono  the chronology, not null
 161      * @param instant  the instant, not null
 162      * @param zone  the zone identifier, not null
 163      * @return the zoned date-time, not null
 164      */
 165     static <R extends Chrono<R>> ChronoZonedDateTimeImpl<R> ofInstant(Chrono<R> chrono, Instant instant, ZoneId zone) {
 166         ZoneRules rules = zone.getRules();
 167         ZoneOffset offset = rules.getOffset(instant);
 168         Objects.requireNonNull(offset, "offset");  // protect against bad ZoneRules
 169         LocalDateTime ldt = LocalDateTime.ofEpochSecond(instant.getEpochSecond(), instant.getNano(), offset);
 170         ChronoLocalDateTimeImpl<R> cldt = (ChronoLocalDateTimeImpl<R>) chrono.localDateTime(ldt);
 171         return new ChronoZonedDateTimeImpl<R>(cldt, offset, zone);
 172     }
 173 
 174     /**
 175      * Obtains an instance from an {@code Instant}.
 176      *
 177      * @param instant  the instant to create the date-time from, not null
 178      * @param zone  the time-zone to use, validated not null
 179      * @return the zoned date-time, validated not null
 180      */
 181     private ChronoZonedDateTimeImpl<C> create(Instant instant, ZoneId zone) {
 182         return ofInstant(getDate().getChrono(), instant, zone);
 183     }
 184 
 185     //-----------------------------------------------------------------------
 186     /**
 187      * Constructor.
 188      *
 189      * @param dateTime  the date-time, not null
 190      * @param offset  the zone offset, not null
 191      * @param zone  the zone ID, not null
 192      */
 193     private ChronoZonedDateTimeImpl(ChronoLocalDateTimeImpl<C> dateTime, ZoneOffset offset, ZoneId zone) {
 194         this.dateTime = Objects.requireNonNull(dateTime, "dateTime");
 195         this.offset = Objects.requireNonNull(offset, "offset");
 196         this.zone = Objects.requireNonNull(zone, "zone");
 197     }
 198 
 199     //-----------------------------------------------------------------------
 200     public ZoneOffset getOffset() {
 201         return offset;
 202     }
 203 
 204     @Override
 205     public ChronoZonedDateTime<C> withEarlierOffsetAtOverlap() {
 206         ZoneOffsetTransition trans = getZone().getRules().getTransition(LocalDateTime.from(this));
 207         if (trans != null && trans.isOverlap()) {
 208             ZoneOffset earlierOffset = trans.getOffsetBefore();
 209             if (earlierOffset.equals(offset) == false) {
 210                 return new ChronoZonedDateTimeImpl<C>(dateTime, earlierOffset, zone);
 211             }
 212         }
 213         return this;
 214     }
 215 
 216     @Override
 217     public ChronoZonedDateTime<C> withLaterOffsetAtOverlap() {
 218         ZoneOffsetTransition trans = getZone().getRules().getTransition(LocalDateTime.from(this));
 219         if (trans != null) {
 220             ZoneOffset offset = trans.getOffsetAfter();
 221             if (offset.equals(getOffset()) == false) {
 222                 return new ChronoZonedDateTimeImpl<C>(dateTime, offset, zone);
 223             }
 224         }
 225         return this;
 226     }
 227 
 228     //-----------------------------------------------------------------------
 229     @Override
 230     public ChronoLocalDateTime<C> getDateTime() {
 231         return dateTime;
 232     }
 233 
 234     public ZoneId getZone() {
 235         return zone;
 236     }
 237 
 238     public ChronoZonedDateTime<C> withZoneSameLocal(ZoneId zone) {
 239         return ofBest(dateTime, zone, offset);
 240     }
 241 
 242     @Override
 243     public ChronoZonedDateTime<C> withZoneSameInstant(ZoneId zone) {
 244         Objects.requireNonNull(zone, "zone");
 245         return this.zone.equals(zone) ? this : create(dateTime.toInstant(offset), zone);
 246     }
 247 
 248     //-----------------------------------------------------------------------
 249     @Override
 250     public boolean isSupported(TemporalField field) {
 251         return field instanceof ChronoField || (field != null && field.doIsSupported(this));
 252     }
 253 
 254     //-----------------------------------------------------------------------
 255     @Override
 256     public ChronoZonedDateTime<C> with(TemporalField field, long newValue) {
 257         if (field instanceof ChronoField) {
 258             ChronoField f = (ChronoField) field;
 259             switch (f) {
 260                 case INSTANT_SECONDS: return plus(newValue - toEpochSecond(), SECONDS);
 261                 case OFFSET_SECONDS: {
 262                     ZoneOffset offset = ZoneOffset.ofTotalSeconds(f.checkValidIntValue(newValue));
 263                     return create(dateTime.toInstant(offset), zone);
 264                 }
 265             }
 266             return ofBest(dateTime.with(field, newValue), zone, offset);
 267         }
 268         return getDate().getChrono().ensureChronoZonedDateTime(field.doWith(this, newValue));
 269     }
 270 
 271     //-----------------------------------------------------------------------
 272     @Override
 273     public ChronoZonedDateTime<C> plus(long amountToAdd, TemporalUnit unit) {
 274         if (unit instanceof ChronoUnit) {
 275             return with(dateTime.plus(amountToAdd, unit));
 276         }
 277         return getDate().getChrono().ensureChronoZonedDateTime(unit.doPlus(this, amountToAdd));   /// TODO: Generics replacement Risk!
 278     }
 279 
 280     //-----------------------------------------------------------------------
 281     @Override
 282     public long periodUntil(Temporal endDateTime, TemporalUnit unit) {
 283         if (endDateTime instanceof ChronoZonedDateTime == false) {
 284             throw new DateTimeException("Unable to calculate period between objects of two different types");
 285         }
 286         @SuppressWarnings("unchecked")
 287         ChronoZonedDateTime<C> end = (ChronoZonedDateTime<C>) endDateTime;
 288         if (getDate().getChrono().equals(end.getDate().getChrono()) == false) {
 289             throw new DateTimeException("Unable to calculate period between two different chronologies");
 290         }
 291         if (unit instanceof ChronoUnit) {
 292             end = end.withZoneSameInstant(offset);
 293             return dateTime.periodUntil(end.getDateTime(), unit);
 294         }
 295         return unit.between(this, endDateTime).getAmount();
 296     }
 297 
 298     //-----------------------------------------------------------------------
 299     private Object writeReplace() {
 300         return new Ser(Ser.CHRONO_ZONE_DATE_TIME_TYPE, this);
 301     }
 302 
 303     /**
 304      * Defend against malicious streams.
 305      * @return never
 306      * @throws InvalidObjectException always
 307      */
 308     private Object readResolve() throws ObjectStreamException {
 309         throw new InvalidObjectException("Deserialization via serialization delegate");
 310     }
 311 
 312     void writeExternal(ObjectOutput out) throws IOException {
 313         out.writeObject(dateTime);
 314         out.writeObject(offset);
 315         out.writeObject(zone);
 316     }
 317 
 318     static ChronoZonedDateTime<?> readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
 319         ChronoLocalDateTime<?> dateTime = (ChronoLocalDateTime<?>) in.readObject();
 320         ZoneOffset offset = (ZoneOffset) in.readObject();
 321         ZoneId zone = (ZoneId) in.readObject();
 322         return dateTime.atZone(offset).withZoneSameLocal(zone);
 323         // TODO: ZDT uses ofLenient()
 324     }
 325 
 326     //-------------------------------------------------------------------------
 327     @Override
 328     public boolean equals(Object obj) {
 329         if (this == obj) {
 330             return true;
 331         }
 332         if (obj instanceof ChronoZonedDateTime) {
 333             return compareTo((ChronoZonedDateTime<?>) obj) == 0;
 334         }
 335         return false;
 336     }
 337 
 338     @Override
 339     public int hashCode() {
 340         return getDateTime().hashCode() ^ getOffset().hashCode() ^ Integer.rotateLeft(getZone().hashCode(), 3);
 341     }
 342 
 343     @Override
 344     public String toString() {
 345         String str = getDateTime().toString() + getOffset().toString();
 346         if (getOffset() != getZone()) {
 347             str += '[' + getZone().toString() + ']';
 348         }
 349         return str;
 350     }
 351 
 352 
 353 }