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