1 /*
2  * Copyright (c) 2012, 2015, 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) 2009-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.zone;
63 
64 import java.io.DataInput;
65 import java.io.DataOutput;
66 import java.io.IOException;
67 import java.io.InvalidObjectException;
68 import java.io.ObjectInputStream;
69 import java.io.Serializable;
70 import java.time.Duration;
71 import java.time.Instant;
72 import java.time.LocalDateTime;
73 import java.time.ZoneOffset;
74 import java.util.Arrays;
75 import java.util.Collections;
76 import java.util.List;
77 import java.util.Objects;
78 
79 /**
80  * A transition between two offsets caused by a discontinuity in the local time-line.
81  * <p>
82  * A transition between two offsets is normally the result of a daylight savings cutover.
83  * The discontinuity is normally a gap in spring and an overlap in autumn.
84  * {@code ZoneOffsetTransition} models the transition between the two offsets.
85  * <p>
86  * Gaps occur where there are local date-times that simply do not exist.
87  * An example would be when the offset changes from {@code +03:00} to {@code +04:00}.
88  * This might be described as 'the clocks will move forward one hour tonight at 1am'.
89  * <p>
90  * Overlaps occur where there are local date-times that exist twice.
91  * An example would be when the offset changes from {@code +04:00} to {@code +03:00}.
92  * This might be described as 'the clocks will move back one hour tonight at 2am'.
93  *
94  * @implSpec
95  * This class is immutable and thread-safe.
96  *
97  * @since 1.8
98  */
99 public final class ZoneOffsetTransition
100         implements Comparable<ZoneOffsetTransition>, Serializable {
101 
102     /**
103      * Serialization version.
104      */
105     private static final long serialVersionUID = -6946044323557704546L;
106     /**
107      * The local transition date-time at the transition.
108      */
109     private final LocalDateTime transition;
110     /**
111      * The offset before transition.
112      */
113     private final ZoneOffset offsetBefore;
114     /**
115      * The offset after transition.
116      */
117     private final ZoneOffset offsetAfter;
118 
119     //-----------------------------------------------------------------------
120     /**
121      * Obtains an instance defining a transition between two offsets.
122      * <p>
123      * Applications should normally obtain an instance from {@link ZoneRules}.
124      * This factory is only intended for use when creating {@link ZoneRules}.
125      *
126      * @param transition  the transition date-time at the transition, which never
127      *  actually occurs, expressed local to the before offset, not null
128      * @param offsetBefore  the offset before the transition, not null
129      * @param offsetAfter  the offset at and after the transition, not null
130      * @return the transition, not null
131      * @throws IllegalArgumentException if {@code offsetBefore} and {@code offsetAfter}
132      *         are equal, or {@code transition.getNano()} returns non-zero value
133      */
of(LocalDateTime transition, ZoneOffset offsetBefore, ZoneOffset offsetAfter)134     public static ZoneOffsetTransition of(LocalDateTime transition, ZoneOffset offsetBefore, ZoneOffset offsetAfter) {
135         Objects.requireNonNull(transition, "transition");
136         Objects.requireNonNull(offsetBefore, "offsetBefore");
137         Objects.requireNonNull(offsetAfter, "offsetAfter");
138         if (offsetBefore.equals(offsetAfter)) {
139             throw new IllegalArgumentException("Offsets must not be equal");
140         }
141         if (transition.getNano() != 0) {
142             throw new IllegalArgumentException("Nano-of-second must be zero");
143         }
144         return new ZoneOffsetTransition(transition, offsetBefore, offsetAfter);
145     }
146 
147     /**
148      * Creates an instance defining a transition between two offsets.
149      *
150      * @param transition  the transition date-time with the offset before the transition, not null
151      * @param offsetBefore  the offset before the transition, not null
152      * @param offsetAfter  the offset at and after the transition, not null
153      */
ZoneOffsetTransition(LocalDateTime transition, ZoneOffset offsetBefore, ZoneOffset offsetAfter)154     ZoneOffsetTransition(LocalDateTime transition, ZoneOffset offsetBefore, ZoneOffset offsetAfter) {
155         this.transition = transition;
156         this.offsetBefore = offsetBefore;
157         this.offsetAfter = offsetAfter;
158     }
159 
160     /**
161      * Creates an instance from epoch-second and offsets.
162      *
163      * @param epochSecond  the transition epoch-second
164      * @param offsetBefore  the offset before the transition, not null
165      * @param offsetAfter  the offset at and after the transition, not null
166      */
ZoneOffsetTransition(long epochSecond, ZoneOffset offsetBefore, ZoneOffset offsetAfter)167     ZoneOffsetTransition(long epochSecond, ZoneOffset offsetBefore, ZoneOffset offsetAfter) {
168         this.transition = LocalDateTime.ofEpochSecond(epochSecond, 0, offsetBefore);
169         this.offsetBefore = offsetBefore;
170         this.offsetAfter = offsetAfter;
171     }
172 
173     //-----------------------------------------------------------------------
174     /**
175      * Defend against malicious streams.
176      *
177      * @param s the stream to read
178      * @throws InvalidObjectException always
179      */
readObject(ObjectInputStream s)180     private void readObject(ObjectInputStream s) throws InvalidObjectException {
181         throw new InvalidObjectException("Deserialization via serialization delegate");
182     }
183 
184     /**
185      * Writes the object using a
186      * <a href="../../../serialized-form.html#java.time.zone.Ser">dedicated serialized form</a>.
187      * @serialData
188      * Refer to the serialized form of
189      * <a href="../../../serialized-form.html#java.time.zone.ZoneRules">ZoneRules.writeReplace</a>
190      * for the encoding of epoch seconds and offsets.
191      * <pre style="font-size:1.0em">{@code
192      *
193      *   out.writeByte(2);                // identifies a ZoneOffsetTransition
194      *   out.writeEpochSec(toEpochSecond);
195      *   out.writeOffset(offsetBefore);
196      *   out.writeOffset(offsetAfter);
197      * }
198      * </pre>
199      * @return the replacing object, not null
200      */
writeReplace()201     private Object writeReplace() {
202         return new Ser(Ser.ZOT, this);
203     }
204 
205     /**
206      * Writes the state to the stream.
207      *
208      * @param out  the output stream, not null
209      * @throws IOException if an error occurs
210      */
writeExternal(DataOutput out)211     void writeExternal(DataOutput out) throws IOException {
212         Ser.writeEpochSec(toEpochSecond(), out);
213         Ser.writeOffset(offsetBefore, out);
214         Ser.writeOffset(offsetAfter, out);
215     }
216 
217     /**
218      * Reads the state from the stream.
219      *
220      * @param in  the input stream, not null
221      * @return the created object, not null
222      * @throws IOException if an error occurs
223      */
readExternal(DataInput in)224     static ZoneOffsetTransition readExternal(DataInput in) throws IOException {
225         long epochSecond = Ser.readEpochSec(in);
226         ZoneOffset before = Ser.readOffset(in);
227         ZoneOffset after = Ser.readOffset(in);
228         if (before.equals(after)) {
229             throw new IllegalArgumentException("Offsets must not be equal");
230         }
231         return new ZoneOffsetTransition(epochSecond, before, after);
232     }
233 
234     //-----------------------------------------------------------------------
235     /**
236      * Gets the transition instant.
237      * <p>
238      * This is the instant of the discontinuity, which is defined as the first
239      * instant that the 'after' offset applies.
240      * <p>
241      * The methods {@link #getInstant()}, {@link #getDateTimeBefore()} and {@link #getDateTimeAfter()}
242      * all represent the same instant.
243      *
244      * @return the transition instant, not null
245      */
getInstant()246     public Instant getInstant() {
247         return transition.toInstant(offsetBefore);
248     }
249 
250     /**
251      * Gets the transition instant as an epoch second.
252      *
253      * @return the transition epoch second
254      */
toEpochSecond()255     public long toEpochSecond() {
256         return transition.toEpochSecond(offsetBefore);
257     }
258 
259     //-------------------------------------------------------------------------
260     /**
261      * Gets the local transition date-time, as would be expressed with the 'before' offset.
262      * <p>
263      * This is the date-time where the discontinuity begins expressed with the 'before' offset.
264      * At this instant, the 'after' offset is actually used, therefore the combination of this
265      * date-time and the 'before' offset will never occur.
266      * <p>
267      * The combination of the 'before' date-time and offset represents the same instant
268      * as the 'after' date-time and offset.
269      *
270      * @return the transition date-time expressed with the before offset, not null
271      */
getDateTimeBefore()272     public LocalDateTime getDateTimeBefore() {
273         return transition;
274     }
275 
276     /**
277      * Gets the local transition date-time, as would be expressed with the 'after' offset.
278      * <p>
279      * This is the first date-time after the discontinuity, when the new offset applies.
280      * <p>
281      * The combination of the 'before' date-time and offset represents the same instant
282      * as the 'after' date-time and offset.
283      *
284      * @return the transition date-time expressed with the after offset, not null
285      */
getDateTimeAfter()286     public LocalDateTime getDateTimeAfter() {
287         return transition.plusSeconds(getDurationSeconds());
288     }
289 
290     /**
291      * Gets the offset before the transition.
292      * <p>
293      * This is the offset in use before the instant of the transition.
294      *
295      * @return the offset before the transition, not null
296      */
getOffsetBefore()297     public ZoneOffset getOffsetBefore() {
298         return offsetBefore;
299     }
300 
301     /**
302      * Gets the offset after the transition.
303      * <p>
304      * This is the offset in use on and after the instant of the transition.
305      *
306      * @return the offset after the transition, not null
307      */
getOffsetAfter()308     public ZoneOffset getOffsetAfter() {
309         return offsetAfter;
310     }
311 
312     /**
313      * Gets the duration of the transition.
314      * <p>
315      * In most cases, the transition duration is one hour, however this is not always the case.
316      * The duration will be positive for a gap and negative for an overlap.
317      * Time-zones are second-based, so the nanosecond part of the duration will be zero.
318      *
319      * @return the duration of the transition, positive for gaps, negative for overlaps
320      */
getDuration()321     public Duration getDuration() {
322         return Duration.ofSeconds(getDurationSeconds());
323     }
324 
325     /**
326      * Gets the duration of the transition in seconds.
327      *
328      * @return the duration in seconds
329      */
getDurationSeconds()330     private int getDurationSeconds() {
331         return getOffsetAfter().getTotalSeconds() - getOffsetBefore().getTotalSeconds();
332     }
333 
334     /**
335      * Does this transition represent a gap in the local time-line.
336      * <p>
337      * Gaps occur where there are local date-times that simply do not exist.
338      * An example would be when the offset changes from {@code +01:00} to {@code +02:00}.
339      * This might be described as 'the clocks will move forward one hour tonight at 1am'.
340      *
341      * @return true if this transition is a gap, false if it is an overlap
342      */
isGap()343     public boolean isGap() {
344         return getOffsetAfter().getTotalSeconds() > getOffsetBefore().getTotalSeconds();
345     }
346 
347     /**
348      * Does this transition represent an overlap in the local time-line.
349      * <p>
350      * Overlaps occur where there are local date-times that exist twice.
351      * An example would be when the offset changes from {@code +02:00} to {@code +01:00}.
352      * This might be described as 'the clocks will move back one hour tonight at 2am'.
353      *
354      * @return true if this transition is an overlap, false if it is a gap
355      */
isOverlap()356     public boolean isOverlap() {
357         return getOffsetAfter().getTotalSeconds() < getOffsetBefore().getTotalSeconds();
358     }
359 
360     /**
361      * Checks if the specified offset is valid during this transition.
362      * <p>
363      * This checks to see if the given offset will be valid at some point in the transition.
364      * A gap will always return false.
365      * An overlap will return true if the offset is either the before or after offset.
366      *
367      * @param offset  the offset to check, null returns false
368      * @return true if the offset is valid during the transition
369      */
isValidOffset(ZoneOffset offset)370     public boolean isValidOffset(ZoneOffset offset) {
371         return isGap() ? false : (getOffsetBefore().equals(offset) || getOffsetAfter().equals(offset));
372     }
373 
374     /**
375      * Gets the valid offsets during this transition.
376      * <p>
377      * A gap will return an empty list, while an overlap will return both offsets.
378      *
379      * @return the list of valid offsets
380      */
getValidOffsets()381     List<ZoneOffset> getValidOffsets() {
382         if (isGap()) {
383             return Collections.emptyList();
384         }
385         return Arrays.asList(getOffsetBefore(), getOffsetAfter());
386     }
387 
388     //-----------------------------------------------------------------------
389     /**
390      * Compares this transition to another based on the transition instant.
391      * <p>
392      * This compares the instants of each transition.
393      * The offsets are ignored, making this order inconsistent with equals.
394      *
395      * @param transition  the transition to compare to, not null
396      * @return the comparator value, negative if less, positive if greater
397      */
398     @Override
compareTo(ZoneOffsetTransition transition)399     public int compareTo(ZoneOffsetTransition transition) {
400         return this.getInstant().compareTo(transition.getInstant());
401     }
402 
403     //-----------------------------------------------------------------------
404     /**
405      * Checks if this object equals another.
406      * <p>
407      * The entire state of the object is compared.
408      *
409      * @param other  the other object to compare to, null returns false
410      * @return true if equal
411      */
412     @Override
equals(Object other)413     public boolean equals(Object other) {
414         if (other == this) {
415             return true;
416         }
417         if (other instanceof ZoneOffsetTransition) {
418             ZoneOffsetTransition d = (ZoneOffsetTransition) other;
419             return transition.equals(d.transition) &&
420                 offsetBefore.equals(d.offsetBefore) && offsetAfter.equals(d.offsetAfter);
421         }
422         return false;
423     }
424 
425     /**
426      * Returns a suitable hash code.
427      *
428      * @return the hash code
429      */
430     @Override
hashCode()431     public int hashCode() {
432         return transition.hashCode() ^ offsetBefore.hashCode() ^ Integer.rotateLeft(offsetAfter.hashCode(), 16);
433     }
434 
435     //-----------------------------------------------------------------------
436     /**
437      * Returns a string describing this object.
438      *
439      * @return a string for debugging, not null
440      */
441     @Override
toString()442     public String toString() {
443         StringBuilder buf = new StringBuilder();
444         buf.append("Transition[")
445             .append(isGap() ? "Gap" : "Overlap")
446             .append(" at ")
447             .append(transition)
448             .append(offsetBefore)
449             .append(" to ")
450             .append(offsetAfter)
451             .append(']');
452         return buf.toString();
453     }
454 
455 }
456