1 /*
   2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.  Oracle designates this
   7  * particular file as subject to the "Classpath" exception as provided
   8  * by Oracle in the LICENSE file that accompanied this code.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  */
  24 
  25 /*
  26  * Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos
  27  *
  28  * All rights reserved.
  29  *
  30  * Redistribution and use in source and binary forms, with or without
  31  * modification, are permitted provided that the following conditions are met:
  32  *
  33  *  * Redistributions of source code must retain the above copyright notice,
  34  *    this list of conditions and the following disclaimer.
  35  *
  36  *  * Redistributions in binary form must reproduce the above copyright notice,
  37  *    this list of conditions and the following disclaimer in the documentation
  38  *    and/or other materials provided with the distribution.
  39  *
  40  *  * Neither the name of JSR-310 nor the names of its contributors
  41  *    may be used to endorse or promote products derived from this software
  42  *    without specific prior written permission.
  43  *
  44  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  45  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  46  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  47  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  48  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  49  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  50  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  51  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  52  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  53  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  54  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  55  */
  56 package tck.java.time.chrono;
  57 
  58 import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH;
  59 import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR;
  60 import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_MONTH;
  61 import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_YEAR;
  62 import static java.time.temporal.ChronoField.DAY_OF_MONTH;
  63 import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
  64 import static java.time.temporal.ChronoField.YEAR_OF_ERA;
  65 
  66 import java.io.Serializable;
  67 
  68 import java.time.DateTimeException;
  69 import java.time.LocalDate;
  70 import java.time.Period;
  71 import java.time.chrono.ChronoLocalDate;
  72 import java.time.temporal.ChronoField;
  73 import java.time.temporal.ChronoUnit;
  74 import java.time.temporal.Temporal;
  75 import java.time.temporal.TemporalField;
  76 import java.time.temporal.TemporalUnit;
  77 import java.time.temporal.ValueRange;
  78 import java.time.Year;
  79 
  80 /**
  81  * A date in the Coptic calendar system.
  82  * <p>
  83  * This implements {@code ChronoLocalDate} for the {@link CopticChronology Coptic calendar}.
  84  *
  85  * <h4>Implementation notes</h4>
  86  * This class is immutable and thread-safe.
  87  */
  88 public final class CopticDate
  89         implements ChronoLocalDate<CopticDate>, Serializable {
  90 
  91     /**
  92      * Serialization version.
  93      */
  94     private static final long serialVersionUID = -7920528871688876868L;
  95     /**
  96      * The difference between the Coptic and Coptic epoch day count.
  97      */
  98     private static final int EPOCH_DAY_DIFFERENCE = 574971 + 40587;
  99 
 100     /**
 101      * The proleptic year.
 102      */
 103     private final int prolepticYear;
 104     /**
 105      * The month.
 106      */
 107     private final short month;
 108     /**
 109      * The day.
 110      */
 111     private final short day;
 112 
 113     //-----------------------------------------------------------------------
 114     /**
 115      * Creates an instance.
 116      *
 117      * @param epochDay  the epoch day to convert based on 1970-01-01 (ISO)
 118      * @return the Coptic date, not null
 119      * @throws DateTimeException if the date is invalid
 120      */
 121     static CopticDate ofEpochDay(long epochDay) {
 122         epochDay += EPOCH_DAY_DIFFERENCE;
 123         int prolepticYear = (int) (((epochDay * 4) + 1463) / 1461);
 124         int startYearEpochDay = (prolepticYear - 1) * 365 + (prolepticYear / 4);
 125         int doy0 = (int) (epochDay - startYearEpochDay);
 126         int month = doy0 / 30 + 1;
 127         int dom = doy0 % 30 + 1;
 128         return new CopticDate(prolepticYear, month, dom);
 129     }
 130 
 131     private static CopticDate resolvePreviousValid(int prolepticYear, int month, int day) {
 132         if (month == 13 && day > 5) {
 133             day = CopticChronology.INSTANCE.isLeapYear(prolepticYear) ? 6 : 5;
 134         }
 135         return new CopticDate(prolepticYear, month, day);
 136     }
 137 
 138     //-----------------------------------------------------------------------
 139     /**
 140      * Creates an instance.
 141      *
 142      * @param prolepticYear  the Coptic proleptic-year
 143      * @param month  the Coptic month, from 1 to 13
 144      * @param dayOfMonth  the Coptic day-of-month, from 1 to 30
 145      * @throws DateTimeException if the date is invalid
 146      */
 147     CopticDate(int prolepticYear, int month, int dayOfMonth) {
 148         CopticChronology.MOY_RANGE.checkValidValue(month, MONTH_OF_YEAR);
 149         ValueRange range;
 150         if (month == 13) {
 151             range = CopticChronology.INSTANCE.isLeapYear(prolepticYear) ? CopticChronology.DOM_RANGE_LEAP : CopticChronology.DOM_RANGE_NONLEAP;
 152         } else {
 153             range = CopticChronology.DOM_RANGE;
 154         }
 155         range.checkValidValue(dayOfMonth, DAY_OF_MONTH);
 156 
 157         this.prolepticYear = prolepticYear;
 158         this.month = (short) month;
 159         this.day = (short) dayOfMonth;
 160     }
 161 
 162     /**
 163      * Validates the object.
 164      *
 165      * @return the resolved date, not null
 166      */
 167     private Object readResolve() {
 168         // TODO: validate
 169         return this;
 170     }
 171 
 172     //-----------------------------------------------------------------------
 173     @Override
 174     public CopticChronology getChronology() {
 175         return CopticChronology.INSTANCE;
 176     }
 177 
 178     //-----------------------------------------------------------------------
 179     @Override
 180     public int lengthOfMonth() {
 181         switch (month) {
 182             case 13:
 183                 return (isLeapYear() ? 6 : 5);
 184             default:
 185                 return 30;
 186         }
 187     }
 188 
 189     @Override
 190     public ValueRange range(TemporalField field) {
 191         if (field instanceof ChronoField) {
 192             if (isSupported(field)) {
 193                 ChronoField f = (ChronoField) field;
 194                 switch (f) {
 195                     case DAY_OF_MONTH: return ValueRange.of(1, lengthOfMonth());
 196                     case DAY_OF_YEAR: return ValueRange.of(1, lengthOfYear());
 197                     case ALIGNED_WEEK_OF_MONTH: return ValueRange.of(1, month == 13 ? 1 : 5);
 198                     case YEAR:
 199                     case YEAR_OF_ERA: return (prolepticYear <= 0 ?
 200                             ValueRange.of(1, Year.MAX_VALUE + 1) : ValueRange.of(1, Year.MAX_VALUE));  // TODO
 201                 }
 202                 return getChronology().range(f);
 203             }
 204             throw new DateTimeException("Unsupported field: " + field.getName());
 205         }
 206         return field.rangeRefinedBy(this);
 207     }
 208 
 209     @Override
 210     public long getLong(TemporalField field) {
 211         if (field instanceof ChronoField) {
 212             switch ((ChronoField) field) {
 213                 case DAY_OF_WEEK: return Math.floorMod(toEpochDay() + 3, 7) + 1;
 214                 case ALIGNED_DAY_OF_WEEK_IN_MONTH: return ((day - 1) % 7) + 1;
 215                 case ALIGNED_DAY_OF_WEEK_IN_YEAR: return ((get(ChronoField.DAY_OF_YEAR) - 1) % 7) + 1;
 216                 case DAY_OF_MONTH: return day;
 217                 case DAY_OF_YEAR: return (month - 1) * 30 + day;
 218                 case EPOCH_DAY: return toEpochDay();
 219                 case ALIGNED_WEEK_OF_MONTH: return ((day - 1) / 7) + 1;
 220                 case ALIGNED_WEEK_OF_YEAR: return ((get(ChronoField.DAY_OF_YEAR) - 1) / 7) + 1;
 221                 case MONTH_OF_YEAR: return month;
 222                 case YEAR_OF_ERA: return (prolepticYear >= 1 ? prolepticYear : 1 - prolepticYear);
 223                 case YEAR: return prolepticYear;
 224                 case ERA: return (prolepticYear >= 1 ? 1 : 0);
 225             }
 226             throw new DateTimeException("Unsupported field: " + field.getName());
 227         }
 228         return field.getFrom(this);
 229     }
 230 
 231     @Override
 232     public CopticDate with(TemporalField field, long newValue) {
 233         if (field instanceof ChronoField) {
 234             ChronoField f = (ChronoField) field;
 235             f.checkValidValue(newValue);        // TODO: validate value
 236             int nvalue = (int) newValue;
 237             switch (f) {
 238                 case DAY_OF_WEEK: return plusDays(newValue - get(ChronoField.DAY_OF_WEEK));
 239                 case ALIGNED_DAY_OF_WEEK_IN_MONTH: return plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_MONTH));
 240                 case ALIGNED_DAY_OF_WEEK_IN_YEAR: return plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_YEAR));
 241                 case DAY_OF_MONTH: return resolvePreviousValid(prolepticYear, month, nvalue);
 242                 case DAY_OF_YEAR: return resolvePreviousValid(prolepticYear, ((nvalue - 1) / 30) + 1, ((nvalue - 1) % 30) + 1);
 243                 case EPOCH_DAY: return ofEpochDay(nvalue);
 244                 case ALIGNED_WEEK_OF_MONTH: return plusDays((newValue - getLong(ALIGNED_WEEK_OF_MONTH)) * 7);
 245                 case ALIGNED_WEEK_OF_YEAR: return plusDays((newValue - getLong(ALIGNED_WEEK_OF_YEAR)) * 7);
 246                 case MONTH_OF_YEAR: return resolvePreviousValid(prolepticYear, nvalue, day);
 247                 case YEAR_OF_ERA: return resolvePreviousValid(prolepticYear >= 1 ? nvalue : 1 - nvalue, month, day);
 248                 case YEAR: return resolvePreviousValid(nvalue, month, day);
 249                 case ERA: return resolvePreviousValid(1 - prolepticYear, month, day);
 250             }
 251             throw new DateTimeException("Unsupported field: " + field.getName());
 252         }
 253         return field.adjustInto(this, newValue);
 254     }
 255 
 256     //-----------------------------------------------------------------------
 257     @Override
 258     public CopticDate plus(long amountToAdd, TemporalUnit unit) {
 259         if (unit instanceof ChronoUnit) {
 260             ChronoUnit f = (ChronoUnit) unit;
 261             switch (f) {
 262                 case DAYS: return plusDays(amountToAdd);
 263                 case WEEKS: return plusDays(Math.multiplyExact(amountToAdd, 7));
 264                 case MONTHS: return plusMonths(amountToAdd);
 265                 case YEARS: return plusYears(amountToAdd);
 266                 case DECADES: return plusYears(Math.multiplyExact(amountToAdd, 10));
 267                 case CENTURIES: return plusYears(Math.multiplyExact(amountToAdd, 100));
 268                 case MILLENNIA: return plusYears(Math.multiplyExact(amountToAdd, 1000));
 269             }
 270             throw new DateTimeException(unit.getName() + " not valid for CopticDate");
 271         }
 272         return unit.addTo(this, amountToAdd);
 273     }
 274 
 275     //-----------------------------------------------------------------------
 276     private CopticDate plusYears(long years) {
 277         return plusMonths(Math.multiplyExact(years, 13));
 278     }
 279 
 280     private CopticDate plusMonths(long months) {
 281         if (months == 0) {
 282             return this;
 283         }
 284         long curEm = prolepticYear * 13L + (month - 1);
 285         long calcEm = Math.addExact(curEm, months);
 286         int newYear = Math.toIntExact(Math.floorDiv(calcEm, 13));
 287         int newMonth = (int)Math.floorMod(calcEm, 13) + 1;
 288         return resolvePreviousValid(newYear, newMonth, day);
 289     }
 290 
 291     private CopticDate plusDays(long days) {
 292         if (days == 0) {
 293             return this;
 294         }
 295         return CopticDate.ofEpochDay(Math.addExact(toEpochDay(), days));
 296     }
 297 
 298     @Override
 299     public long periodUntil(Temporal endDateTime, TemporalUnit unit) {
 300         if (endDateTime instanceof ChronoLocalDate == false) {
 301             throw new DateTimeException("Unable to calculate period between objects of two different types");
 302         }
 303         ChronoLocalDate<?> end = (ChronoLocalDate<?>) endDateTime;
 304         if (getChronology().equals(end.getChronology()) == false) {
 305             throw new DateTimeException("Unable to calculate period between two different chronologies");
 306         }
 307         if (unit instanceof ChronoUnit) {
 308             return LocalDate.from(this).periodUntil(end, unit);  // TODO: this is wrong
 309         }
 310         return unit.between(this, endDateTime);
 311     }
 312 
 313     @Override
 314     public Period periodUntil(ChronoLocalDate<?> endDate) {
 315         // TODO: untested
 316         CopticDate end = (CopticDate) getChronology().date(endDate);
 317         long totalMonths = (end.prolepticYear - this.prolepticYear) * 13 + (end.month - this.month);  // safe
 318         int days = end.day - this.day;
 319         if (totalMonths > 0 && days < 0) {
 320             totalMonths--;
 321             CopticDate calcDate = this.plusMonths(totalMonths);
 322             days = (int) (end.toEpochDay() - calcDate.toEpochDay());  // safe
 323         } else if (totalMonths < 0 && days > 0) {
 324             totalMonths++;
 325             days -= end.lengthOfMonth();
 326         }
 327         long years = totalMonths / 13;  // safe
 328         int months = (int) (totalMonths % 13);  // safe
 329         return Period.of(Math.toIntExact(years), months, days);
 330     }
 331 
 332     //-----------------------------------------------------------------------
 333     @Override
 334     public long toEpochDay() {
 335         long year = (long) prolepticYear;
 336         long copticEpochDay = ((year - 1) * 365) + Math.floorDiv(year, 4) + (get(ChronoField.DAY_OF_YEAR) - 1);
 337         return copticEpochDay - EPOCH_DAY_DIFFERENCE;
 338     }
 339 
 340     @Override
 341     public String toString() {
 342         // getLong() reduces chances of exceptions in toString()
 343         long yoe = getLong(YEAR_OF_ERA);
 344         long moy = getLong(MONTH_OF_YEAR);
 345         long dom = getLong(DAY_OF_MONTH);
 346         StringBuilder buf = new StringBuilder(30);
 347         buf.append(getChronology().toString())
 348                 .append(" ")
 349                 .append(getEra())
 350                 .append(" ")
 351                 .append(yoe)
 352                 .append(moy < 10 ? "-0" : "-").append(moy)
 353                 .append(dom < 10 ? "-0" : "-").append(dom);
 354         return buf.toString();
 355     }
 356 }