8187443: Forest Consolidation: Move files to unified layout

Reviewed-by: darcy, ihse
This commit is contained in:
Erik Joelsson 2017-09-12 19:03:39 +02:00
parent 270fe13182
commit 3789983e89
56923 changed files with 3 additions and 15727 deletions

View file

@ -0,0 +1,281 @@
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Copyright (c) 2011-2012, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package java.time.zone;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.Externalizable;
import java.io.IOException;
import java.io.InvalidClassException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.StreamCorruptedException;
import java.time.ZoneOffset;
/**
* The shared serialization delegate for this package.
*
* @implNote
* This class is mutable and should be created once per serialization.
*
* @serial include
* @since 1.8
*/
final class Ser implements Externalizable {
/**
* Serialization version.
*/
private static final long serialVersionUID = -8885321777449118786L;
/** Type for ZoneRules. */
static final byte ZRULES = 1;
/** Type for ZoneOffsetTransition. */
static final byte ZOT = 2;
/** Type for ZoneOffsetTransition. */
static final byte ZOTRULE = 3;
/** The type being serialized. */
private byte type;
/** The object being serialized. */
private Object object;
/**
* Constructor for deserialization.
*/
public Ser() {
}
/**
* Creates an instance for serialization.
*
* @param type the type
* @param object the object
*/
Ser(byte type, Object object) {
this.type = type;
this.object = object;
}
//-----------------------------------------------------------------------
/**
* Implements the {@code Externalizable} interface to write the object.
* @serialData
* Each serializable class is mapped to a type that is the first byte
* in the stream. Refer to each class {@code writeReplace}
* serialized form for the value of the type and sequence of values for the type.
*
* <ul>
* <li><a href="../../../serialized-form.html#java.time.zone.ZoneRules">ZoneRules.writeReplace</a>
* <li><a href="../../../serialized-form.html#java.time.zone.ZoneOffsetTransition">ZoneOffsetTransition.writeReplace</a>
* <li><a href="../../../serialized-form.html#java.time.zone.ZoneOffsetTransitionRule">ZoneOffsetTransitionRule.writeReplace</a>
* </ul>
*
* @param out the data stream to write to, not null
*/
@Override
public void writeExternal(ObjectOutput out) throws IOException {
writeInternal(type, object, out);
}
static void write(Object object, DataOutput out) throws IOException {
writeInternal(ZRULES, object, out);
}
private static void writeInternal(byte type, Object object, DataOutput out) throws IOException {
out.writeByte(type);
switch (type) {
case ZRULES:
((ZoneRules) object).writeExternal(out);
break;
case ZOT:
((ZoneOffsetTransition) object).writeExternal(out);
break;
case ZOTRULE:
((ZoneOffsetTransitionRule) object).writeExternal(out);
break;
default:
throw new InvalidClassException("Unknown serialized type");
}
}
//-----------------------------------------------------------------------
/**
* Implements the {@code Externalizable} interface to read the object.
* @serialData
* The streamed type and parameters defined by the type's {@code writeReplace}
* method are read and passed to the corresponding static factory for the type
* to create a new instance. That instance is returned as the de-serialized
* {@code Ser} object.
*
* <ul>
* <li><a href="../../../serialized-form.html#java.time.zone.ZoneRules">ZoneRules</a>
* - {@code ZoneRules.of(standardTransitions, standardOffsets, savingsInstantTransitions, wallOffsets, lastRules);}
* <li><a href="../../../serialized-form.html#java.time.zone.ZoneOffsetTransition">ZoneOffsetTransition</a>
* - {@code ZoneOffsetTransition of(LocalDateTime.ofEpochSecond(epochSecond), offsetBefore, offsetAfter);}
* <li><a href="../../../serialized-form.html#java.time.zone.ZoneOffsetTransitionRule">ZoneOffsetTransitionRule</a>
* - {@code ZoneOffsetTransitionRule.of(month, dom, dow, time, timeEndOfDay, timeDefinition, standardOffset, offsetBefore, offsetAfter);}
* </ul>
* @param in the data to read, not null
*/
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
type = in.readByte();
object = readInternal(type, in);
}
static Object read(DataInput in) throws IOException, ClassNotFoundException {
byte type = in.readByte();
return readInternal(type, in);
}
private static Object readInternal(byte type, DataInput in) throws IOException, ClassNotFoundException {
switch (type) {
case ZRULES:
return ZoneRules.readExternal(in);
case ZOT:
return ZoneOffsetTransition.readExternal(in);
case ZOTRULE:
return ZoneOffsetTransitionRule.readExternal(in);
default:
throw new StreamCorruptedException("Unknown serialized type");
}
}
/**
* Returns the object that will replace this one.
*
* @return the read object, should never be null
*/
private Object readResolve() {
return object;
}
//-----------------------------------------------------------------------
/**
* Writes the state to the stream.
*
* @param offset the offset, not null
* @param out the output stream, not null
* @throws IOException if an error occurs
*/
static void writeOffset(ZoneOffset offset, DataOutput out) throws IOException {
final int offsetSecs = offset.getTotalSeconds();
int offsetByte = offsetSecs % 900 == 0 ? offsetSecs / 900 : 127; // compress to -72 to +72
out.writeByte(offsetByte);
if (offsetByte == 127) {
out.writeInt(offsetSecs);
}
}
/**
* Reads the state from the stream.
*
* @param in the input stream, not null
* @return the created object, not null
* @throws IOException if an error occurs
*/
static ZoneOffset readOffset(DataInput in) throws IOException {
int offsetByte = in.readByte();
return (offsetByte == 127 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(offsetByte * 900));
}
//-----------------------------------------------------------------------
/**
* Writes the state to the stream.
*
* @param epochSec the epoch seconds, not null
* @param out the output stream, not null
* @throws IOException if an error occurs
*/
static void writeEpochSec(long epochSec, DataOutput out) throws IOException {
if (epochSec >= -4575744000L && epochSec < 10413792000L && epochSec % 900 == 0) { // quarter hours between 1825 and 2300
int store = (int) ((epochSec + 4575744000L) / 900);
out.writeByte((store >>> 16) & 255);
out.writeByte((store >>> 8) & 255);
out.writeByte(store & 255);
} else {
out.writeByte(255);
out.writeLong(epochSec);
}
}
/**
* Reads the state from the stream.
*
* @param in the input stream, not null
* @return the epoch seconds, not null
* @throws IOException if an error occurs
*/
static long readEpochSec(DataInput in) throws IOException {
int hiByte = in.readByte() & 255;
if (hiByte == 255) {
return in.readLong();
} else {
int midByte = in.readByte() & 255;
int loByte = in.readByte() & 255;
long tot = ((hiByte << 16) + (midByte << 8) + loByte);
return (tot * 900) - 4575744000L;
}
}
}

View file

