Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/time/chrono/JapaneseEra.java
38918 views
/*1* Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* This file is available under and governed by the GNU General Public27* License version 2 only, as published by the Free Software Foundation.28* However, the following notice accompanied the original version of this29* file:30*31* Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos32*33* All rights reserved.34*35* Redistribution and use in source and binary forms, with or without36* modification, are permitted provided that the following conditions are met:37*38* * Redistributions of source code must retain the above copyright notice,39* this list of conditions and the following disclaimer.40*41* * Redistributions in binary form must reproduce the above copyright notice,42* this list of conditions and the following disclaimer in the documentation43* and/or other materials provided with the distribution.44*45* * Neither the name of JSR-310 nor the names of its contributors46* may be used to endorse or promote products derived from this software47* without specific prior written permission.48*49* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS50* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT51* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR52* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR53* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,54* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,55* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR56* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF57* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING58* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS59* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.60*/61package java.time.chrono;6263import static java.time.chrono.JapaneseDate.MEIJI_6_ISODATE;64import static java.time.temporal.ChronoField.ERA;6566import java.io.DataInput;67import java.io.DataOutput;68import java.io.IOException;69import java.io.InvalidObjectException;70import java.io.ObjectInputStream;71import java.io.ObjectStreamException;72import java.io.Serializable;73import java.time.DateTimeException;74import java.time.LocalDate;75import java.time.format.DateTimeFormatterBuilder;76import java.time.format.TextStyle;77import java.time.temporal.ChronoField;78import java.time.temporal.TemporalField;79import java.time.temporal.UnsupportedTemporalTypeException;80import java.time.temporal.ValueRange;81import java.util.Arrays;82import java.util.Locale;83import java.util.Objects;8485import sun.util.calendar.CalendarDate;8687/**88* An era in the Japanese Imperial calendar system.89* <p>90* The Japanese government defines the official name and start date of91* each era. Eras are consecutive and their date ranges do not overlap,92* so the end date of one era is always the day before the start date93* of the next era.94* <p>95* The Java SE Platform supports all eras defined by the Japanese government,96* beginning with the Meiji era. Each era is identified in the Platform by an97* integer value and a name. The {@link #of(int)} and {@link #valueOf(String)}98* methods may be used to obtain a singleton instance of JapaneseEra for each99* era. The {@link #values()} method returns the singleton instances of all100* supported eras.101* <p>102* For convenience, this class declares a number of public static final fields103* that refer to singleton instances returned by the values() method.104*105* @apiNote106* The fields declared in this class may evolve over time, in line with the107* results of the {@link #values()} method. However, there is not necessarily108* a 1:1 correspondence between the fields and the singleton instances.109*110* @apiNote111* The Japanese government may announce a new era and define its start112* date but not its official name. In this scenario, the singleton instance113* that represents the new era may return a name that is not stable until114* the official name is defined. Developers should exercise caution when115* relying on the name returned by any singleton instance that does not116* correspond to a public static final field.117*118* @implSpec119* This class is immutable and thread-safe.120*121* @since 1.8122*/123public final class JapaneseEra124implements Era, Serializable {125126// The offset value to 0-based index from the era value.127// i.e., getValue() + ERA_OFFSET == 0-based index128static final int ERA_OFFSET = 2;129130static final sun.util.calendar.Era[] ERA_CONFIG;131132/**133* The singleton instance for the 'Meiji' era (1868-01-01 - 1912-07-29)134* which has the value -1.135*/136public static final JapaneseEra MEIJI = new JapaneseEra(-1, LocalDate.of(1868, 1, 1));137/**138* The singleton instance for the 'Taisho' era (1912-07-30 - 1926-12-24)139* which has the value 0.140*/141public static final JapaneseEra TAISHO = new JapaneseEra(0, LocalDate.of(1912, 7, 30));142/**143* The singleton instance for the 'Showa' era (1926-12-25 - 1989-01-07)144* which has the value 1.145*/146public static final JapaneseEra SHOWA = new JapaneseEra(1, LocalDate.of(1926, 12, 25));147/**148* The singleton instance for the 'Heisei' era (1989-01-08 - 2019-04-30)149* which has the value 2.150*/151public static final JapaneseEra HEISEI = new JapaneseEra(2, LocalDate.of(1989, 1, 8));152/**153* The singleton instance for the 'Reiwa' era (2019-05-01 - )154* which has the value 3.155*/156private static final JapaneseEra REIWA = new JapaneseEra(3, LocalDate.of(2019, 5, 1));157158// The number of predefined JapaneseEra constants.159// There may be a supplemental era defined by the property.160private static final int N_ERA_CONSTANTS = REIWA.getValue() + ERA_OFFSET;161162/**163* Serialization version.164*/165private static final long serialVersionUID = 1466499369062886794L;166167// array for the singleton JapaneseEra instances168private static final JapaneseEra[] KNOWN_ERAS;169170static {171ERA_CONFIG = JapaneseChronology.JCAL.getEras();172173KNOWN_ERAS = new JapaneseEra[ERA_CONFIG.length];174KNOWN_ERAS[0] = MEIJI;175KNOWN_ERAS[1] = TAISHO;176KNOWN_ERAS[2] = SHOWA;177KNOWN_ERAS[3] = HEISEI;178KNOWN_ERAS[4] = REIWA;179for (int i = N_ERA_CONSTANTS; i < ERA_CONFIG.length; i++) {180CalendarDate date = ERA_CONFIG[i].getSinceDate();181LocalDate isoDate = LocalDate.of(date.getYear(), date.getMonth(), date.getDayOfMonth());182KNOWN_ERAS[i] = new JapaneseEra(i - ERA_OFFSET + 1, isoDate);183}184};185186/**187* The era value.188* @serial189*/190private final transient int eraValue;191192// the first day of the era193private final transient LocalDate since;194195/**196* Creates an instance.197*198* @param eraValue the era value, validated199* @param since the date representing the first date of the era, validated not null200*/201private JapaneseEra(int eraValue, LocalDate since) {202this.eraValue = eraValue;203this.since = since;204}205206//-----------------------------------------------------------------------207/**208* Returns the Sun private Era instance corresponding to this {@code JapaneseEra}.209*210* @return the Sun private Era instance for this {@code JapaneseEra}.211*/212sun.util.calendar.Era getPrivateEra() {213return ERA_CONFIG[ordinal(eraValue)];214}215216//-----------------------------------------------------------------------217/**218* Obtains an instance of {@code JapaneseEra} from an {@code int} value.219* <ul>220* <li>The value {@code 1} is associated with the 'Showa' era, because221* it contains 1970-01-01 (ISO calendar system).</li>222* <li>The values {@code -1} and {@code 0} are associated with two earlier223* eras, Meiji and Taisho, respectively.</li>224* <li>A value greater than {@code 1} is associated with a later era,225* beginning with Heisei ({@code 2}).</li>226* </ul>227* <p>228* Every instance of {@code JapaneseEra} that is returned from the {@link values()}229* method has an int value (available via {@link Era#getValue()} which is230* accepted by this method.231*232* @param japaneseEra the era to represent233* @return the {@code JapaneseEra} singleton, not null234* @throws DateTimeException if the value is invalid235*/236public static JapaneseEra of(int japaneseEra) {237if (japaneseEra < MEIJI.eraValue || japaneseEra + ERA_OFFSET > KNOWN_ERAS.length) {238throw new DateTimeException("Invalid era: " + japaneseEra);239}240return KNOWN_ERAS[ordinal(japaneseEra)];241}242243/**244* Returns the {@code JapaneseEra} with the name.245* <p>246* The string must match exactly the name of the era.247* (Extraneous whitespace characters are not permitted.)248*249* @param japaneseEra the japaneseEra name; non-null250* @return the {@code JapaneseEra} singleton, never null251* @throws IllegalArgumentException if there is not JapaneseEra with the specified name252*/253public static JapaneseEra valueOf(String japaneseEra) {254Objects.requireNonNull(japaneseEra, "japaneseEra");255for (JapaneseEra era : KNOWN_ERAS) {256if (era.getName().equals(japaneseEra)) {257return era;258}259}260throw new IllegalArgumentException("japaneseEra is invalid");261}262263/**264* Returns an array of JapaneseEras.265* <p>266* This method may be used to iterate over the JapaneseEras as follows:267* <pre>268* for (JapaneseEra c : JapaneseEra.values())269* System.out.println(c);270* </pre>271*272* @return an array of JapaneseEras273*/274public static JapaneseEra[] values() {275return Arrays.copyOf(KNOWN_ERAS, KNOWN_ERAS.length);276}277278/**279* {@inheritDoc}280*281* @param style {@inheritDoc}282* @param locale {@inheritDoc}283*/284@Override285public String getDisplayName(TextStyle style, Locale locale) {286// If this JapaneseEra is a supplemental one, obtain the name from287// the era definition.288if (getValue() > N_ERA_CONSTANTS - ERA_OFFSET) {289Objects.requireNonNull(locale, "locale");290return style.asNormal() == TextStyle.NARROW ? getAbbreviation() : getName();291}292293return new DateTimeFormatterBuilder()294.appendText(ERA, style)295.toFormatter(locale)296.withChronology(JapaneseChronology.INSTANCE)297.format(this == MEIJI ? MEIJI_6_ISODATE : since);298}299300//-----------------------------------------------------------------------301/**302* Obtains an instance of {@code JapaneseEra} from a date.303*304* @param date the date, not null305* @return the Era singleton, never null306*/307static JapaneseEra from(LocalDate date) {308if (date.isBefore(MEIJI_6_ISODATE)) {309throw new DateTimeException("JapaneseDate before Meiji 6 are not supported");310}311for (int i = KNOWN_ERAS.length - 1; i > 0; i--) {312JapaneseEra era = KNOWN_ERAS[i];313if (date.compareTo(era.since) >= 0) {314return era;315}316}317return null;318}319320static JapaneseEra toJapaneseEra(sun.util.calendar.Era privateEra) {321for (int i = ERA_CONFIG.length - 1; i >= 0; i--) {322if (ERA_CONFIG[i].equals(privateEra)) {323return KNOWN_ERAS[i];324}325}326return null;327}328329static sun.util.calendar.Era privateEraFrom(LocalDate isoDate) {330for (int i = KNOWN_ERAS.length - 1; i > 0; i--) {331JapaneseEra era = KNOWN_ERAS[i];332if (isoDate.compareTo(era.since) >= 0) {333return ERA_CONFIG[i];334}335}336return null;337}338339/**340* Returns the index into the arrays from the Era value.341* the eraValue is a valid Era number, -1..2.342*343* @param eraValue the era value to convert to the index344* @return the index of the current Era345*/346private static int ordinal(int eraValue) {347return eraValue + ERA_OFFSET - 1;348}349350//-----------------------------------------------------------------------351/**352* Gets the numeric era {@code int} value.353* <p>354* The {@link #SHOWA} era that contains 1970-01-01 (ISO calendar system) has the value 1.355* Later eras are numbered from 2 ({@link #HEISEI}).356* Earlier eras are numbered 0 ({@link #TAISHO}), -1 ({@link #MEIJI})).357*358* @return the era value359*/360@Override361public int getValue() {362return eraValue;363}364365//-----------------------------------------------------------------------366/**367* Gets the range of valid values for the specified field.368* <p>369* The range object expresses the minimum and maximum valid values for a field.370* This era is used to enhance the accuracy of the returned range.371* If it is not possible to return the range, because the field is not supported372* or for some other reason, an exception is thrown.373* <p>374* If the field is a {@link ChronoField} then the query is implemented here.375* The {@code ERA} field returns the range.376* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.377* <p>378* If the field is not a {@code ChronoField}, then the result of this method379* is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}380* passing {@code this} as the argument.381* Whether the range can be obtained is determined by the field.382* <p>383* The range of valid Japanese eras can change over time due to the nature384* of the Japanese calendar system.385*386* @param field the field to query the range for, not null387* @return the range of valid values for the field, not null388* @throws DateTimeException if the range for the field cannot be obtained389* @throws UnsupportedTemporalTypeException if the unit is not supported390*/391@Override // override as super would return range from 0 to 1392public ValueRange range(TemporalField field) {393if (field == ERA) {394return JapaneseChronology.INSTANCE.range(ERA);395}396return Era.super.range(field);397}398399//-----------------------------------------------------------------------400String getAbbreviation() {401return ERA_CONFIG[ordinal(getValue())].getAbbreviation();402}403404String getName() {405return ERA_CONFIG[ordinal(getValue())].getName();406}407408@Override409public String toString() {410return getName();411}412413//-----------------------------------------------------------------------414/**415* Defend against malicious streams.416*417* @param s the stream to read418* @throws InvalidObjectException always419*/420private void readObject(ObjectInputStream s) throws InvalidObjectException {421throw new InvalidObjectException("Deserialization via serialization delegate");422}423424//-----------------------------------------------------------------------425/**426* Writes the object using a427* <a href="../../../serialized-form.html#java.time.chrono.Ser">dedicated serialized form</a>.428* @serialData429* <pre>430* out.writeByte(5); // identifies a JapaneseEra431* out.writeInt(getValue());432* </pre>433*434* @return the instance of {@code Ser}, not null435*/436private Object writeReplace() {437return new Ser(Ser.JAPANESE_ERA_TYPE, this);438}439440void writeExternal(DataOutput out) throws IOException {441out.writeByte(this.getValue());442}443444static JapaneseEra readExternal(DataInput in) throws IOException {445byte eraValue = in.readByte();446return JapaneseEra.of(eraValue);447}448449}450451452