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