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