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) 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.chrono;
  63 
  64 import static java.time.chrono.JapaneseDate.MEIJI_6_ISODATE;
  65 import static java.time.temporal.ChronoField.ERA;
  66 
  67 import java.io.DataInput;
  68 import java.io.DataOutput;
  69 import java.io.IOException;
  70 import java.io.InvalidObjectException;
  71 import java.io.ObjectInputStream;
  72 import java.io.ObjectStreamException;
  73 import java.io.Serializable;
  74 import java.time.DateTimeException;
  75 import java.time.LocalDate;
  76 import java.time.format.DateTimeFormatterBuilder;
  77 import java.time.format.TextStyle;
  78 import java.time.temporal.ChronoField;
  79 import java.time.temporal.TemporalField;
  80 import java.time.temporal.UnsupportedTemporalTypeException;
  81 import java.time.temporal.ValueRange;
  82 import java.util.Arrays;
  83 import java.util.Locale;
  84 import java.util.Objects;
  85 
  86 import sun.util.calendar.CalendarDate;
  87 
  88 /**
  89  * An era in the Japanese Imperial calendar system.
  90  * <p>
  91  * The Japanese government defines the official name and start date of
  92  * each era. Eras are consecutive and their date ranges do not overlap,
  93  * so the end date of one era is always the day before the start date
  94  * of the next era.
  95  * <p>
  96  * The Java SE Platform supports all eras defined by the Japanese government,
  97  * beginning with the Meiji era. Each era is identified in the Platform by an
  98  * integer value and a name. The {@link #of(int)} and {@link #valueOf(String)}
  99  * methods may be used to obtain a singleton instance of {@code JapaneseEra}
 100  * for each era. The {@link #values()} method returns the singleton instances
 101  * of all supported eras.
 102  * <p>
 103  * For convenience, this class declares a number of public static final fields
 104  * that refer to singleton instances returned by the {@link #values()} method.
 105  *
 106  * @apiNote
 107  * The fields declared in this class may evolve over time, in line with the
 108  * results of the {@link #values()} method. However, there is not necessarily
 109  * a 1:1 correspondence between the fields and the singleton instances.
 110  *
 111  * @apiNote
 112  * The Japanese government may announce a new era and define its start
 113  * date but not its official name. In this scenario, the singleton instance
 114  * that represents the new era may return a name that is not stable until
 115  * the official name is defined. Developers should exercise caution when
 116  * relying on the name returned by any singleton instance that does not
 117  * correspond to a public static final field.
 118  *
 119  * @implSpec
 120  * This class is immutable and thread-safe.
 121  *
 122  * @since 1.8
 123  */
 124 public final class JapaneseEra
 125         implements Era, Serializable {
 126 
 127     // The offset value to 0-based index from the era value.
 128     // i.e., getValue() + ERA_OFFSET == 0-based index
 129     static final int ERA_OFFSET = 2;
 130 
 131     static final sun.util.calendar.Era[] ERA_CONFIG;
 132 
 133     /**
 134      * The singleton instance for the 'Meiji' era (1868-01-01 - 1912-07-29)
 135      * which has the value -1.
 136      */
 137     public static final JapaneseEra MEIJI = new JapaneseEra(-1, LocalDate.of(1868, 1, 1));
 138     /**
 139      * The singleton instance for the 'Taisho' era (1912-07-30 - 1926-12-24)
 140      * which has the value 0.
 141      */
 142     public static final JapaneseEra TAISHO = new JapaneseEra(0, LocalDate.of(1912, 7, 30));
 143     /**
 144      * The singleton instance for the 'Showa' era (1926-12-25 - 1989-01-07)
 145      * which has the value 1.
 146      */
 147     public static final JapaneseEra SHOWA = new JapaneseEra(1, LocalDate.of(1926, 12, 25));
 148     /**
 149      * The singleton instance for the 'Heisei' era (1989-01-08 - 2019-04-30)
 150      * which has the value 2.
 151      */
 152     public static final JapaneseEra HEISEI = new JapaneseEra(2, LocalDate.of(1989, 1, 8));
 153     /**
 154      * The singleton instance for the 'Reiwa' era (2019-05-01 - )
 155      * which has the value 3. The end date of this era is not specified, unless
 156      * the Japanese Government defines it.
 157      *
 158      * @since 13
 159      */
 160     public static final JapaneseEra REIWA = new JapaneseEra(3, LocalDate.of(2019, 5, 1));
 161 
 162     // The number of predefined JapaneseEra constants.
 163     // There may be a supplemental era defined by the property.
 164     private static final int N_ERA_CONSTANTS = REIWA.getValue() + ERA_OFFSET;
 165 
 166     /**
 167      * Serialization version.
 168      */
 169     private static final long serialVersionUID = 1466499369062886794L;
 170 
 171     // array for the singleton JapaneseEra instances
 172     private static final JapaneseEra[] KNOWN_ERAS;
 173 
 174     static {
 175         ERA_CONFIG = JapaneseChronology.JCAL.getEras();
 176 
 177         KNOWN_ERAS = new JapaneseEra[ERA_CONFIG.length];
 178         KNOWN_ERAS[0] = MEIJI;
 179         KNOWN_ERAS[1] = TAISHO;
 180         KNOWN_ERAS[2] = SHOWA;
 181         KNOWN_ERAS[3] = HEISEI;
 182         KNOWN_ERAS[4] = REIWA;
 183         for (int i = N_ERA_CONSTANTS; i < ERA_CONFIG.length; i++) {
 184             CalendarDate date = ERA_CONFIG[i].getSinceDate();
 185             LocalDate isoDate = LocalDate.of(date.getYear(), date.getMonth(), date.getDayOfMonth());
 186             KNOWN_ERAS[i] = new JapaneseEra(i - ERA_OFFSET + 1, isoDate);
 187         }
 188     };
 189 
 190     /**
 191      * The era value.
 192      * @serial
 193      */
 194     private final transient int eraValue;
 195 
 196     // the first day of the era
 197     private final transient LocalDate since;
 198 
 199     /**
 200      * Creates an instance.
 201      *
 202      * @param eraValue  the era value, validated
 203      * @param since  the date representing the first date of the era, validated not null
 204      */
 205     private JapaneseEra(int eraValue, LocalDate since) {
 206         this.eraValue = eraValue;
 207         this.since = since;
 208     }
 209 
 210     //-----------------------------------------------------------------------
 211     /**
 212      * Returns the Sun private Era instance corresponding to this {@code JapaneseEra}.
 213      *
 214      * @return the Sun private Era instance for this {@code JapaneseEra}.
 215      */
 216     sun.util.calendar.Era getPrivateEra() {
 217         return ERA_CONFIG[ordinal(eraValue)];
 218     }
 219 
 220     //-----------------------------------------------------------------------
 221     /**
 222      * Obtains an instance of {@code JapaneseEra} from an {@code int} value.
 223      * <ul>
 224      * <li>The value {@code 1} is associated with the 'Showa' era, because
 225      * it contains 1970-01-01 (ISO calendar system).</li>
 226      * <li>The values {@code -1} and {@code 0} are associated with two earlier
 227      * eras, Meiji and Taisho, respectively.</li>
 228      * <li>A value greater than {@code 1} is associated with a later era,
 229      * beginning with Heisei ({@code 2}).</li>
 230      * </ul>
 231      * <p>
 232      * Every instance of {@code JapaneseEra} that is returned from the {@link #values()}
 233      * method has an int value (available via {@link Era#getValue()} which is
 234      * accepted by this method.
 235      *
 236      * @param japaneseEra  the era to represent
 237      * @return the {@code JapaneseEra} singleton, not null
 238      * @throws DateTimeException if the value is invalid
 239      */
 240     public static JapaneseEra of(int japaneseEra) {
 241         int i = ordinal(japaneseEra);
 242         if (i < 0 || i >= KNOWN_ERAS.length) {
 243             throw new DateTimeException("Invalid era: " + japaneseEra);
 244         }
 245         return KNOWN_ERAS[i];
 246     }
 247 
 248     /**
 249      * Returns the {@code JapaneseEra} with the name.
 250      * <p>
 251      * The string must match exactly the name of the era.
 252      * (Extraneous whitespace characters are not permitted.)
 253      * <p>
 254      * Valid era names are the names of eras returned from {@link #values()}.
 255      *
 256      * @param japaneseEra  the japaneseEra name; non-null
 257      * @return the {@code JapaneseEra} singleton, never null
 258      * @throws IllegalArgumentException if there is not JapaneseEra with the specified name
 259      */
 260     public static JapaneseEra valueOf(String japaneseEra) {
 261         Objects.requireNonNull(japaneseEra, "japaneseEra");
 262         for (JapaneseEra era : KNOWN_ERAS) {
 263             if (era.getName().equals(japaneseEra)) {
 264                 return era;
 265             }
 266         }
 267         throw new IllegalArgumentException("japaneseEra is invalid");
 268     }
 269 
 270     /**
 271      * Returns an array of JapaneseEras. The array may contain eras defined
 272      * by the Japanese government beyond the known era singletons.
 273      *
 274      * <p>
 275      * This method may be used to iterate over the JapaneseEras as follows:
 276      * <pre>
 277      * for (JapaneseEra c : JapaneseEra.values())
 278      *     System.out.println(c);
 279      * </pre>
 280      *
 281      * @return an array of JapaneseEras
 282      */
 283     public static JapaneseEra[] values() {
 284         return Arrays.copyOf(KNOWN_ERAS, KNOWN_ERAS.length);
 285     }
 286 
 287     /**
 288      * {@inheritDoc}
 289      *
 290      * @param style {@inheritDoc}
 291      * @param locale {@inheritDoc}
 292      */
 293     @Override
 294     public String getDisplayName(TextStyle style, Locale locale) {
 295         // If this JapaneseEra is a supplemental one, obtain the name from
 296         // the era definition.
 297         if (getValue() > N_ERA_CONSTANTS - ERA_OFFSET) {
 298             Objects.requireNonNull(locale, "locale");
 299             return style.asNormal() == TextStyle.NARROW ? getAbbreviation() : getName();
 300         }
 301 
 302         return new DateTimeFormatterBuilder()
 303             .appendText(ERA, style)
 304             .toFormatter(locale)
 305             .withChronology(JapaneseChronology.INSTANCE)
 306             .format(this == MEIJI ? MEIJI_6_ISODATE : since);
 307     }
 308 
 309     //-----------------------------------------------------------------------
 310     /**
 311      * Obtains an instance of {@code JapaneseEra} from a date.
 312      *
 313      * @param date  the date, not null
 314      * @return the Era singleton, never null
 315      */
 316     static JapaneseEra from(LocalDate date) {
 317         if (date.isBefore(MEIJI_6_ISODATE)) {
 318             throw new DateTimeException("JapaneseDate before Meiji 6 are not supported");
 319         }
 320         for (int i = KNOWN_ERAS.length - 1; i > 0; i--) {
 321             JapaneseEra era = KNOWN_ERAS[i];
 322             if (date.compareTo(era.since) >= 0) {
 323                 return era;
 324             }
 325         }
 326         return null;
 327     }
 328 
 329     static JapaneseEra toJapaneseEra(sun.util.calendar.Era privateEra) {
 330         for (int i = ERA_CONFIG.length - 1; i >= 0; i--) {
 331             if (ERA_CONFIG[i].equals(privateEra)) {
 332                 return KNOWN_ERAS[i];
 333             }
 334         }
 335         return null;
 336     }
 337 
 338     static sun.util.calendar.Era privateEraFrom(LocalDate isoDate) {
 339         for (int i = KNOWN_ERAS.length - 1; i > 0; i--) {
 340             JapaneseEra era = KNOWN_ERAS[i];
 341             if (isoDate.compareTo(era.since) >= 0) {
 342                 return ERA_CONFIG[i];
 343             }
 344         }
 345         return null;
 346     }
 347 
 348     /**
 349      * Returns the index into the arrays from the Era value.
 350      * the eraValue is a valid Era number, -1..2.
 351      *
 352      * @param eraValue  the era value to convert to the index
 353      * @return the index of the current Era
 354      */
 355     private static int ordinal(int eraValue) {
 356         return eraValue + ERA_OFFSET - 1;
 357     }
 358 
 359     //-----------------------------------------------------------------------
 360     /**
 361      * Gets the numeric era {@code int} value.
 362      * <p>
 363      * The {@link #SHOWA} era that contains 1970-01-01 (ISO calendar system) has the value 1.
 364      * Later eras are numbered from 2 ({@link #HEISEI}).
 365      * Earlier eras are numbered 0 ({@link #TAISHO}), -1 ({@link #MEIJI})).
 366      *
 367      * @return the era value
 368      */
 369     @Override
 370     public int getValue() {
 371         return eraValue;
 372     }
 373 
 374     //-----------------------------------------------------------------------
 375     /**
 376      * Gets the range of valid values for the specified field.
 377      * <p>
 378      * The range object expresses the minimum and maximum valid values for a field.
 379      * This era is used to enhance the accuracy of the returned range.
 380      * If it is not possible to return the range, because the field is not supported
 381      * or for some other reason, an exception is thrown.
 382      * <p>
 383      * If the field is a {@link ChronoField} then the query is implemented here.
 384      * The {@code ERA} field returns the range.
 385      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
 386      * <p>
 387      * If the field is not a {@code ChronoField}, then the result of this method
 388      * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
 389      * passing {@code this} as the argument.
 390      * Whether the range can be obtained is determined by the field.
 391      * <p>
 392      * The range of valid Japanese eras can change over time due to the nature
 393      * of the Japanese calendar system.
 394      *
 395      * @param field  the field to query the range for, not null
 396      * @return the range of valid values for the field, not null
 397      * @throws DateTimeException if the range for the field cannot be obtained
 398      * @throws UnsupportedTemporalTypeException if the unit is not supported
 399      */
 400     @Override  // override as super would return range from 0 to 1
 401     public ValueRange range(TemporalField field) {
 402         if (field == ERA) {
 403             return JapaneseChronology.INSTANCE.range(ERA);
 404         }
 405         return Era.super.range(field);
 406     }
 407 
 408     //-----------------------------------------------------------------------
 409     String getAbbreviation() {
 410         return ERA_CONFIG[ordinal(getValue())].getAbbreviation();
 411     }
 412 
 413     String getName() {
 414         return ERA_CONFIG[ordinal(getValue())].getName();
 415     }
 416 
 417     @Override
 418     public String toString() {
 419         return getName();
 420     }
 421 
 422     //-----------------------------------------------------------------------
 423     /**
 424      * Defend against malicious streams.
 425      *
 426      * @param s the stream to read
 427      * @throws InvalidObjectException always
 428      */
 429     private void readObject(ObjectInputStream s) throws InvalidObjectException {
 430         throw new InvalidObjectException("Deserialization via serialization delegate");
 431     }
 432 
 433     //-----------------------------------------------------------------------
 434     /**
 435      * Writes the object using a
 436      * <a href="{@docRoot}/serialized-form.html#java.time.chrono.Ser">dedicated serialized form</a>.
 437      * @serialData
 438      * <pre>
 439      *  out.writeByte(5);        // identifies a JapaneseEra
 440      *  out.writeInt(getValue());
 441      * </pre>
 442      *
 443      * @return the instance of {@code Ser}, not null
 444      */
 445     private Object writeReplace() {
 446         return new Ser(Ser.JAPANESE_ERA_TYPE, this);
 447     }
 448 
 449     void writeExternal(DataOutput out) throws IOException {
 450         out.writeByte(this.getValue());
 451     }
 452 
 453     static JapaneseEra readExternal(DataInput in) throws IOException {
 454         byte eraValue = in.readByte();
 455         return JapaneseEra.of(eraValue);
 456     }
 457 
 458 }