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