@ -0,0 +1,206 @@
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Copyright (c) 2009-2012, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package java.time.zone;
import java.io.ByteArrayInputStream;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StreamCorruptedException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
/**
* Loads time-zone rules for 'TZDB'.
*
* @since 1.8
*/
final class TzdbZoneRulesProvider extends ZoneRulesProvider {
/**
* All the regions that are available.
*/
private List<String> regionIds;
/**
* Version Id of this tzdb rules
*/
private String versionId;
/**
* Region to rules mapping
*/
private final Map<String, Object> regionToRules = new ConcurrentHashMap<>();
/**
* Creates an instance.
* Created by the {@code ServiceLoader}.
*
* @throws ZoneRulesException if unable to load
*/
public TzdbZoneRulesProvider() {
try {
String libDir = System.getProperty("java.home") + File.separator + "lib";
try (DataInputStream dis = new DataInputStream(
new BufferedInputStream(new FileInputStream(
new File(libDir, "tzdb.dat"))))) {
load(dis);
}
} catch (Exception ex) {
throw new ZoneRulesException("Unable to load TZDB time-zone rules", ex);
}
}
@Override
protected Set<String> provideZoneIds() {
return new HashSet<>(regionIds);
}
@Override
protected ZoneRules provideRules(String zoneId, boolean forCaching) {
// forCaching flag is ignored because this is not a dynamic provider
Object obj = regionToRules.get(zoneId);
if (obj == null) {
throw new ZoneRulesException("Unknown time-zone ID: " + zoneId);
}
try {
if (obj instanceof byte[]) {
byte[] bytes = (byte[]) obj;
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes));
obj = Ser.read(dis);
regionToRules.put(zoneId, obj);
}
return (ZoneRules) obj;
} catch (Exception ex) {
throw new ZoneRulesException("Invalid binary time-zone data: TZDB:" + zoneId + ", version: " + versionId, ex);
}
}
@Override
protected NavigableMap<String, ZoneRules> provideVersions(String zoneId) {
TreeMap<String, ZoneRules> map = new TreeMap<>();
ZoneRules rules = getRules(zoneId, false);
if (rules != null) {
map.put(versionId, rules);
}
return map;
}
/**
* Loads the rules from a DateInputStream, often in a jar file.
*
* @param dis the DateInputStream to load, not null
* @throws Exception if an error occurs
*/
private void load(DataInputStream dis) throws Exception {
if (dis.readByte() != 1) {
throw new StreamCorruptedException("File format not recognised");
}
// group
String groupId = dis.readUTF();
if ("TZDB".equals(groupId) == false) {
throw new StreamCorruptedException("File format not recognised");
}
// versions
int versionCount = dis.readShort();
for (int i = 0; i < versionCount; i++) {
versionId = dis.readUTF();
}
// regions
int regionCount = dis.readShort();
String[] regionArray = new String[regionCount];
for (int i = 0; i < regionCount; i++) {
regionArray[i] = dis.readUTF();
}
regionIds = Arrays.asList(regionArray);
// rules
int ruleCount = dis.readShort();
Object[] ruleArray = new Object[ruleCount];
for (int i = 0; i < ruleCount; i++) {
byte[] bytes = new byte[dis.readShort()];
dis.readFully(bytes);
ruleArray[i] = bytes;
}
// link version-region-rules
for (int i = 0; i < versionCount; i++) {
int versionRegionCount = dis.readShort();
regionToRules.clear();
for (int j = 0; j < versionRegionCount; j++) {
String region = regionArray[dis.readShort()];
Object rule = ruleArray[dis.readShort() & 0xffff];
regionToRules.put(region, rule);
}
}
}
@Override
public String toString() {
return "TZDB[" + versionId + "]";
}
}

View file

