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  * Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos
  28  *
  29  * All rights reserved.
  30  *
  31  * Redistribution and use in source and binary forms, with or without
  32  * modification, are permitted provided that the following conditions are met:
  33  *
  34  *  * Redistributions of source code must retain the above copyright notice,
  35  *    this list of conditions and the following disclaimer.
  36  *
  37  *  * Redistributions in binary form must reproduce the above copyright notice,
  38  *    this list of conditions and the following disclaimer in the documentation
  39  *    and/or other materials provided with the distribution.
  40  *
  41  *  * Neither the name of JSR-310 nor the names of its contributors
  42  *    may be used to endorse or promote products derived from this software
  43  *    without specific prior written permission.
  44  *
  45  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  46  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  47  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  48  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  49  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  50  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  51  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  52  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  53  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  54  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  55  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  56  */
  57 package java.time.chrono;
  58 
  59 import java.io.InvalidObjectException;
  60 import static java.time.temporal.ChronoField.PROLEPTIC_MONTH;
  61 import static java.time.temporal.ChronoField.YEAR;
  62 
  63 import java.io.ObjectInputStream;
  64 import java.io.Serializable;
  65 import java.time.Clock;
  66 import java.time.DateTimeException;
  67 import java.time.Instant;
  68 import java.time.LocalDate;
  69 import java.time.ZoneId;
  70 import java.time.format.ResolverStyle;
  71 import java.time.temporal.ChronoField;
  72 import java.time.temporal.TemporalAccessor;
  73 import java.time.temporal.TemporalField;
  74 import java.time.temporal.ValueRange;
  75 import java.util.Arrays;
  76 import java.util.HashMap;
  77 import java.util.List;
  78 import java.util.Locale;
  79 import java.util.Map;
  80 
  81 /**
  82  * The Thai Buddhist calendar system.
  83  * <p>
  84  * This chronology defines the rules of the Thai Buddhist calendar system.
  85  * This calendar system is primarily used in Thailand.
  86  * Dates are aligned such that {@code 2484-01-01 (Buddhist)} is {@code 1941-01-01 (ISO)}.
  87  * <p>
  88  * The fields are defined as follows:
  89  * <ul>
  90  * <li>era - There are two eras, the current 'Buddhist' (ERA_BE) and the previous era (ERA_BEFORE_BE).
  91  * <li>year-of-era - The year-of-era for the current era increases uniformly from the epoch at year one.
  92  *  For the previous era the year increases from one as time goes backwards.
  93  *  The value for the current era is equal to the ISO proleptic-year plus 543.
  94  * <li>proleptic-year - The proleptic year is the same as the year-of-era for the
  95  *  current era. For the previous era, years have zero, then negative values.
  96  *  The value is equal to the ISO proleptic-year plus 543.
  97  * <li>month-of-year - The ThaiBuddhist month-of-year exactly matches ISO.
  98  * <li>day-of-month - The ThaiBuddhist day-of-month exactly matches ISO.
  99  * <li>day-of-year - The ThaiBuddhist day-of-year exactly matches ISO.
 100  * <li>leap-year - The ThaiBuddhist leap-year pattern exactly matches ISO, such that the two calendars
 101  *  are never out of step.
 102  * </ul>
 103  *
 104  * @implSpec
 105  * This class is immutable and thread-safe.
 106  *
 107  * @since 1.8
 108  */
 109 public final class ThaiBuddhistChronology extends AbstractChronology implements Serializable {
 110 
 111     /**
 112      * Singleton instance of the Buddhist chronology.
 113      */
 114     public static final ThaiBuddhistChronology INSTANCE = new ThaiBuddhistChronology();
 115 
 116     /**
 117      * Serialization version.
 118      */
 119     @java.io.Serial
 120     private static final long serialVersionUID = 2775954514031616474L;
 121     /**
 122      * Containing the offset to add to the ISO year.
 123      */
 124     static final int YEARS_DIFFERENCE = 543;
 125     /**
 126      * Narrow names for eras.
 127      */
 128     private static final HashMap<String, String[]> ERA_NARROW_NAMES = new HashMap<>();
 129     /**
 130      * Short names for eras.
 131      */
 132     private static final HashMap<String, String[]> ERA_SHORT_NAMES = new HashMap<>();
 133     /**
 134      * Full names for eras.
 135      */
 136     private static final HashMap<String, String[]> ERA_FULL_NAMES = new HashMap<>();
 137     /**
 138      * Fallback language for the era names.
 139      */
 140     private static final String FALLBACK_LANGUAGE = "en";
 141     /**
 142      * Language that has the era names.
 143      */
 144     private static final String TARGET_LANGUAGE = "th";
 145     /**
 146      * Name data.
 147      */
 148     static {
 149         ERA_NARROW_NAMES.put(FALLBACK_LANGUAGE, new String[]{"BB", "BE"});
 150         ERA_NARROW_NAMES.put(TARGET_LANGUAGE, new String[]{"BB", "BE"});
 151         ERA_SHORT_NAMES.put(FALLBACK_LANGUAGE, new String[]{"B.B.", "B.E."});
 152         ERA_SHORT_NAMES.put(TARGET_LANGUAGE,
 153                 new String[]{"\u0e1e.\u0e28.",
 154                 "\u0e1b\u0e35\u0e01\u0e48\u0e2d\u0e19\u0e04\u0e23\u0e34\u0e2a\u0e15\u0e4c\u0e01\u0e32\u0e25\u0e17\u0e35\u0e48"});
 155         ERA_FULL_NAMES.put(FALLBACK_LANGUAGE, new String[]{"Before Buddhist", "Budhhist Era"});
 156         ERA_FULL_NAMES.put(TARGET_LANGUAGE,
 157                 new String[]{"\u0e1e\u0e38\u0e17\u0e18\u0e28\u0e31\u0e01\u0e23\u0e32\u0e0a",
 158                 "\u0e1b\u0e35\u0e01\u0e48\u0e2d\u0e19\u0e04\u0e23\u0e34\u0e2a\u0e15\u0e4c\u0e01\u0e32\u0e25\u0e17\u0e35\u0e48"});
 159     }
 160 
 161     /**
 162      * Restricted constructor.
 163      */
 164     private ThaiBuddhistChronology() {
 165     }
 166 
 167     //-----------------------------------------------------------------------
 168     /**
 169      * Gets the ID of the chronology - 'ThaiBuddhist'.
 170      * <p>
 171      * The ID uniquely identifies the {@code Chronology}.
 172      * It can be used to lookup the {@code Chronology} using {@link Chronology#of(String)}.
 173      *
 174      * @return the chronology ID - 'ThaiBuddhist'
 175      * @see #getCalendarType()
 176      */
 177     @Override
 178     public String getId() {
 179         return "ThaiBuddhist";
 180     }
 181 
 182     /**
 183      * Gets the calendar type of the underlying calendar system - 'buddhist'.
 184      * <p>
 185      * The calendar type is an identifier defined by the
 186      * <em>Unicode Locale Data Markup Language (LDML)</em> specification.
 187      * It can be used to lookup the {@code Chronology} using {@link Chronology#of(String)}.
 188      * It can also be used as part of a locale, accessible via
 189      * {@link Locale#getUnicodeLocaleType(String)} with the key 'ca'.
 190      *
 191      * @return the calendar system type - 'buddhist'
 192      * @see #getId()
 193      */
 194     @Override
 195     public String getCalendarType() {
 196         return "buddhist";
 197     }
 198 
 199     //-----------------------------------------------------------------------
 200     /**
 201      * Obtains a local date in Thai Buddhist calendar system from the
 202      * era, year-of-era, month-of-year and day-of-month fields.
 203      *
 204      * @param era  the Thai Buddhist era, not null
 205      * @param yearOfEra  the year-of-era
 206      * @param month  the month-of-year
 207      * @param dayOfMonth  the day-of-month
 208      * @return the Thai Buddhist local date, not null
 209      * @throws DateTimeException if unable to create the date
 210      * @throws ClassCastException if the {@code era} is not a {@code ThaiBuddhistEra}
 211      */
 212     @Override
 213     public ThaiBuddhistDate date(Era era, int yearOfEra, int month, int dayOfMonth) {
 214         return date(prolepticYear(era, yearOfEra), month, dayOfMonth);
 215     }
 216 
 217     /**
 218      * Obtains a local date in Thai Buddhist calendar system from the
 219      * proleptic-year, month-of-year and day-of-month fields.
 220      *
 221      * @param prolepticYear  the proleptic-year
 222      * @param month  the month-of-year
 223      * @param dayOfMonth  the day-of-month
 224      * @return the Thai Buddhist local date, not null
 225      * @throws DateTimeException if unable to create the date
 226      */
 227     @Override
 228     public ThaiBuddhistDate date(int prolepticYear, int month, int dayOfMonth) {
 229         return new ThaiBuddhistDate(LocalDate.of(prolepticYear - YEARS_DIFFERENCE, month, dayOfMonth));
 230     }
 231 
 232     /**
 233      * Obtains a local date in Thai Buddhist calendar system from the
 234      * era, year-of-era and day-of-year fields.
 235      *
 236      * @param era  the Thai Buddhist era, not null
 237      * @param yearOfEra  the year-of-era
 238      * @param dayOfYear  the day-of-year
 239      * @return the Thai Buddhist local date, not null
 240      * @throws DateTimeException if unable to create the date
 241      * @throws ClassCastException if the {@code era} is not a {@code ThaiBuddhistEra}
 242      */
 243     @Override
 244     public ThaiBuddhistDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {
 245         return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);
 246     }
 247 
 248     /**
 249      * Obtains a local date in Thai Buddhist calendar system from the
 250      * proleptic-year and day-of-year fields.
 251      *
 252      * @param prolepticYear  the proleptic-year
 253      * @param dayOfYear  the day-of-year
 254      * @return the Thai Buddhist local date, not null
 255      * @throws DateTimeException if unable to create the date
 256      */
 257     @Override
 258     public ThaiBuddhistDate dateYearDay(int prolepticYear, int dayOfYear) {
 259         return new ThaiBuddhistDate(LocalDate.ofYearDay(prolepticYear - YEARS_DIFFERENCE, dayOfYear));
 260     }
 261 
 262     /**
 263      * Obtains a local date in the Thai Buddhist calendar system from the epoch-day.
 264      *
 265      * @param epochDay  the epoch day
 266      * @return the Thai Buddhist local date, not null
 267      * @throws DateTimeException if unable to create the date
 268      */
 269     @Override  // override with covariant return type
 270     public ThaiBuddhistDate dateEpochDay(long epochDay) {
 271         return new ThaiBuddhistDate(LocalDate.ofEpochDay(epochDay));
 272     }
 273 
 274     @Override
 275     public ThaiBuddhistDate dateNow() {
 276         return dateNow(Clock.systemDefaultZone());
 277     }
 278 
 279     @Override
 280     public ThaiBuddhistDate dateNow(ZoneId zone) {
 281         return dateNow(Clock.system(zone));
 282     }
 283 
 284     @Override
 285     public ThaiBuddhistDate dateNow(Clock clock) {
 286         return date(LocalDate.now(clock));
 287     }
 288 
 289     @Override
 290     public ThaiBuddhistDate date(TemporalAccessor temporal) {
 291         if (temporal instanceof ThaiBuddhistDate) {
 292             return (ThaiBuddhistDate) temporal;
 293         }
 294         return new ThaiBuddhistDate(LocalDate.from(temporal));
 295     }
 296 
 297     @Override
 298     @SuppressWarnings("unchecked")
 299     public ChronoLocalDateTime<ThaiBuddhistDate> localDateTime(TemporalAccessor temporal) {
 300         return (ChronoLocalDateTime<ThaiBuddhistDate>)super.localDateTime(temporal);
 301     }
 302 
 303     @Override
 304     @SuppressWarnings("unchecked")
 305     public ChronoZonedDateTime<ThaiBuddhistDate> zonedDateTime(TemporalAccessor temporal) {
 306         return (ChronoZonedDateTime<ThaiBuddhistDate>)super.zonedDateTime(temporal);
 307     }
 308 
 309     @Override
 310     @SuppressWarnings("unchecked")
 311     public ChronoZonedDateTime<ThaiBuddhistDate> zonedDateTime(Instant instant, ZoneId zone) {
 312         return (ChronoZonedDateTime<ThaiBuddhistDate>)super.zonedDateTime(instant, zone);
 313     }
 314 
 315     //-----------------------------------------------------------------------
 316     /**
 317      * Checks if the specified year is a leap year.
 318      * <p>
 319      * Thai Buddhist leap years occur exactly in line with ISO leap years.
 320      * This method does not validate the year passed in, and only has a
 321      * well-defined result for years in the supported range.
 322      *
 323      * @param prolepticYear  the proleptic-year to check, not validated for range
 324      * @return true if the year is a leap year
 325      */
 326     @Override
 327     public boolean isLeapYear(long prolepticYear) {
 328         return IsoChronology.INSTANCE.isLeapYear(prolepticYear - YEARS_DIFFERENCE);
 329     }
 330 
 331     @Override
 332     public int prolepticYear(Era era, int yearOfEra) {
 333         if (era instanceof ThaiBuddhistEra == false) {
 334             throw new ClassCastException("Era must be BuddhistEra");
 335         }
 336         return (era == ThaiBuddhistEra.BE ? yearOfEra : 1 - yearOfEra);
 337     }
 338 
 339     @Override
 340     public ThaiBuddhistEra eraOf(int eraValue) {
 341         return ThaiBuddhistEra.of(eraValue);
 342     }
 343 
 344     @Override
 345     public List<Era> eras() {
 346         return List.of(ThaiBuddhistEra.values());
 347     }
 348 
 349     //-----------------------------------------------------------------------
 350     @Override
 351     public ValueRange range(ChronoField field) {
 352         switch (field) {
 353             case PROLEPTIC_MONTH: {
 354                 ValueRange range = PROLEPTIC_MONTH.range();
 355                 return ValueRange.of(range.getMinimum() + YEARS_DIFFERENCE * 12L, range.getMaximum() + YEARS_DIFFERENCE * 12L);
 356             }
 357             case YEAR_OF_ERA: {
 358                 ValueRange range = YEAR.range();
 359                 return ValueRange.of(1, -(range.getMinimum() + YEARS_DIFFERENCE) + 1, range.getMaximum() + YEARS_DIFFERENCE);
 360             }
 361             case YEAR: {
 362                 ValueRange range = YEAR.range();
 363                 return ValueRange.of(range.getMinimum() + YEARS_DIFFERENCE, range.getMaximum() + YEARS_DIFFERENCE);
 364             }
 365         }
 366         return field.range();
 367     }
 368 
 369     //-----------------------------------------------------------------------
 370     @Override  // override for return type
 371     public ThaiBuddhistDate resolveDate(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {
 372         return (ThaiBuddhistDate) super.resolveDate(fieldValues, resolverStyle);
 373     }
 374 
 375     //-----------------------------------------------------------------------
 376     /**
 377      * Writes the Chronology using a
 378      * <a href="{@docRoot}/serialized-form.html#java.time.chrono.Ser">dedicated serialized form</a>.
 379      * @serialData
 380      * <pre>
 381      *  out.writeByte(1);     // identifies a Chronology
 382      *  out.writeUTF(getId());
 383      * </pre>
 384      *
 385      * @return the instance of {@code Ser}, not null
 386      */
 387     @Override
 388     @java.io.Serial
 389     Object writeReplace() {
 390         return super.writeReplace();
 391     }
 392 
 393     /**
 394      * Defend against malicious streams.
 395      *
 396      * @param s the stream to read
 397      * @throws InvalidObjectException always
 398      */
 399     @java.io.Serial
 400     private void readObject(ObjectInputStream s) throws InvalidObjectException {
 401         throw new InvalidObjectException("Deserialization via serialization delegate");
 402     }
 403 }