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