@ -0,0 +1,462 @@
/*
* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Copyright (c) 2009-2012, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package java.time.zone;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
/**
* A transition between two offsets caused by a discontinuity in the local time-line.
* <p>
* A transition between two offsets is normally the result of a daylight savings cutover.
* The discontinuity is normally a gap in spring and an overlap in autumn.
* {@code ZoneOffsetTransition} models the transition between the two offsets.
* <p>
* Gaps occur where there are local date-times that simply do not exist.
* An example would be when the offset changes from {@code +03:00} to {@code +04:00}.
* This might be described as 'the clocks will move forward one hour tonight at 1am'.
* <p>
* Overlaps occur where there are local date-times that exist twice.
* An example would be when the offset changes from {@code +04:00} to {@code +03:00}.
* This might be described as 'the clocks will move back one hour tonight at 2am'.
*
* @implSpec
* This class is immutable and thread-safe.
*
* @since 1.8
*/
public final class ZoneOffsetTransition
implements Comparable<ZoneOffsetTransition>, Serializable {
/**
* Serialization version.
*/
private static final long serialVersionUID = -6946044323557704546L;
/**
* The transition epoch-second.
*/
private final long epochSecond;
/**
* The local transition date-time at the transition.
*/
private final LocalDateTime transition;
/**
* The offset before transition.
*/
private final ZoneOffset offsetBefore;
/**
* The offset after transition.
*/
private final ZoneOffset offsetAfter;
//-----------------------------------------------------------------------
/**
* Obtains an instance defining a transition between two offsets.
* <p>
* Applications should normally obtain an instance from {@link ZoneRules}.
* This factory is only intended for use when creating {@link ZoneRules}.
*
* @param transition the transition date-time at the transition, which never
* actually occurs, expressed local to the before offset, not null
* @param offsetBefore the offset before the transition, not null
* @param offsetAfter the offset at and after the transition, not null
* @return the transition, not null
* @throws IllegalArgumentException if {@code offsetBefore} and {@code offsetAfter}
* are equal, or {@code transition.getNano()} returns non-zero value
*/
public static ZoneOffsetTransition of(LocalDateTime transition, ZoneOffset offsetBefore, ZoneOffset offsetAfter) {
Objects.requireNonNull(transition, "transition");
Objects.requireNonNull(offsetBefore, "offsetBefore");
Objects.requireNonNull(offsetAfter, "offsetAfter");
if (offsetBefore.equals(offsetAfter)) {
throw new IllegalArgumentException("Offsets must not be equal");
}
if (transition.getNano() != 0) {
throw new IllegalArgumentException("Nano-of-second must be zero");
}
return new ZoneOffsetTransition(transition, offsetBefore, offsetAfter);
}
/**
* Creates an instance defining a transition between two offsets.
*
* @param transition the transition date-time with the offset before the transition, not null
* @param offsetBefore the offset before the transition, not null
* @param offsetAfter the offset at and after the transition, not null
*/
ZoneOffsetTransition(LocalDateTime transition, ZoneOffset offsetBefore, ZoneOffset offsetAfter) {
assert transition.getNano() == 0;
this.epochSecond = transition.toEpochSecond(offsetBefore);
this.transition = transition;
this.offsetBefore = offsetBefore;
this.offsetAfter = offsetAfter;
}
/**
* Creates an instance from epoch-second and offsets.
*
* @param epochSecond the transition epoch-second
* @param offsetBefore the offset before the transition, not null
* @param offsetAfter the offset at and after the transition, not null
*/
ZoneOffsetTransition(long epochSecond, ZoneOffset offsetBefore, ZoneOffset offsetAfter) {
this.epochSecond = epochSecond;
this.transition = LocalDateTime.ofEpochSecond(epochSecond, 0, offsetBefore);
this.offsetBefore = offsetBefore;
this.offsetAfter = offsetAfter;
}
//-----------------------------------------------------------------------
/**
* Defend against malicious streams.
*
* @param s the stream to read
* @throws InvalidObjectException always
*/
private void readObject(ObjectInputStream s) throws InvalidObjectException {
throw new InvalidObjectException("Deserialization via serialization delegate");
}
/**
* Writes the object using a
* <a href="../../../serialized-form.html#java.time.zone.Ser">dedicated serialized form</a>.
* @serialData
* Refer to the serialized form of
* <a href="../../../serialized-form.html#java.time.zone.ZoneRules">ZoneRules.writeReplace</a>
* for the encoding of epoch seconds and offsets.
* <pre style="font-size:1.0em">{@code
*
* out.writeByte(2); // identifies a ZoneOffsetTransition
* out.writeEpochSec(toEpochSecond);
* out.writeOffset(offsetBefore);
* out.writeOffset(offsetAfter);
* }
* </pre>
* @return the replacing object, not null
*/
private Object writeReplace() {
return new Ser(Ser.ZOT, this);
}
/**
* Writes the state to the stream.
*
* @param out the output stream, not null
* @throws IOException if an error occurs
*/
void writeExternal(DataOutput out) throws IOException {
Ser.writeEpochSec(epochSecond, out);
Ser.writeOffset(offsetBefore, out);
Ser.writeOffset(offsetAfter, out);
}
/**
* Reads the state from the stream.
*
* @param in the input stream, not null
* @return the created object, not null
* @throws IOException if an error occurs
*/
static ZoneOffsetTransition readExternal(DataInput in) throws IOException {
long epochSecond = Ser.readEpochSec(in);
ZoneOffset before = Ser.readOffset(in);
ZoneOffset after = Ser.readOffset(in);
if (before.equals(after)) {
throw new IllegalArgumentException("Offsets must not be equal");
}
return new ZoneOffsetTransition(epochSecond, before, after);
}
//-----------------------------------------------------------------------
/**
* Gets the transition instant.
* <p>
* This is the instant of the discontinuity, which is defined as the first
* instant that the 'after' offset applies.
* <p>
* The methods {@link #getInstant()}, {@link #getDateTimeBefore()} and {@link #getDateTimeAfter()}
* all represent the same instant.
*
* @return the transition instant, not null
*/
public Instant getInstant() {
return Instant.ofEpochSecond(epochSecond);
}
/**
* Gets the transition instant as an epoch second.
*
* @return the transition epoch second
*/
public long toEpochSecond() {
return epochSecond;
}
//-------------------------------------------------------------------------
/**
* Gets the local transition date-time, as would be expressed with the 'before' offset.
* <p>
* This is the date-time where the discontinuity begins expressed with the 'before' offset.
* At this instant, the 'after' offset is actually used, therefore the combination of this
* date-time and the 'before' offset will never occur.
* <p>
* The combination of the 'before' date-time and offset represents the same instant
* as the 'after' date-time and offset.
*
* @return the transition date-time expressed with the before offset, not null
*/
public LocalDateTime getDateTimeBefore() {
return transition;
}
/**
* Gets the local transition date-time, as would be expressed with the 'after' offset.
* <p>
* This is the first date-time after the discontinuity, when the new offset applies.
* <p>
* The combination of the 'before' date-time and offset represents the same instant
* as the 'after' date-time and offset.
*
* @return the transition date-time expressed with the after offset, not null
*/
public LocalDateTime getDateTimeAfter() {
return transition.plusSeconds(getDurationSeconds());
}
/**
* Gets the offset before the transition.
* <p>
* This is the offset in use before the instant of the transition.
*
* @return the offset before the transition, not null
*/
public ZoneOffset getOffsetBefore() {
return offsetBefore;
}
/**
* Gets the offset after the transition.
* <p>
* This is the offset in use on and after the instant of the transition.
*
* @return the offset after the transition, not null
*/
public ZoneOffset getOffsetAfter() {
return offsetAfter;
}
/**
* Gets the duration of the transition.
* <p>
* In most cases, the transition duration is one hour, however this is not always the case.
* The duration will be positive for a gap and negative for an overlap.
* Time-zones are second-based, so the nanosecond part of the duration will be zero.
*
* @return the duration of the transition, positive for gaps, negative for overlaps
*/
public Duration getDuration() {
return Duration.ofSeconds(getDurationSeconds());
}
/**
* Gets the duration of the transition in seconds.
*
* @return the duration in seconds
*/
private int getDurationSeconds() {
return getOffsetAfter().getTotalSeconds() - getOffsetBefore().getTotalSeconds();
}
/**
* Does this transition represent a gap in the local time-line.
* <p>
* Gaps occur where there are local date-times that simply do not exist.
* An example would be when the offset changes from {@code +01:00} to {@code +02:00}.
* This might be described as 'the clocks will move forward one hour tonight at 1am'.
*
* @return true if this transition is a gap, false if it is an overlap
*/
public boolean isGap() {
return getOffsetAfter().getTotalSeconds() > getOffsetBefore().getTotalSeconds();
}
/**
* Does this transition represent an overlap in the local time-line.
* <p>
* Overlaps occur where there are local date-times that exist twice.
* An example would be when the offset changes from {@code +02:00} to {@code +01:00}.
* This might be described as 'the clocks will move back one hour tonight at 2am'.
*
* @return true if this transition is an overlap, false if it is a gap
*/
public boolean isOverlap() {
return getOffsetAfter().getTotalSeconds() < getOffsetBefore().getTotalSeconds();
}
/**
* Checks if the specified offset is valid during this transition.
* <p>
* This checks to see if the given offset will be valid at some point in the transition.
* A gap will always return false.
* An overlap will return true if the offset is either the before or after offset.
*
* @param offset the offset to check, null returns false
* @return true if the offset is valid during the transition
*/
public boolean isValidOffset(ZoneOffset offset) {
return isGap() ? false : (getOffsetBefore().equals(offset) || getOffsetAfter().equals(offset));
}
/**
* Gets the valid offsets during this transition.
* <p>
* A gap will return an empty list, while an overlap will return both offsets.
*
* @return the list of valid offsets
*/
List<ZoneOffset> getValidOffsets() {
if (isGap()) {
return List.of();
}
return List.of(getOffsetBefore(), getOffsetAfter());
}
//-----------------------------------------------------------------------
/**
* Compares this transition to another based on the transition instant.
* <p>
* This compares the instants of each transition.
* The offsets are ignored, making this order inconsistent with equals.
*
* @param transition the transition to compare to, not null
* @return the comparator value, negative if less, positive if greater
*/
@Override
public int compareTo(ZoneOffsetTransition transition) {
return Long.compare(epochSecond, transition.epochSecond);
}
//-----------------------------------------------------------------------
/**
* Checks if this object equals another.
* <p>
* The entire state of the object is compared.
*
* @param other the other object to compare to, null returns false
* @return true if equal
*/
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (other instanceof ZoneOffsetTransition) {
ZoneOffsetTransition d = (ZoneOffsetTransition) other;
return epochSecond == d.epochSecond &&
offsetBefore.equals(d.offsetBefore) && offsetAfter.equals(d.offsetAfter);
}
return false;
}
/**
* Returns a suitable hash code.
*
* @return the hash code
*/
@Override
public int hashCode() {
return transition.hashCode() ^ offsetBefore.hashCode() ^ Integer.rotateLeft(offsetAfter.hashCode(), 16);
}
//-----------------------------------------------------------------------
/**
* Returns a string describing this object.
*
* @return a string for debugging, not null
*/
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append("Transition[")
.append(isGap() ? "Gap" : "Overlap")
.append(" at ")
.append(transition)
.append(offsetBefore)
.append(" to ")
.append(offsetAfter)
.append(']');
return buf.toString();
}
}

