1 /*
2  * Copyright (c) 2012, 2019, 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) 2011-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.Externalizable;
67 import java.io.IOException;
68 import java.io.InvalidClassException;
69 import java.io.ObjectInput;
70 import java.io.ObjectOutput;
71 import java.io.Serializable;
72 import java.io.StreamCorruptedException;
73 import java.time.ZoneOffset;
74 
75 /**
76  * The shared serialization delegate for this package.
77  *
78  * @implNote
79  * This class is mutable and should be created once per serialization.
80  *
81  * @serial include
82  * @since 1.8
83  */
84 final class Ser implements Externalizable {
85 
86     /**
87      * Serialization version.
88      */
89     private static final long serialVersionUID = -8885321777449118786L;
90 
91     /** Type for ZoneRules. */
92     static final byte ZRULES = 1;
93     /** Type for ZoneOffsetTransition. */
94     static final byte ZOT = 2;
95     /** Type for ZoneOffsetTransitionRule. */
96     static final byte ZOTRULE = 3;
97 
98     /** The type being serialized. */
99     private byte type;
100     /** The object being serialized. */
101     private Serializable object;
102 
103     /**
104      * Constructor for deserialization.
105      */
Ser()106     public Ser() {
107     }
108 
109     /**
110      * Creates an instance for serialization.
111      *
112      * @param type  the type
113      * @param object  the object
114      */
Ser(byte type, Serializable object)115     Ser(byte type, Serializable object) {
116         this.type = type;
117         this.object = object;
118     }
119 
120     //-----------------------------------------------------------------------
121     /**
122      * Implements the {@code Externalizable} interface to write the object.
123      * @serialData
124      * Each serializable class is mapped to a type that is the first byte
125      * in the stream.  Refer to each class {@code writeReplace}
126      * serialized form for the value of the type and sequence of values for the type.
127      *
128      * <ul>
129      * <li><a href="{@docRoot}/serialized-form.html#java.time.zone.ZoneRules">ZoneRules.writeReplace</a>
130      * <li><a href="{@docRoot}/serialized-form.html#java.time.zone.ZoneOffsetTransition">ZoneOffsetTransition.writeReplace</a>
131      * <li><a href="{@docRoot}/serialized-form.html#java.time.zone.ZoneOffsetTransitionRule">ZoneOffsetTransitionRule.writeReplace</a>
132      * </ul>
133      *
134      * @param out  the data stream to write to, not null
135      */
136     @Override
writeExternal(ObjectOutput out)137     public void writeExternal(ObjectOutput out) throws IOException {
138         writeInternal(type, object, out);
139     }
140 
write(Object object, DataOutput out)141     static void write(Object object, DataOutput out) throws IOException {
142         writeInternal(ZRULES, object, out);
143     }
144 
writeInternal(byte type, Object object, DataOutput out)145     private static void writeInternal(byte type, Object object, DataOutput out) throws IOException {
146         out.writeByte(type);
147         switch (type) {
148             case ZRULES:
149                 ((ZoneRules) object).writeExternal(out);
150                 break;
151             case ZOT:
152                 ((ZoneOffsetTransition) object).writeExternal(out);
153                 break;
154             case ZOTRULE:
155                 ((ZoneOffsetTransitionRule) object).writeExternal(out);
156                 break;
157             default:
158                 throw new InvalidClassException("Unknown serialized type");
159         }
160     }
161 
162     //-----------------------------------------------------------------------
163     /**
164      * Implements the {@code Externalizable} interface to read the object.
165      * @serialData
166      * The streamed type and parameters defined by the type's {@code writeReplace}
167      * method are read and passed to the corresponding static factory for the type
168      * to create a new instance.  That instance is returned as the de-serialized
169      * {@code Ser} object.
170      *
171      * <ul>
172      * <li><a href="{@docRoot}/serialized-form.html#java.time.zone.ZoneRules">ZoneRules</a>
173      * - {@code ZoneRules.of(standardTransitions, standardOffsets, savingsInstantTransitions, wallOffsets, lastRules);}
174      * <li><a href="{@docRoot}/serialized-form.html#java.time.zone.ZoneOffsetTransition">ZoneOffsetTransition</a>
175      * - {@code ZoneOffsetTransition of(LocalDateTime.ofEpochSecond(epochSecond), offsetBefore, offsetAfter);}
176      * <li><a href="{@docRoot}/serialized-form.html#java.time.zone.ZoneOffsetTransitionRule">ZoneOffsetTransitionRule</a>
177      * - {@code ZoneOffsetTransitionRule.of(month, dom, dow, time, timeEndOfDay, timeDefinition, standardOffset, offsetBefore, offsetAfter);}
178      * </ul>
179      * @param in  the data to read, not null
180      */
181     @Override
readExternal(ObjectInput in)182     public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
183         type = in.readByte();
184         object = readInternal(type, in);
185     }
186 
read(DataInput in)187     static Serializable read(DataInput in) throws IOException, ClassNotFoundException {
188         byte type = in.readByte();
189         return readInternal(type, in);
190     }
191 
readInternal(byte type, DataInput in)192     private static Serializable readInternal(byte type, DataInput in)
193             throws IOException, ClassNotFoundException {
194         switch (type) {
195             case ZRULES:
196                 return ZoneRules.readExternal(in);
197             case ZOT:
198                 return ZoneOffsetTransition.readExternal(in);
199             case ZOTRULE:
200                 return ZoneOffsetTransitionRule.readExternal(in);
201             default:
202                 throw new StreamCorruptedException("Unknown serialized type");
203         }
204     }
205 
206     /**
207      * Returns the object that will replace this one.
208      *
209      * @return the read object, should never be null
210      */
readResolve()211     private Object readResolve() {
212          return object;
213     }
214 
215     //-----------------------------------------------------------------------
216     /**
217      * Writes the state to the stream.
218      *
219      * @param offset  the offset, not null
220      * @param out  the output stream, not null
221      * @throws IOException if an error occurs
222      */
writeOffset(ZoneOffset offset, DataOutput out)223     static void writeOffset(ZoneOffset offset, DataOutput out) throws IOException {
224         final int offsetSecs = offset.getTotalSeconds();
225         int offsetByte = offsetSecs % 900 == 0 ? offsetSecs / 900 : 127;  // compress to -72 to +72
226         out.writeByte(offsetByte);
227         if (offsetByte == 127) {
228             out.writeInt(offsetSecs);
229         }
230     }
231 
232     /**
233      * Reads the state from the stream.
234      *
235      * @param in  the input stream, not null
236      * @return the created object, not null
237      * @throws IOException if an error occurs
238      */
readOffset(DataInput in)239     static ZoneOffset readOffset(DataInput in) throws IOException {
240         int offsetByte = in.readByte();
241         return (offsetByte == 127 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(offsetByte * 900));
242     }
243 
244     //-----------------------------------------------------------------------
245     /**
246      * Writes the state to the stream.
247      *
248      * @param epochSec  the epoch seconds, not null
249      * @param out  the output stream, not null
250      * @throws IOException if an error occurs
251      */
writeEpochSec(long epochSec, DataOutput out)252     static void writeEpochSec(long epochSec, DataOutput out) throws IOException {
253         if (epochSec >= -4575744000L && epochSec < 10413792000L && epochSec % 900 == 0) {  // quarter hours between 1825 and 2300
254             int store = (int) ((epochSec + 4575744000L) / 900);
255             out.writeByte((store >>> 16) & 255);
256             out.writeByte((store >>> 8) & 255);
257             out.writeByte(store & 255);
258         } else {
259             out.writeByte(255);
260             out.writeLong(epochSec);
261         }
262     }
263 
264     /**
265      * Reads the state from the stream.
266      *
267      * @param in  the input stream, not null
268      * @return the epoch seconds, not null
269      * @throws IOException if an error occurs
270      */
readEpochSec(DataInput in)271     static long readEpochSec(DataInput in) throws IOException {
272         int hiByte = in.readByte() & 255;
273         if (hiByte == 255) {
274             return in.readLong();
275         } else {
276             int midByte = in.readByte() & 255;
277             int loByte = in.readByte() & 255;
278             long tot = ((hiByte << 16) + (midByte << 8) + loByte);
279             return (tot * 900) - 4575744000L;
280         }
281     }
282 
283 }
284