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 static java.time.chrono.ThaiBuddhistChronology.YEARS_DIFFERENCE;
  60 import static java.time.temporal.ChronoField.DAY_OF_MONTH;
  61 import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
  62 import static java.time.temporal.ChronoField.YEAR;
  63 
  64 import java.io.DataInput;
  65 import java.io.DataOutput;
  66 import java.io.IOException;
  67 import java.io.InvalidObjectException;
  68 import java.io.ObjectInputStream;
  69 import java.io.Serializable;
  70 import java.time.Clock;
  71 import java.time.DateTimeException;
  72 import java.time.LocalDate;
  73 import java.time.LocalTime;
  74 import java.time.Period;
  75 import java.time.ZoneId;
  76 import java.time.temporal.ChronoField;
  77 import java.time.temporal.TemporalAccessor;
  78 import java.time.temporal.TemporalAdjuster;
  79 import java.time.temporal.TemporalAmount;
  80 import java.time.temporal.TemporalField;
  81 import java.time.temporal.TemporalQuery;
  82 import java.time.temporal.TemporalUnit;
  83 import java.time.temporal.UnsupportedTemporalTypeException;
  84 import java.time.temporal.ValueRange;
  85 import java.util.Objects;
  86 
  87 /**
  88  * A date in the Thai Buddhist calendar system.
  89  * <p>
  90  * This date operates using the {@linkplain ThaiBuddhistChronology Thai Buddhist calendar}.
  91  * This calendar system is primarily used in Thailand.
  92  * Dates are aligned such that {@code 2484-01-01 (Buddhist)} is {@code 1941-01-01 (ISO)}.
  93  *
  94  * <p>
  95  * This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
  96  * class; use of identity-sensitive operations (including reference equality
  97  * ({@code ==}), identity hash code, or synchronization) on instances of
  98  * {@code ThaiBuddhistDate} may have unpredictable results and should be avoided.
  99  * The {@code equals} method should be used for comparisons.
 100  *
 101  * @implSpec
 102  * This class is immutable and thread-safe.
 103  *
 104  * @since 1.8
 105  */
 106 public final class ThaiBuddhistDate
 107         extends ChronoLocalDateImpl<ThaiBuddhistDate>
 108         implements ChronoLocalDate, Serializable {
 109 
 110     /**
 111      * Serialization version.
 112      */
 113     @java.io.Serial
 114     private static final long serialVersionUID = -8722293800195731463L;
 115 
 116     /**
 117      * The underlying date.
 118      */
 119     private final transient LocalDate isoDate;
 120 
 121     //-----------------------------------------------------------------------
 122     /**
 123      * Obtains the current {@code ThaiBuddhistDate} from the system clock in the default time-zone.
 124      * <p>
 125      * This will query the {@link Clock#systemDefaultZone() system clock} in the default
 126      * time-zone to obtain the current date.
 127      * <p>
 128      * Using this method will prevent the ability to use an alternate clock for testing
 129      * because the clock is hard-coded.
 130      *
 131      * @return the current date using the system clock and default time-zone, not null
 132      */
 133     public static ThaiBuddhistDate now() {
 134         return now(Clock.systemDefaultZone());
 135     }
 136 
 137     /**
 138      * Obtains the current {@code ThaiBuddhistDate} from the system clock in the specified time-zone.
 139      * <p>
 140      * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date.
 141      * Specifying the time-zone avoids dependence on the default time-zone.
 142      * <p>
 143      * Using this method will prevent the ability to use an alternate clock for testing
 144      * because the clock is hard-coded.
 145      *
 146      * @param zone  the zone ID to use, not null
 147      * @return the current date using the system clock, not null
 148      */
 149     public static ThaiBuddhistDate now(ZoneId zone) {
 150         return now(Clock.system(zone));
 151     }
 152 
 153     /**
 154      * Obtains the current {@code ThaiBuddhistDate} from the specified clock.
 155      * <p>
 156      * This will query the specified clock to obtain the current date - today.
 157      * Using this method allows the use of an alternate clock for testing.
 158      * The alternate clock may be introduced using {@linkplain Clock dependency injection}.
 159      *
 160      * @param clock  the clock to use, not null
 161      * @return the current date, not null
 162      * @throws DateTimeException if the current date cannot be obtained
 163      */
 164     public static ThaiBuddhistDate now(Clock clock) {
 165         return new ThaiBuddhistDate(LocalDate.now(clock));
 166     }
 167 
 168     /**
 169      * Obtains a {@code ThaiBuddhistDate} representing a date in the Thai Buddhist calendar
 170      * system from the proleptic-year, month-of-year and day-of-month fields.
 171      * <p>
 172      * This returns a {@code ThaiBuddhistDate} with the specified fields.
 173      * The day must be valid for the year and month, otherwise an exception will be thrown.
 174      *
 175      * @param prolepticYear  the Thai Buddhist proleptic-year
 176      * @param month  the Thai Buddhist month-of-year, from 1 to 12
 177      * @param dayOfMonth  the Thai Buddhist day-of-month, from 1 to 31
 178      * @return the date in Thai Buddhist calendar system, not null
 179      * @throws DateTimeException if the value of any field is out of range,
 180      *  or if the day-of-month is invalid for the month-year
 181      */
 182     public static ThaiBuddhistDate of(int prolepticYear, int month, int dayOfMonth) {
 183         return new ThaiBuddhistDate(LocalDate.of(prolepticYear - YEARS_DIFFERENCE, month, dayOfMonth));
 184     }
 185 
 186     /**
 187      * Obtains a {@code ThaiBuddhistDate} from a temporal object.
 188      * <p>
 189      * This obtains a date in the Thai Buddhist calendar system based on the specified temporal.
 190      * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
 191      * which this factory converts to an instance of {@code ThaiBuddhistDate}.
 192      * <p>
 193      * The conversion typically uses the {@link ChronoField#EPOCH_DAY EPOCH_DAY}
 194      * field, which is standardized across calendar systems.
 195      * <p>
 196      * This method matches the signature of the functional interface {@link TemporalQuery}
 197      * allowing it to be used as a query via method reference, {@code ThaiBuddhistDate::from}.
 198      *
 199      * @param temporal  the temporal object to convert, not null
 200      * @return the date in Thai Buddhist calendar system, not null
 201      * @throws DateTimeException if unable to convert to a {@code ThaiBuddhistDate}
 202      */
 203     public static ThaiBuddhistDate from(TemporalAccessor temporal) {
 204         return ThaiBuddhistChronology.INSTANCE.date(temporal);
 205     }
 206 
 207     //-----------------------------------------------------------------------
 208     /**
 209      * Creates an instance from an ISO date.
 210      *
 211      * @param isoDate  the standard local date, validated not null
 212      */
 213     ThaiBuddhistDate(LocalDate isoDate) {
 214         Objects.requireNonNull(isoDate, "isoDate");
 215         this.isoDate = isoDate;
 216     }
 217 
 218     //-----------------------------------------------------------------------
 219     /**
 220      * Gets the chronology of this date, which is the Thai Buddhist calendar system.
 221      * <p>
 222      * The {@code Chronology} represents the calendar system in use.
 223      * The era and other fields in {@link ChronoField} are defined by the chronology.
 224      *
 225      * @return the Thai Buddhist chronology, not null
 226      */
 227     @Override
 228     public ThaiBuddhistChronology getChronology() {
 229         return ThaiBuddhistChronology.INSTANCE;
 230     }
 231 
 232     /**
 233      * Gets the era applicable at this date.
 234      * <p>
 235      * The Thai Buddhist calendar system has two eras, 'BE' and 'BEFORE_BE',
 236      * defined by {@link ThaiBuddhistEra}.
 237      *
 238      * @return the era applicable at this date, not null
 239      */
 240     @Override
 241     public ThaiBuddhistEra getEra() {
 242         return (getProlepticYear() >= 1 ? ThaiBuddhistEra.BE : ThaiBuddhistEra.BEFORE_BE);
 243     }
 244 
 245     /**
 246      * Returns the length of the month represented by this date.
 247      * <p>
 248      * This returns the length of the month in days.
 249      * Month lengths match those of the ISO calendar system.
 250      *
 251      * @return the length of the month in days
 252      */
 253     @Override
 254     public int lengthOfMonth() {
 255         return isoDate.lengthOfMonth();
 256     }
 257 
 258     //-----------------------------------------------------------------------
 259     @Override
 260     public ValueRange range(TemporalField field) {
 261         if (field instanceof ChronoField) {
 262             if (isSupported(field)) {
 263                 ChronoField f = (ChronoField) field;
 264                 switch (f) {
 265                     case DAY_OF_MONTH:
 266                     case DAY_OF_YEAR:
 267                     case ALIGNED_WEEK_OF_MONTH:
 268                         return isoDate.range(field);
 269                     case YEAR_OF_ERA: {
 270                         ValueRange range = YEAR.range();
 271                         long max = (getProlepticYear() <= 0 ? -(range.getMinimum() + YEARS_DIFFERENCE) + 1 : range.getMaximum() + YEARS_DIFFERENCE);
 272                         return ValueRange.of(1, max);
 273                     }
 274                 }
 275                 return getChronology().range(f);
 276             }
 277             throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
 278         }
 279         return field.rangeRefinedBy(this);
 280     }
 281 
 282     @Override
 283     public long getLong(TemporalField field) {
 284         if (field instanceof ChronoField) {
 285             switch ((ChronoField) field) {
 286                 case PROLEPTIC_MONTH:
 287                     return getProlepticMonth();
 288                 case YEAR_OF_ERA: {
 289                     int prolepticYear = getProlepticYear();
 290                     return (prolepticYear >= 1 ? prolepticYear : 1 - prolepticYear);
 291                 }
 292                 case YEAR:
 293                     return getProlepticYear();
 294                 case ERA:
 295                     return (getProlepticYear() >= 1 ? 1 : 0);
 296             }
 297             return isoDate.getLong(field);
 298         }
 299         return field.getFrom(this);
 300     }
 301 
 302     private long getProlepticMonth() {
 303         return getProlepticYear() * 12L + isoDate.getMonthValue() - 1;
 304     }
 305 
 306     private int getProlepticYear() {
 307         return isoDate.getYear() + YEARS_DIFFERENCE;
 308     }
 309 
 310     //-----------------------------------------------------------------------
 311     @Override
 312     public ThaiBuddhistDate with(TemporalField field, long newValue) {
 313         if (field instanceof ChronoField) {
 314             ChronoField f = (ChronoField) field;
 315             if (getLong(f) == newValue) {
 316                 return this;
 317             }
 318             switch (f) {
 319                 case PROLEPTIC_MONTH:
 320                     getChronology().range(f).checkValidValue(newValue, f);
 321                     return plusMonths(newValue - getProlepticMonth());
 322                 case YEAR_OF_ERA:
 323                 case YEAR:
 324                 case ERA: {
 325                     int nvalue = getChronology().range(f).checkValidIntValue(newValue, f);
 326                     switch (f) {
 327                         case YEAR_OF_ERA:
 328                             return with(isoDate.withYear((getProlepticYear() >= 1 ? nvalue : 1 - nvalue)  - YEARS_DIFFERENCE));
 329                         case YEAR:
 330                             return with(isoDate.withYear(nvalue - YEARS_DIFFERENCE));
 331                         case ERA:
 332                             return with(isoDate.withYear((1 - getProlepticYear()) - YEARS_DIFFERENCE));
 333                     }
 334                 }
 335             }
 336             return with(isoDate.with(field, newValue));
 337         }
 338         return super.with(field, newValue);
 339     }
 340 
 341     /**
 342      * {@inheritDoc}
 343      * @throws DateTimeException {@inheritDoc}
 344      * @throws ArithmeticException {@inheritDoc}
 345      */
 346     @Override
 347     public  ThaiBuddhistDate with(TemporalAdjuster adjuster) {
 348         return super.with(adjuster);
 349     }
 350 
 351     /**
 352      * {@inheritDoc}
 353      * @throws DateTimeException {@inheritDoc}
 354      * @throws ArithmeticException {@inheritDoc}
 355      */
 356     @Override
 357     public ThaiBuddhistDate plus(TemporalAmount amount) {
 358         return super.plus(amount);
 359     }
 360 
 361     /**
 362      * {@inheritDoc}
 363      * @throws DateTimeException {@inheritDoc}
 364      * @throws ArithmeticException {@inheritDoc}
 365      */
 366     @Override
 367     public ThaiBuddhistDate minus(TemporalAmount amount) {
 368         return super.minus(amount);
 369     }
 370 
 371     //-----------------------------------------------------------------------
 372     @Override
 373     ThaiBuddhistDate plusYears(long years) {
 374         return with(isoDate.plusYears(years));
 375     }
 376 
 377     @Override
 378     ThaiBuddhistDate plusMonths(long months) {
 379         return with(isoDate.plusMonths(months));
 380     }
 381 
 382     @Override
 383     ThaiBuddhistDate plusWeeks(long weeksToAdd) {
 384         return super.plusWeeks(weeksToAdd);
 385     }
 386 
 387     @Override
 388     ThaiBuddhistDate plusDays(long days) {
 389         return with(isoDate.plusDays(days));
 390     }
 391 
 392     @Override
 393     public ThaiBuddhistDate plus(long amountToAdd, TemporalUnit unit) {
 394         return super.plus(amountToAdd, unit);
 395     }
 396 
 397     @Override
 398     public ThaiBuddhistDate minus(long amountToAdd, TemporalUnit unit) {
 399         return super.minus(amountToAdd, unit);
 400     }
 401 
 402     @Override
 403     ThaiBuddhistDate minusYears(long yearsToSubtract) {
 404         return super.minusYears(yearsToSubtract);
 405     }
 406 
 407     @Override
 408     ThaiBuddhistDate minusMonths(long monthsToSubtract) {
 409         return super.minusMonths(monthsToSubtract);
 410     }
 411 
 412     @Override
 413     ThaiBuddhistDate minusWeeks(long weeksToSubtract) {
 414         return super.minusWeeks(weeksToSubtract);
 415     }
 416 
 417     @Override
 418     ThaiBuddhistDate minusDays(long daysToSubtract) {
 419         return super.minusDays(daysToSubtract);
 420     }
 421 
 422     private ThaiBuddhistDate with(LocalDate newDate) {
 423         return (newDate.equals(isoDate) ? this : new ThaiBuddhistDate(newDate));
 424     }
 425 
 426     @Override        // for javadoc and covariant return type
 427     @SuppressWarnings("unchecked")
 428     public final ChronoLocalDateTime<ThaiBuddhistDate> atTime(LocalTime localTime) {
 429         return (ChronoLocalDateTime<ThaiBuddhistDate>) super.atTime(localTime);
 430     }
 431 
 432     @Override
 433     public ChronoPeriod until(ChronoLocalDate endDate) {
 434         Period period = isoDate.until(endDate);
 435         return getChronology().period(period.getYears(), period.getMonths(), period.getDays());
 436     }
 437 
 438     @Override  // override for performance
 439     public long toEpochDay() {
 440         return isoDate.toEpochDay();
 441     }
 442 
 443     //-------------------------------------------------------------------------
 444     /**
 445      * Compares this date to another date, including the chronology.
 446      * <p>
 447      * Compares this {@code ThaiBuddhistDate} with another ensuring that the date is the same.
 448      * <p>
 449      * Only objects of type {@code ThaiBuddhistDate} are compared, other types return false.
 450      * To compare the dates of two {@code TemporalAccessor} instances, including dates
 451      * in two different chronologies, use {@link ChronoField#EPOCH_DAY} as a comparator.
 452      *
 453      * @param obj  the object to check, null returns false
 454      * @return true if this is equal to the other date
 455      */
 456     @Override  // override for performance
 457     public boolean equals(Object obj) {
 458         if (this == obj) {
 459             return true;
 460         }
 461         if (obj instanceof ThaiBuddhistDate) {
 462             ThaiBuddhistDate otherDate = (ThaiBuddhistDate) obj;
 463             return this.isoDate.equals(otherDate.isoDate);
 464         }
 465         return false;
 466     }
 467 
 468     /**
 469      * A hash code for this date.
 470      *
 471      * @return a suitable hash code based only on the Chronology and the date
 472      */
 473     @Override  // override for performance
 474     public int hashCode() {
 475         return getChronology().getId().hashCode() ^ isoDate.hashCode();
 476     }
 477 
 478     //-----------------------------------------------------------------------
 479     /**
 480      * Defend against malicious streams.
 481      *
 482      * @param s the stream to read
 483      * @throws InvalidObjectException always
 484      */
 485     @java.io.Serial
 486     private void readObject(ObjectInputStream s) throws InvalidObjectException {
 487         throw new InvalidObjectException("Deserialization via serialization delegate");
 488     }
 489 
 490     /**
 491      * Writes the object using a
 492      * <a href="{@docRoot}/serialized-form.html#java.time.chrono.Ser">dedicated serialized form</a>.
 493      * @serialData
 494      * <pre>
 495      *  out.writeByte(10);                // identifies a ThaiBuddhistDate
 496      *  out.writeInt(get(YEAR));
 497      *  out.writeByte(get(MONTH_OF_YEAR));
 498      *  out.writeByte(get(DAY_OF_MONTH));
 499      * </pre>
 500      *
 501      * @return the instance of {@code Ser}, not null
 502      */
 503     @java.io.Serial
 504     private Object writeReplace() {
 505         return new Ser(Ser.THAIBUDDHIST_DATE_TYPE, this);
 506     }
 507 
 508     void writeExternal(DataOutput out) throws IOException {
 509         // ThaiBuddhistChronology is implicit in the THAIBUDDHIST_DATE_TYPE
 510         out.writeInt(this.get(YEAR));
 511         out.writeByte(this.get(MONTH_OF_YEAR));
 512         out.writeByte(this.get(DAY_OF_MONTH));
 513     }
 514 
 515     static ThaiBuddhistDate readExternal(DataInput in) throws IOException {
 516         int year = in.readInt();
 517         int month = in.readByte();
 518         int dayOfMonth = in.readByte();
 519         return ThaiBuddhistChronology.INSTANCE.date(year, month, dayOfMonth);
 520     }
 521 
 522 }