View file

@ -0,0 +1,632 @@
/*
* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Copyright (c) 2009-2012, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package java.time.zone;
import static java.time.temporal.TemporalAdjusters.nextOrSame;
import static java.time.temporal.TemporalAdjusters.previousOrSame;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.ZoneOffset;
import java.time.chrono.IsoChronology;
import java.util.Objects;
/**
* A rule expressing how to create a transition.
* <p>
* This class allows rules for identifying future transitions to be expressed.
* A rule might be written in many forms:
* <ul>
* <li>the 16th March
* <li>the Sunday on or after the 16th March
* <li>the Sunday on or before the 16th March
* <li>the last Sunday in February
* </ul>
* These different rule types can be expressed and queried.
*
* @implSpec
* This class is immutable and thread-safe.
*
* @since 1.8
*/
public final class ZoneOffsetTransitionRule implements Serializable {
/**
* Serialization version.
*/
private static final long serialVersionUID = 6889046316657758795L;
/**
* The month of the month-day of the first day of the cutover week.
* The actual date will be adjusted by the dowChange field.
*/
private final Month month;
/**
* The day-of-month of the month-day of the cutover week.
* If positive, it is the start of the week where the cutover can occur.
* If negative, it represents the end of the week where cutover can occur.
* The value is the number of days from the end of the month, such that
* {@code -1} is the last day of the month, {@code -2} is the second
* to last day, and so on.
*/
private final byte dom;
/**
* The cutover day-of-week, null to retain the day-of-month.
*/
private final DayOfWeek dow;
/**
* The cutover time in the 'before' offset.
*/
private final LocalTime time;
/**
* Whether the cutover time is midnight at the end of day.
*/
private final boolean timeEndOfDay;
/**
* The definition of how the local time should be interpreted.
*/
private final TimeDefinition timeDefinition;
/**
* The standard offset at the cutover.
*/
private final ZoneOffset standardOffset;
/**
* The offset before the cutover.
*/
private final ZoneOffset offsetBefore;
/**
* The offset after the cutover.
*/
private final ZoneOffset offsetAfter;
/**
* Obtains an instance defining the yearly rule to create transitions between two offsets.
* <p>
* Applications should normally obtain an instance from {@link ZoneRules}.
* This factory is only intended for use when creating {@link ZoneRules}.
*
* @param month the month of the month-day of the first day of the cutover week, not null
* @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that
* day or later, negative if the week is that day or earlier, counting from the last day of the month,
* from -28 to 31 excluding 0
* @param dayOfWeek the required day-of-week, null if the month-day should not be changed
* @param time the cutover time in the 'before' offset, not null
* @param timeEndOfDay whether the time is midnight at the end of day
* @param timeDefnition how to interpret the cutover
* @param standardOffset the standard offset in force at the cutover, not null
* @param offsetBefore the offset before the cutover, not null
* @param offsetAfter the offset after the cutover, not null
* @return the rule, not null
* @throws IllegalArgumentException if the day of month indicator is invalid
* @throws IllegalArgumentException if the end of day flag is true when the time is not midnight
* @throws IllegalArgumentException if {@code time.getNano()} returns non-zero value
*/
public static ZoneOffsetTransitionRule of(
Month month,
int dayOfMonthIndicator,
DayOfWeek dayOfWeek,
LocalTime time,
boolean timeEndOfDay,
TimeDefinition timeDefnition,
ZoneOffset standardOffset,
ZoneOffset offsetBefore,
ZoneOffset offsetAfter) {
Objects.requireNonNull(month, "month");
Objects.requireNonNull(time, "time");
Objects.requireNonNull(timeDefnition, "timeDefnition");
Objects.requireNonNull(standardOffset, "standardOffset");
Objects.requireNonNull(offsetBefore, "offsetBefore");
Objects.requireNonNull(offsetAfter, "offsetAfter");
if (dayOfMonthIndicator < -28 || dayOfMonthIndicator > 31 || dayOfMonthIndicator == 0) {
throw new IllegalArgumentException("Day of month indicator must be between -28 and 31 inclusive excluding zero");
}
if (timeEndOfDay && time.equals(LocalTime.MIDNIGHT) == false) {
throw new IllegalArgumentException("Time must be midnight when end of day flag is true");
}
if (time.getNano() != 0) {
throw new IllegalArgumentException("Time's nano-of-second must be zero");
}
return new ZoneOffsetTransitionRule(month, dayOfMonthIndicator, dayOfWeek, time, timeEndOfDay, timeDefnition, standardOffset, offsetBefore, offsetAfter);
}
/**
* Creates an instance defining the yearly rule to create transitions between two offsets.
*
* @param month the month of the month-day of the first day of the cutover week, not null
* @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that
* day or later, negative if the week is that day or earlier, counting from the last day of the month,
* from -28 to 31 excluding 0
* @param dayOfWeek the required day-of-week, null if the month-day should not be changed
* @param time the cutover time in the 'before' offset, not null
* @param timeEndOfDay whether the time is midnight at the end of day
* @param timeDefnition how to interpret the cutover
* @param standardOffset the standard offset in force at the cutover, not null
* @param offsetBefore the offset before the cutover, not null
* @param offsetAfter the offset after the cutover, not null
* @throws IllegalArgumentException if the day of month indicator is invalid
* @throws IllegalArgumentException if the end of day flag is true when the time is not midnight
*/
ZoneOffsetTransitionRule(
Month month,
int dayOfMonthIndicator,
DayOfWeek dayOfWeek,
LocalTime time,
boolean timeEndOfDay,
TimeDefinition timeDefnition,
ZoneOffset standardOffset,
ZoneOffset offsetBefore,
ZoneOffset offsetAfter) {
assert time.getNano() == 0;
this.month = month;
this.dom = (byte) dayOfMonthIndicator;
this.dow = dayOfWeek;
this.time = time;
this.timeEndOfDay = timeEndOfDay;
this.timeDefinition = timeDefnition;
this.standardOffset = standardOffset;
this.offsetBefore = offsetBefore;
this.offsetAfter = offsetAfter;
}
//-----------------------------------------------------------------------
/**
* Defend against malicious streams.
*
* @param s the stream to read
* @throws InvalidObjectException always
*/
private void readObject(ObjectInputStream s) throws InvalidObjectException {
throw new InvalidObjectException("Deserialization via serialization delegate");
}
/**
* Writes the object using a
* <a href="../../../serialized-form.html#java.time.zone.Ser">dedicated serialized form</a>.
* @serialData
* Refer to the serialized form of
* <a href="../../../serialized-form.html#java.time.zone.ZoneRules">ZoneRules.writeReplace</a>
* for the encoding of epoch seconds and offsets.
* <pre style="font-size:1.0em">{@code
*
* out.writeByte(3); // identifies a ZoneOffsetTransition
* final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay());
* final int stdOffset = standardOffset.getTotalSeconds();
* final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset;
* final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset;
* final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31);
* final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255);
* final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3);
* final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3);
* final int dowByte = (dow == null ? 0 : dow.getValue());
* int b = (month.getValue() << 28) + // 4 bits
* ((dom + 32) << 22) + // 6 bits
* (dowByte << 19) + // 3 bits
* (timeByte << 14) + // 5 bits
* (timeDefinition.ordinal() << 12) + // 2 bits
* (stdOffsetByte << 4) + // 8 bits
* (beforeByte << 2) + // 2 bits
* afterByte; // 2 bits
* out.writeInt(b);
* if (timeByte == 31) {
* out.writeInt(timeSecs);
* }
* if (stdOffsetByte == 255) {
* out.writeInt(stdOffset);
* }
* if (beforeByte == 3) {
* out.writeInt(offsetBefore.getTotalSeconds());
* }
* if (afterByte == 3) {
* out.writeInt(offsetAfter.getTotalSeconds());
* }
* }
* </pre>
*
* @return the replacing object, not null
*/
private Object writeReplace() {
return new Ser(Ser.ZOTRULE, this);
}
/**
* Writes the state to the stream.
*
* @param out the output stream, not null
* @throws IOException if an error occurs
*/
void writeExternal(DataOutput out) throws IOException {
final int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay());
final int stdOffset = standardOffset.getTotalSeconds();
final int beforeDiff = offsetBefore.getTotalSeconds() - stdOffset;
final int afterDiff = offsetAfter.getTotalSeconds() - stdOffset;
final int timeByte = (timeSecs % 3600 == 0 ? (timeEndOfDay ? 24 : time.getHour()) : 31);
final int stdOffsetByte = (stdOffset % 900 == 0 ? stdOffset / 900 + 128 : 255);
final int beforeByte = (beforeDiff == 0 || beforeDiff == 1800 || beforeDiff == 3600 ? beforeDiff / 1800 : 3);
final int afterByte = (afterDiff == 0 || afterDiff == 1800 || afterDiff == 3600 ? afterDiff / 1800 : 3);
final int dowByte = (dow == null ? 0 : dow.getValue());
int b = (month.getValue() << 28) + // 4 bits
((dom + 32) << 22) + // 6 bits
(dowByte << 19) + // 3 bits
(timeByte << 14) + // 5 bits
(timeDefinition.ordinal() << 12) + // 2 bits
(stdOffsetByte << 4) + // 8 bits
(beforeByte << 2) + // 2 bits
afterByte; // 2 bits
out.writeInt(b);
if (timeByte == 31) {
out.writeInt(timeSecs);
}
if (stdOffsetByte == 255) {
out.writeInt(stdOffset);
}
if (beforeByte == 3) {
out.writeInt(offsetBefore.getTotalSeconds());
}
if (afterByte == 3) {
out.writeInt(offsetAfter.getTotalSeconds());
}
}
/**
* Reads the state from the stream.
*
* @param in the input stream, not null
* @return the created object, not null
* @throws IOException if an error occurs
*/
static ZoneOffsetTransitionRule readExternal(DataInput in) throws IOException {
int data = in.readInt();
Month month = Month.of(data >>> 28);
int dom = ((data & (63 << 22)) >>> 22) - 32;
int dowByte = (data & (7 << 19)) >>> 19;
DayOfWeek dow = dowByte == 0 ? null : DayOfWeek.of(dowByte);
int timeByte = (data & (31 << 14)) >>> 14;
TimeDefinition defn = TimeDefinition.values()[(data & (3 << 12)) >>> 12];
int stdByte = (data & (255 << 4)) >>> 4;
int beforeByte = (data & (3 << 2)) >>> 2;
int afterByte = (data & 3);
LocalTime time = (timeByte == 31 ? LocalTime.ofSecondOfDay(in.readInt()) : LocalTime.of(timeByte % 24, 0));
ZoneOffset std = (stdByte == 255 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds((stdByte - 128) * 900));
ZoneOffset before = (beforeByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + beforeByte * 1800));
ZoneOffset after = (afterByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + afterByte * 1800));
return ZoneOffsetTransitionRule.of(month, dom, dow, time, timeByte == 24, defn, std, before, after);
}
//-----------------------------------------------------------------------
/**
* Gets the month of the transition.
* <p>
* If the rule defines an exact date then the month is the month of that date.
* <p>
* If the rule defines a week where the transition might occur, then the month
* if the month of either the earliest or latest possible date of the cutover.
*
* @return the month of the transition, not null
*/
public Month getMonth() {
return month;
}
/**
* Gets the indicator of the day-of-month of the transition.
* <p>
* If the rule defines an exact date then the day is the month of that date.
* <p>
* If the rule defines a week where the transition might occur, then the day
* defines either the start of the end of the transition week.
* <p>
* If the value is positive, then it represents a normal day-of-month, and is the
* earliest possible date that the transition can be.
* The date may refer to 29th February which should be treated as 1st March in non-leap years.
* <p>
* If the value is negative, then it represents the number of days back from the
* end of the month where {@code -1} is the last day of the month.
* In this case, the day identified is the latest possible date that the transition can be.
*
* @return the day-of-month indicator, from -28 to 31 excluding 0
*/
public int getDayOfMonthIndicator() {
return dom;
}
/**
* Gets the day-of-week of the transition.
* <p>
* If the rule defines an exact date then this returns null.
* <p>
* If the rule defines a week where the cutover might occur, then this method
* returns the day-of-week that the month-day will be adjusted to.
* If the day is positive then the adjustment is later.
* If the day is negative then the adjustment is earlier.
*
* @return the day-of-week that the transition occurs, null if the rule defines an exact date
*/
public DayOfWeek getDayOfWeek() {
return dow;
}
/**
* Gets the local time of day of the transition which must be checked with
* {@link #isMidnightEndOfDay()}.
* <p>
* The time is converted into an instant using the time definition.
*
* @return the local time of day of the transition, not null
*/
public LocalTime getLocalTime() {
return time;
}
/**
* Is the transition local time midnight at the end of day.
* <p>
* The transition may be represented as occurring at 24:00.
*
* @return whether a local time of midnight is at the start or end of the day
*/
public boolean isMidnightEndOfDay() {
return timeEndOfDay;
}
/**
* Gets the time definition, specifying how to convert the time to an instant.
* <p>
* The local time can be converted to an instant using the standard offset,
* the wall offset or UTC.
*
* @return the time definition, not null
*/
public TimeDefinition getTimeDefinition() {
return timeDefinition;
}
/**
* Gets the standard offset in force at the transition.
*
* @return the standard offset, not null
*/
public ZoneOffset getStandardOffset() {
return standardOffset;
}
/**
* Gets the offset before the transition.
*
* @return the offset before, not null
*/
public ZoneOffset getOffsetBefore() {
return offsetBefore;
}
/**
* Gets the offset after the transition.
*
* @return the offset after, not null
*/
public ZoneOffset getOffsetAfter() {
return offsetAfter;
}
//-----------------------------------------------------------------------
/**
* Creates a transition instance for the specified year.
* <p>
* Calculations are performed using the ISO-8601 chronology.
*
* @param year the year to create a transition for, not null
* @return the transition instance, not null
*/
public ZoneOffsetTransition createTransition(int year) {
LocalDate date;
if (dom < 0) {
date = LocalDate.of(year, month, month.length(IsoChronology.INSTANCE.isLeapYear(year)) + 1 + dom);
if (dow != null) {
date = date.with(previousOrSame(dow));
}
} else {
date = LocalDate.of(year, month, dom);
if (dow != null) {
date = date.with(nextOrSame(dow));
}
}
if (timeEndOfDay) {
date = date.plusDays(1);
}
LocalDateTime localDT = LocalDateTime.of(date, time);
LocalDateTime transition = timeDefinition.createDateTime(localDT, standardOffset, offsetBefore);
return new ZoneOffsetTransition(transition, offsetBefore, offsetAfter);
}
//-----------------------------------------------------------------------
/**
* Checks if this object equals another.
* <p>
* The entire state of the object is compared.
*
* @param otherRule the other object to compare to, null returns false
* @return true if equal
*/
@Override
public boolean equals(Object otherRule) {
if (otherRule == this) {
return true;
}
if (otherRule instanceof ZoneOffsetTransitionRule) {
ZoneOffsetTransitionRule other = (ZoneOffsetTransitionRule) otherRule;
return month == other.month && dom == other.dom && dow == other.dow &&
timeDefinition == other.timeDefinition &&
time.equals(other.time) &&
timeEndOfDay == other.timeEndOfDay &&
standardOffset.equals(other.standardOffset) &&
offsetBefore.equals(other.offsetBefore) &&
offsetAfter.equals(other.offsetAfter);
}
return false;
}
/**
* Returns a suitable hash code.
*
* @return the hash code
*/
@Override
public int hashCode() {
int hash = ((time.toSecondOfDay() + (timeEndOfDay ? 1 : 0)) << 15) +
(month.ordinal() << 11) + ((dom + 32) << 5) +
((dow == null ? 7 : dow.ordinal()) << 2) + (timeDefinition.ordinal());
return hash ^ standardOffset.hashCode() ^
offsetBefore.hashCode() ^ offsetAfter.hashCode();
}
//-----------------------------------------------------------------------
/**
* Returns a string describing this object.
*
* @return a string for debugging, not null
*/
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append("TransitionRule[")
.append(offsetBefore.compareTo(offsetAfter) > 0 ? "Gap " : "Overlap ")
.append(offsetBefore).append(" to ").append(offsetAfter).append(", ");
if (dow != null) {
if (dom == -1) {
buf.append(dow.name()).append(" on or before last day of ").append(month.name());
} else if (dom < 0) {
buf.append(dow.name()).append(" on or before last day minus ").append(-dom - 1).append(" of ").append(month.name());
} else {
buf.append(dow.name()).append(" on or after ").append(month.name()).append(' ').append(dom);
}
} else {
buf.append(month.name()).append(' ').append(dom);
}
buf.append(" at ").append(timeEndOfDay ? "24:00" : time.toString())
.append(" ").append(timeDefinition)
.append(", standard offset ").append(standardOffset)
.append(']');
return buf.toString();
}
//-----------------------------------------------------------------------
/**
* A definition of the way a local time can be converted to the actual
* transition date-time.
* <p>
* Time zone rules are expressed in one of three ways:
* <ul>
* <li>Relative to UTC</li>
* <li>Relative to the standard offset in force</li>
* <li>Relative to the wall offset (what you would see on a clock on the wall)</li>
* </ul>
*/
public static enum TimeDefinition {
/** The local date-time is expressed in terms of the UTC offset. */
UTC,
/** The local date-time is expressed in terms of the wall offset. */
WALL,
/** The local date-time is expressed in terms of the standard offset. */
STANDARD;
/**
* Converts the specified local date-time to the local date-time actually
* seen on a wall clock.
* <p>
* This method converts using the type of this enum.
* The output is defined relative to the 'before' offset of the transition.
* <p>
* The UTC type uses the UTC offset.
* The STANDARD type uses the standard offset.
* The WALL type returns the input date-time.
* The result is intended for use with the wall-offset.
*
* @param dateTime the local date-time, not null
* @param standardOffset the standard offset, not null
* @param wallOffset the wall offset, not null
* @return the date-time relative to the wall/before offset, not null
*/
public LocalDateTime createDateTime(LocalDateTime dateTime, ZoneOffset standardOffset, ZoneOffset wallOffset) {
switch (this) {
case UTC: {
int difference = wallOffset.getTotalSeconds() - ZoneOffset.UTC.getTotalSeconds();
return dateTime.plusSeconds(difference);
}
case STANDARD: {
int difference = wallOffset.getTotalSeconds() - standardOffset.getTotalSeconds();
return dateTime.plusSeconds(difference);
}
default: // WALL
return dateTime;
}
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,98 @@
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* Copyright (c) 2008-2012, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package java.time.zone;
import java.time.DateTimeException;
/**
* Thrown to indicate a problem with time-zone configuration.
* <p>
* This exception is used to indicate a problems with the configured
* time-zone rules.
*
* @implSpec
* This class is intended for use in a single thread.
*
* @since 1.8
*/
public class ZoneRulesException extends DateTimeException {
/**
* Serialization version.
*/
private static final long serialVersionUID = -1632418723876261839L;
/**
* Constructs a new date-time exception with the specified message.
*
* @param message the message to use for this exception, may be null
*/
public ZoneRulesException(String message) {
super(message);
}
/**
* Constructs a new date-time exception with the specified message and cause.
*
* @param message the message to use for this exception, may be null
* @param cause the cause of the exception, may be null
*/
public ZoneRulesException(String message, Throwable cause) {
super(message, cause);
}
}

View file

@ -0,0 +1,448 @@
/*
* Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Copyright (c) 2009-2012, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package java.time.zone;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.NavigableMap;
import java.util.Objects;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.Collections;
/**
* Provider of time-zone rules to the system.
* <p>
* This class manages the configuration of time-zone rules.
* The static methods provide the public API that can be used to manage the providers.
* The abstract methods provide the SPI that allows rules to be provided.
* <p>
* ZoneRulesProvider may be installed in an instance of the Java Platform as
* extension classes, that is, jar files placed into any of the usual extension
* directories. Installed providers are loaded using the service-provider loading
* facility defined by the {@link ServiceLoader} class. A ZoneRulesProvider
* identifies itself with a provider configuration file named
* {@code java.time.zone.ZoneRulesProvider} in the resource directory
* {@code META-INF/services}. The file should contain a line that specifies the
* fully qualified concrete zonerules-provider class name.
* Providers may also be made available by adding them to the class path or by
* registering themselves via {@link #registerProvider} method.
* <p>
* The Java virtual machine has a default provider that provides zone rules
* for the time-zones defined by IANA Time Zone Database (TZDB). If the system
* property {@code java.time.zone.DefaultZoneRulesProvider} is defined then
* it is taken to be the fully-qualified name of a concrete ZoneRulesProvider
* class to be loaded as the default provider, using the system class loader.
* If this system property is not defined, a system-default provider will be
* loaded to serve as the default provider.
* <p>
* Rules are looked up primarily by zone ID, as used by {@link ZoneId}.
* Only zone region IDs may be used, zone offset IDs are not used here.
* <p>
* Time-zone rules are political, thus the data can change at any time.
* Each provider will provide the latest rules for each zone ID, but they
* may also provide the history of how the rules changed.
*
* @implSpec
* This interface is a service provider that can be called by multiple threads.
* Implementations must be immutable and thread-safe.
* <p>
* Providers must ensure that once a rule has been seen by the application, the
* rule must continue to be available.
* <p>
* Providers are encouraged to implement a meaningful {@code toString} method.
* <p>
* Many systems would like to update time-zone rules dynamically without stopping the JVM.
* When examined in detail, this is a complex problem.
* Providers may choose to handle dynamic updates, however the default provider does not.
*
* @since 1.8
*/
public abstract class ZoneRulesProvider {
/**
* The set of loaded providers.
*/
private static final CopyOnWriteArrayList<ZoneRulesProvider> PROVIDERS = new CopyOnWriteArrayList<>();
/**
* The lookup from zone ID to provider.
*/
private static final ConcurrentMap<String, ZoneRulesProvider> ZONES = new ConcurrentHashMap<>(512, 0.75f, 2);
/**
* The zone ID data
*/
private static volatile Set<String> ZONE_IDS;
static {
// if the property java.time.zone.DefaultZoneRulesProvider is
// set then its value is the class name of the default provider
final List<ZoneRulesProvider> loaded = new ArrayList<>();
AccessController.doPrivileged(new PrivilegedAction<>() {
public Object run() {
String prop = System.getProperty("java.time.zone.DefaultZoneRulesProvider");
if (prop != null) {
try {
Class<?> c = Class.forName(prop, true, ClassLoader.getSystemClassLoader());
@SuppressWarnings("deprecation")
ZoneRulesProvider provider = ZoneRulesProvider.class.cast(c.newInstance());
registerProvider(provider);
loaded.add(provider);
} catch (Exception x) {
throw new Error(x);
}
} else {
registerProvider(new TzdbZoneRulesProvider());
}
return null;
}
});
ServiceLoader<ZoneRulesProvider> sl = ServiceLoader.load(ZoneRulesProvider.class, ClassLoader.getSystemClassLoader());
Iterator<ZoneRulesProvider> it = sl.iterator();
while (it.hasNext()) {
ZoneRulesProvider provider;
try {
provider = it.next();
} catch (ServiceConfigurationError ex) {
if (ex.getCause() instanceof SecurityException) {
continue; // ignore the security exception, try the next provider
}
throw ex;
}
boolean found = false;
for (ZoneRulesProvider p : loaded) {
if (p.getClass() == provider.getClass()) {
found = true;
}
}
if (!found) {
registerProvider0(provider);
loaded.add(provider);
}
}
// CopyOnWriteList could be slow if lots of providers and each added individually
PROVIDERS.addAll(loaded);
}
//-------------------------------------------------------------------------
/**
* Gets the set of available zone IDs.
* <p>
* These IDs are the string form of a {@link ZoneId}.
*
* @return the unmodifiable set of zone IDs, not null
*/
public static Set<String> getAvailableZoneIds() {
return ZONE_IDS;
}
/**
* Gets the rules for the zone ID.
* <p>
* This returns the latest available rules for the zone ID.
* <p>
* This method relies on time-zone data provider files that are configured.
* These are loaded using a {@code ServiceLoader}.
* <p>
* The caching flag is designed to allow provider implementations to
* prevent the rules being cached in {@code ZoneId}.
* Under normal circumstances, the caching of zone rules is highly desirable
* as it will provide greater performance. However, there is a use case where
* the caching would not be desirable, see {@link #provideRules}.
*
* @param zoneId the zone ID as defined by {@code ZoneId}, not null
* @param forCaching whether the rules are being queried for caching,
* true if the returned rules will be cached by {@code ZoneId},
* false if they will be returned to the user without being cached in {@code ZoneId}
* @return the rules, null if {@code forCaching} is true and this
* is a dynamic provider that wants to prevent caching in {@code ZoneId},
* otherwise not null
* @throws ZoneRulesException if rules cannot be obtained for the zone ID
*/
public static ZoneRules getRules(String zoneId, boolean forCaching) {
Objects.requireNonNull(zoneId, "zoneId");
return getProvider(zoneId).provideRules(zoneId, forCaching);
}
/**
* Gets the history of rules for the zone ID.
* <p>
* Time-zones are defined by governments and change frequently.
* This method allows applications to find the history of changes to the
* rules for a single zone ID. The map is keyed by a string, which is the
* version string associated with the rules.
* <p>
* The exact meaning and format of the version is provider specific.
* The version must follow lexicographical order, thus the returned map will
* be order from the oldest known rules to the newest available rules.
* The default 'TZDB' group uses version numbering consisting of the year
* followed by a letter, such as '2009e' or '2012f'.
* <p>
* Implementations must provide a result for each valid zone ID, however
* they do not have to provide a history of rules.
* Thus the map will always contain one element, and will only contain more
* than one element if historical rule information is available.
*
* @param zoneId the zone ID as defined by {@code ZoneId}, not null
* @return a modifiable copy of the history of the rules for the ID, sorted
* from oldest to newest, not null
* @throws ZoneRulesException if history cannot be obtained for the zone ID
*/
public static NavigableMap<String, ZoneRules> getVersions(String zoneId) {
Objects.requireNonNull(zoneId, "zoneId");
return getProvider(zoneId).provideVersions(zoneId);
}
/**
* Gets the provider for the zone ID.
*
* @param zoneId the zone ID as defined by {@code ZoneId}, not null
* @return the provider, not null
* @throws ZoneRulesException if the zone ID is unknown
*/
private static ZoneRulesProvider getProvider(String zoneId) {
ZoneRulesProvider provider = ZONES.get(zoneId);
if (provider == null) {
if (ZONES.isEmpty()) {
throw new ZoneRulesException("No time-zone data files registered");
}
throw new ZoneRulesException("Unknown time-zone ID: " + zoneId);
}
return provider;
}
//-------------------------------------------------------------------------
/**
* Registers a zone rules provider.
* <p>
* This adds a new provider to those currently available.
* A provider supplies rules for one or more zone IDs.
* A provider cannot be registered if it supplies a zone ID that has already been
* registered. See the notes on time-zone IDs in {@link ZoneId}, especially
* the section on using the concept of a "group" to make IDs unique.
* <p>
* To ensure the integrity of time-zones already created, there is no way
* to deregister providers.
*
* @param provider the provider to register, not null
* @throws ZoneRulesException if a zone ID is already registered
*/
public static void registerProvider(ZoneRulesProvider provider) {
Objects.requireNonNull(provider, "provider");
registerProvider0(provider);
PROVIDERS.add(provider);
}
/**
* Registers the provider.
*
* @param provider the provider to register, not null
* @throws ZoneRulesException if unable to complete the registration
*/
private static synchronized void registerProvider0(ZoneRulesProvider provider) {
for (String zoneId : provider.provideZoneIds()) {
Objects.requireNonNull(zoneId, "zoneId");
ZoneRulesProvider old = ZONES.putIfAbsent(zoneId, provider);
if (old != null) {
throw new ZoneRulesException(
"Unable to register zone as one already registered with that ID: " + zoneId +
", currently loading from provider: " + provider);
}
}
Set<String> combinedSet = new HashSet<String>(ZONES.keySet());
ZONE_IDS = Collections.unmodifiableSet(combinedSet);
}
/**
* Refreshes the rules from the underlying data provider.
* <p>
* This method allows an application to request that the providers check
* for any updates to the provided rules.
* After calling this method, the offset stored in any {@link ZonedDateTime}
* may be invalid for the zone ID.
* <p>
* Dynamic update of rules is a complex problem and most applications
* should not use this method or dynamic rules.
* To achieve dynamic rules, a provider implementation will have to be written
* as per the specification of this class.
* In addition, instances of {@code ZoneRules} must not be cached in the
* application as they will become stale. However, the boolean flag on
* {@link #provideRules(String, boolean)} allows provider implementations
* to control the caching of {@code ZoneId}, potentially ensuring that
* all objects in the system see the new rules.
* Note that there is likely to be a cost in performance of a dynamic rules
* provider. Note also that no dynamic rules provider is in this specification.
*
* @return true if the rules were updated
* @throws ZoneRulesException if an error occurs during the refresh
*/
public static boolean refresh() {
boolean changed = false;
for (ZoneRulesProvider provider : PROVIDERS) {
changed |= provider.provideRefresh();
}
return changed;
}
/**
* Constructor.
*/
protected ZoneRulesProvider() {
}
//-----------------------------------------------------------------------
/**
* SPI method to get the available zone IDs.
* <p>
* This obtains the IDs that this {@code ZoneRulesProvider} provides.
* A provider should provide data for at least one zone ID.
* <p>
* The returned zone IDs remain available and valid for the lifetime of the application.
* A dynamic provider may increase the set of IDs as more data becomes available.
*
* @return the set of zone IDs being provided, not null
* @throws ZoneRulesException if a problem occurs while providing the IDs
*/
protected abstract Set<String> provideZoneIds();
/**
* SPI method to get the rules for the zone ID.
* <p>
* This loads the rules for the specified zone ID.
* The provider implementation must validate that the zone ID is valid and
* available, throwing a {@code ZoneRulesException} if it is not.
* The result of the method in the valid case depends on the caching flag.
* <p>
* If the provider implementation is not dynamic, then the result of the
* method must be the non-null set of rules selected by the ID.
* <p>
* If the provider implementation is dynamic, then the flag gives the option
* of preventing the returned rules from being cached in {@link ZoneId}.
* When the flag is true, the provider is permitted to return null, where
* null will prevent the rules from being cached in {@code ZoneId}.
* When the flag is false, the provider must return non-null rules.
*
* @param zoneId the zone ID as defined by {@code ZoneId}, not null
* @param forCaching whether the rules are being queried for caching,
* true if the returned rules will be cached by {@code ZoneId},
* false if they will be returned to the user without being cached in {@code ZoneId}
* @return the rules, null if {@code forCaching} is true and this
* is a dynamic provider that wants to prevent caching in {@code ZoneId},
* otherwise not null
* @throws ZoneRulesException if rules cannot be obtained for the zone ID
*/
protected abstract ZoneRules provideRules(String zoneId, boolean forCaching);
/**
* SPI method to get the history of rules for the zone ID.
* <p>
* This returns a map of historical rules keyed by a version string.
* The exact meaning and format of the version is provider specific.
* The version must follow lexicographical order, thus the returned map will
* be order from the oldest known rules to the newest available rules.
* The default 'TZDB' group uses version numbering consisting of the year
* followed by a letter, such as '2009e' or '2012f'.
* <p>
* Implementations must provide a result for each valid zone ID, however
* they do not have to provide a history of rules.
* Thus the map will contain at least one element, and will only contain
* more than one element if historical rule information is available.
* <p>
* The returned versions remain available and valid for the lifetime of the application.
* A dynamic provider may increase the set of versions as more data becomes available.
*
* @param zoneId the zone ID as defined by {@code ZoneId}, not null
* @return a modifiable copy of the history of the rules for the ID, sorted
* from oldest to newest, not null
* @throws ZoneRulesException if history cannot be obtained for the zone ID
*/
protected abstract NavigableMap<String, ZoneRules> provideVersions(String zoneId);
/**
* SPI method to refresh the rules from the underlying data provider.
* <p>
* This method provides the opportunity for a provider to dynamically
* recheck the underlying data provider to find the latest rules.
* This could be used to load new rules without stopping the JVM.
* Dynamic behavior is entirely optional and most providers do not support it.
* <p>
* This implementation returns false.
*
* @return true if the rules were updated
* @throws ZoneRulesException if an error occurs during the refresh
*/
protected boolean provideRefresh() {
return false;
}
}

View file

@ -0,0 +1,86 @@
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* <p>
* Support for time-zones and their rules.
* </p>
* <p>
* Daylight Saving Time and Time-Zones are concepts used by Governments to alter local time.
* This package provides support for time-zones, their rules and the resulting
* gaps and overlaps in the local time-line typically caused by Daylight Saving Time.
* </p>
*
* <h3>Package specification</h3>
* <p>
* Unless otherwise noted, passing a null argument to a constructor or method in any class or interface
* in this package will cause a {@link java.lang.NullPointerException NullPointerException} to be thrown.
* The Javadoc "@param" definition is used to summarise the null-behavior.
* The "@throws {@link java.lang.NullPointerException}" is not explicitly documented in each method.
* </p>
* <p>
* All calculations should check for numeric overflow and throw either an {@link java.lang.ArithmeticException}
* or a {@link java.time.DateTimeException}.
* </p>
* @since 1.8
*/
package java.time.zone;