JapaneseEra.java revision 11361:28f3d0e8b4bd
1/*
2 * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26/*
27 * This file is available under and governed by the GNU General Public
28 * License version 2 only, as published by the Free Software Foundation.
29 * However, the following notice accompanied the original version of this
30 * file:
31 *
32 * Copyright (c) 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 */
62package java.time.chrono;
63
64import static java.time.chrono.JapaneseDate.MEIJI_6_ISODATE;
65import static java.time.temporal.ChronoField.ERA;
66
67import java.io.DataInput;
68import java.io.DataOutput;
69import java.io.IOException;
70import java.io.InvalidObjectException;
71import java.io.ObjectInputStream;
72import java.io.ObjectStreamException;
73import java.io.Serializable;
74import java.time.DateTimeException;
75import java.time.LocalDate;
76import java.time.temporal.ChronoField;
77import java.time.temporal.TemporalField;
78import java.time.temporal.UnsupportedTemporalTypeException;
79import java.time.temporal.ValueRange;
80import java.util.Arrays;
81import java.util.Objects;
82
83import sun.util.calendar.CalendarDate;
84
85/**
86 * An era in the Japanese Imperial calendar system.
87 * <p>
88 * This class defines the valid eras for the Japanese chronology.
89 * Japan introduced the Gregorian calendar starting with Meiji 6.
90 * Only Meiji and later eras are supported;
91 * dates before Meiji 6, January 1 are not supported.
92 *
93 * @implSpec
94 * This class is immutable and thread-safe.
95 *
96 * @since 1.8
97 */
98public final class JapaneseEra
99        implements Era, Serializable {
100
101    // The offset value to 0-based index from the era value.
102    // i.e., getValue() + ERA_OFFSET == 0-based index
103    static final int ERA_OFFSET = 2;
104
105    static final sun.util.calendar.Era[] ERA_CONFIG;
106
107    /**
108     * The singleton instance for the 'Meiji' era (1868-01-01 - 1912-07-29)
109     * which has the value -1.
110     */
111    public static final JapaneseEra MEIJI = new JapaneseEra(-1, LocalDate.of(1868, 1, 1));
112    /**
113     * The singleton instance for the 'Taisho' era (1912-07-30 - 1926-12-24)
114     * which has the value 0.
115     */
116    public static final JapaneseEra TAISHO = new JapaneseEra(0, LocalDate.of(1912, 7, 30));
117    /**
118     * The singleton instance for the 'Showa' era (1926-12-25 - 1989-01-07)
119     * which has the value 1.
120     */
121    public static final JapaneseEra SHOWA = new JapaneseEra(1, LocalDate.of(1926, 12, 25));
122    /**
123     * The singleton instance for the 'Heisei' era (1989-01-08 - current)
124     * which has the value 2.
125     */
126    public static final JapaneseEra HEISEI = new JapaneseEra(2, LocalDate.of(1989, 1, 8));
127
128    // the number of defined JapaneseEra constants.
129    // There could be an extra era defined in its configuration.
130    private static final int N_ERA_CONSTANTS = HEISEI.getValue() + ERA_OFFSET;
131
132    /**
133     * Serialization version.
134     */
135    private static final long serialVersionUID = 1466499369062886794L;
136
137    // array for the singleton JapaneseEra instances
138    private static final JapaneseEra[] KNOWN_ERAS;
139
140    static {
141        ERA_CONFIG = JapaneseChronology.JCAL.getEras();
142
143        KNOWN_ERAS = new JapaneseEra[ERA_CONFIG.length];
144        KNOWN_ERAS[0] = MEIJI;
145        KNOWN_ERAS[1] = TAISHO;
146        KNOWN_ERAS[2] = SHOWA;
147        KNOWN_ERAS[3] = HEISEI;
148        for (int i = N_ERA_CONSTANTS; i < ERA_CONFIG.length; i++) {
149            CalendarDate date = ERA_CONFIG[i].getSinceDate();
150            LocalDate isoDate = LocalDate.of(date.getYear(), date.getMonth(), date.getDayOfMonth());
151            KNOWN_ERAS[i] = new JapaneseEra(i - ERA_OFFSET + 1, isoDate);
152        }
153    };
154
155    /**
156     * The era value.
157     * @serial
158     */
159    private final transient int eraValue;
160
161    // the first day of the era
162    private final transient LocalDate since;
163
164    /**
165     * Creates an instance.
166     *
167     * @param eraValue  the era value, validated
168     * @param since  the date representing the first date of the era, validated not null
169     */
170    private JapaneseEra(int eraValue, LocalDate since) {
171        this.eraValue = eraValue;
172        this.since = since;
173    }
174
175    //-----------------------------------------------------------------------
176    /**
177     * Returns the Sun private Era instance corresponding to this {@code JapaneseEra}.
178     *
179     * @return the Sun private Era instance for this {@code JapaneseEra}.
180     */
181    sun.util.calendar.Era getPrivateEra() {
182        return ERA_CONFIG[ordinal(eraValue)];
183    }
184
185    //-----------------------------------------------------------------------
186    /**
187     * Obtains an instance of {@code JapaneseEra} from an {@code int} value.
188     * <p>
189     * The {@link #SHOWA} era that contains 1970-01-01 (ISO calendar system) has the value 1
190     * Later era is numbered 2 ({@link #HEISEI}). Earlier eras are numbered 0 ({@link #TAISHO}),
191     * -1 ({@link #MEIJI}), only Meiji and later eras are supported.
192     *
193     * @param japaneseEra  the era to represent
194     * @return the {@code JapaneseEra} singleton, not null
195     * @throws DateTimeException if the value is invalid
196     */
197    public static JapaneseEra of(int japaneseEra) {
198        int i = ordinal(japaneseEra);
199        if (i < 0 || i >= KNOWN_ERAS.length) {
200            throw new DateTimeException("Invalid era: " + japaneseEra);
201        }
202        return KNOWN_ERAS[i];
203    }
204
205    /**
206     * Returns the {@code JapaneseEra} with the name.
207     * <p>
208     * The string must match exactly the name of the era.
209     * (Extraneous whitespace characters are not permitted.)
210     *
211     * @param japaneseEra  the japaneseEra name; non-null
212     * @return the {@code JapaneseEra} singleton, never null
213     * @throws IllegalArgumentException if there is not JapaneseEra with the specified name
214     */
215    public static JapaneseEra valueOf(String japaneseEra) {
216        Objects.requireNonNull(japaneseEra, "japaneseEra");
217        for (JapaneseEra era : KNOWN_ERAS) {
218            if (era.getName().equals(japaneseEra)) {
219                return era;
220            }
221        }
222        throw new IllegalArgumentException("japaneseEra is invalid");
223    }
224
225    /**
226     * Returns an array of JapaneseEras.
227     * <p>
228     * This method may be used to iterate over the JapaneseEras as follows:
229     * <pre>
230     * for (JapaneseEra c : JapaneseEra.values())
231     *     System.out.println(c);
232     * </pre>
233     *
234     * @return an array of JapaneseEras
235     */
236    public static JapaneseEra[] values() {
237        return Arrays.copyOf(KNOWN_ERAS, KNOWN_ERAS.length);
238    }
239
240    //-----------------------------------------------------------------------
241    /**
242     * Obtains an instance of {@code JapaneseEra} from a date.
243     *
244     * @param date  the date, not null
245     * @return the Era singleton, never null
246     */
247    static JapaneseEra from(LocalDate date) {
248        if (date.isBefore(MEIJI_6_ISODATE)) {
249            throw new DateTimeException("JapaneseDate before Meiji 6 are not supported");
250        }
251        for (int i = KNOWN_ERAS.length - 1; i > 0; i--) {
252            JapaneseEra era = KNOWN_ERAS[i];
253            if (date.compareTo(era.since) >= 0) {
254                return era;
255            }
256        }
257        return null;
258    }
259
260    static JapaneseEra toJapaneseEra(sun.util.calendar.Era privateEra) {
261        for (int i = ERA_CONFIG.length - 1; i >= 0; i--) {
262            if (ERA_CONFIG[i].equals(privateEra)) {
263                return KNOWN_ERAS[i];
264            }
265        }
266        return null;
267    }
268
269    static sun.util.calendar.Era privateEraFrom(LocalDate isoDate) {
270        for (int i = KNOWN_ERAS.length - 1; i > 0; i--) {
271            JapaneseEra era = KNOWN_ERAS[i];
272            if (isoDate.compareTo(era.since) >= 0) {
273                return ERA_CONFIG[i];
274            }
275        }
276        return null;
277    }
278
279    /**
280     * Returns the index into the arrays from the Era value.
281     * the eraValue is a valid Era number, -1..2.
282     *
283     * @param eraValue  the era value to convert to the index
284     * @return the index of the current Era
285     */
286    private static int ordinal(int eraValue) {
287        return eraValue + ERA_OFFSET - 1;
288    }
289
290    //-----------------------------------------------------------------------
291    /**
292     * Gets the numeric era {@code int} value.
293     * <p>
294     * The {@link #SHOWA} era that contains 1970-01-01 (ISO calendar system) has the value 1.
295     * Later eras are numbered from 2 ({@link #HEISEI}).
296     * Earlier eras are numbered 0 ({@link #TAISHO}), -1 ({@link #MEIJI})).
297     *
298     * @return the era value
299     */
300    @Override
301    public int getValue() {
302        return eraValue;
303    }
304
305    //-----------------------------------------------------------------------
306    /**
307     * Gets the range of valid values for the specified field.
308     * <p>
309     * The range object expresses the minimum and maximum valid values for a field.
310     * This era is used to enhance the accuracy of the returned range.
311     * If it is not possible to return the range, because the field is not supported
312     * or for some other reason, an exception is thrown.
313     * <p>
314     * If the field is a {@link ChronoField} then the query is implemented here.
315     * The {@code ERA} field returns the range.
316     * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
317     * <p>
318     * If the field is not a {@code ChronoField}, then the result of this method
319     * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
320     * passing {@code this} as the argument.
321     * Whether the range can be obtained is determined by the field.
322     * <p>
323     * The range of valid Japanese eras can change over time due to the nature
324     * of the Japanese calendar system.
325     *
326     * @param field  the field to query the range for, not null
327     * @return the range of valid values for the field, not null
328     * @throws DateTimeException if the range for the field cannot be obtained
329     * @throws UnsupportedTemporalTypeException if the unit is not supported
330     */
331    @Override  // override as super would return range from 0 to 1
332    public ValueRange range(TemporalField field) {
333        if (field == ERA) {
334            return JapaneseChronology.INSTANCE.range(ERA);
335        }
336        return Era.super.range(field);
337    }
338
339    //-----------------------------------------------------------------------
340    String getAbbreviation() {
341        int index = ordinal(getValue());
342        if (index == 0) {
343            return "";
344        }
345        return ERA_CONFIG[index].getAbbreviation();
346    }
347
348    String getName() {
349        return ERA_CONFIG[ordinal(getValue())].getName();
350    }
351
352    @Override
353    public String toString() {
354        return getName();
355    }
356
357    //-----------------------------------------------------------------------
358    /**
359     * Defend against malicious streams.
360     *
361     * @param s the stream to read
362     * @throws InvalidObjectException always
363     */
364    private void readObject(ObjectInputStream s) throws InvalidObjectException {
365        throw new InvalidObjectException("Deserialization via serialization delegate");
366    }
367
368    //-----------------------------------------------------------------------
369    /**
370     * Writes the object using a
371     * <a href="../../../serialized-form.html#java.time.chrono.Ser">dedicated serialized form</a>.
372     * @serialData
373     * <pre>
374     *  out.writeByte(5);        // identifies a JapaneseEra
375     *  out.writeInt(getValue());
376     * </pre>
377     *
378     * @return the instance of {@code Ser}, not null
379     */
380    private Object writeReplace() {
381        return new Ser(Ser.JAPANESE_ERA_TYPE, this);
382    }
383
384    void writeExternal(DataOutput out) throws IOException {
385        out.writeByte(this.getValue());
386    }
387
388    static JapaneseEra readExternal(DataInput in) throws IOException {
389        byte eraValue = in.readByte();
390        return JapaneseEra.of(eraValue);
391    }
392
393}
394