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.Year;
  72 import java.time.chrono.ChronoLocalDate;
  73 import java.time.temporal.ChronoField;
  74 import java.time.temporal.ChronoUnit;
  75 import java.time.temporal.Temporal;
  76 import java.time.temporal.TemporalField;
  77 import java.time.temporal.TemporalUnit;
  78 import java.time.temporal.ValueRange;
  79 import java.time.temporal.UnsupportedTemporalTypeException;
  80 
  81 /**
  82  * A date in the Coptic calendar system.
  83  * <p>
  84  * This implements {@code ChronoLocalDate} for the {@link CopticChronology Coptic calendar}.
  85  *
  86  * <h4>Implementation notes</h4>
  87  * This class is immutable and thread-safe.
  88  */
  89 public final class CopticDate
  90         implements ChronoLocalDate, Serializable {
  91 
  92     /**
  93      * Serialization version.
  94      */
  95     private static final long serialVersionUID = -7920528871688876868L;
  96     /**
  97      * The difference between the Coptic and Coptic epoch day count.
  98      */
  99     private static final int EPOCH_DAY_DIFFERENCE = 574971 + 40587;
 100 
 101     /**
 102      * The proleptic year.
 103      */
 104     private final int prolepticYear;
 105     /**
 106      * The month.
 107      */
 108     private final short month;
 109     /**
 110      * The day.
 111      */
 112     private final short day;
 113 
 114     //-----------------------------------------------------------------------
 115     /**
 116      * Creates an instance.
 117      *
 118      * @param epochDay  the epoch day to convert based on 1970-01-01 (ISO)
 119      * @return the Coptic date, not null
 120      * @throws DateTimeException if the date is invalid
 121      */
 122     static CopticDate ofEpochDay(long epochDay) {
 123         epochDay += EPOCH_DAY_DIFFERENCE;
 124         int prolepticYear = (int) (((epochDay * 4) + 1463) / 1461);
 125         int startYearEpochDay = (prolepticYear - 1) * 365 + (prolepticYear / 4);
 126         int doy0 = (int) (epochDay - startYearEpochDay);
 127         int month = doy0 / 30 + 1;
 128         int dom = doy0 % 30 + 1;
 129         return new CopticDate(prolepticYear, month, dom);
 130     }
 131 
 132     private static CopticDate resolvePreviousValid(int prolepticYear, int month, int day) {
 133         if (month == 13 && day > 5) {
 134             day = CopticChronology.INSTANCE.isLeapYear(prolepticYear) ? 6 : 5;
 135         }
 136         return new CopticDate(prolepticYear, month, day);
 137     }
 138 
 139     //-----------------------------------------------------------------------
 140     /**
 141      * Creates an instance.
 142      *
 143      * @param prolepticYear  the Coptic proleptic-year
 144      * @param month  the Coptic month, from 1 to 13
 145      * @param dayOfMonth  the Coptic day-of-month, from 1 to 30
 146      * @throws DateTimeException if the date is invalid
 147      */
 148     CopticDate(int prolepticYear, int month, int dayOfMonth) {
 149         CopticChronology.MOY_RANGE.checkValidValue(month, MONTH_OF_YEAR);
 150         ValueRange range;
 151         if (month == 13) {
 152             range = CopticChronology.INSTANCE.isLeapYear(prolepticYear) ? CopticChronology.DOM_RANGE_LEAP : CopticChronology.DOM_RANGE_NONLEAP;
 153         } else {
 154             range = CopticChronology.DOM_RANGE;
 155         }
 156         range.checkValidValue(dayOfMonth, DAY_OF_MONTH);
 157 
 158         this.prolepticYear = prolepticYear;
 159         this.month = (short) month;
 160         this.day = (short) dayOfMonth;
 161     }
 162 
 163     /**
 164      * Validates the object.
 165      *
 166      * @return the resolved date, not null
 167      */
 168     private Object readResolve() {
 169         // TODO: validate
 170         return this;
 171     }
 172 
 173     //-----------------------------------------------------------------------
 174     @Override
 175     public CopticChronology getChronology() {
 176         return CopticChronology.INSTANCE;
 177     }
 178 
 179     //-----------------------------------------------------------------------
 180     @Override
 181     public int lengthOfMonth() {
 182         switch (month) {
 183             case 13:
 184                 return (isLeapYear() ? 6 : 5);
 185             default:
 186                 return 30;
 187         }
 188     }
 189 
 190     @Override
 191     public ValueRange range(TemporalField field) {
 192         if (field instanceof ChronoField) {
 193             if (isSupported(field)) {
 194                 ChronoField f = (ChronoField) field;
 195                 switch (f) {
 196                     case DAY_OF_MONTH: return ValueRange.of(1, lengthOfMonth());
 197                     case DAY_OF_YEAR: return ValueRange.of(1, lengthOfYear());
 198                     case ALIGNED_WEEK_OF_MONTH: return ValueRange.of(1, month == 13 ? 1 : 5);
 199                     case YEAR:
 200                     case YEAR_OF_ERA: return (prolepticYear <= 0 ?
 201                             ValueRange.of(1, Year.MAX_VALUE + 1) : ValueRange.of(1, Year.MAX_VALUE));  // TODO
 202                 }
 203                 return getChronology().range(f);
 204             }
 205             throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
 206         }
 207         return field.rangeRefinedBy(this);
 208     }
 209 
 210     @Override
 211     public long getLong(TemporalField field) {
 212         if (field instanceof ChronoField) {
 213             switch ((ChronoField) field) {
 214                 case DAY_OF_WEEK: return Math.floorMod(toEpochDay() + 3, 7) + 1;
 215                 case ALIGNED_DAY_OF_WEEK_IN_MONTH: return ((day - 1) % 7) + 1;
 216                 case ALIGNED_DAY_OF_WEEK_IN_YEAR: return ((get(ChronoField.DAY_OF_YEAR) - 1) % 7) + 1;
 217                 case DAY_OF_MONTH: return day;
 218                 case DAY_OF_YEAR: return (month - 1) * 30 + day;
 219                 case EPOCH_DAY: return toEpochDay();
 220                 case ALIGNED_WEEK_OF_MONTH: return ((day - 1) / 7) + 1;
 221                 case ALIGNED_WEEK_OF_YEAR: return ((get(ChronoField.DAY_OF_YEAR) - 1) / 7) + 1;
 222                 case MONTH_OF_YEAR: return month;
 223                 case YEAR_OF_ERA: return (prolepticYear >= 1 ? prolepticYear : 1 - prolepticYear);
 224                 case YEAR: return prolepticYear;
 225                 case ERA: return (prolepticYear >= 1 ? 1 : 0);
 226             }
 227             throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
 228         }
 229         return field.getFrom(this);
 230     }
 231 
 232     @Override
 233     public CopticDate with(TemporalField field, long newValue) {
 234         if (field instanceof ChronoField) {
 235             ChronoField f = (ChronoField) field;
 236             f.checkValidValue(newValue);        // TODO: validate value
 237             int nvalue = (int) newValue;
 238             switch (f) {
 239                 case DAY_OF_WEEK: return plusDays(newValue - get(ChronoField.DAY_OF_WEEK));
 240                 case ALIGNED_DAY_OF_WEEK_IN_MONTH: return plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_MONTH));
 241                 case ALIGNED_DAY_OF_WEEK_IN_YEAR: return plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_YEAR));
 242                 case DAY_OF_MONTH: return resolvePreviousValid(prolepticYear, month, nvalue);
 243                 case DAY_OF_YEAR: return resolvePreviousValid(prolepticYear, ((nvalue - 1) / 30) + 1, ((nvalue - 1) % 30) + 1);
 244                 case EPOCH_DAY: return ofEpochDay(nvalue);
 245                 case ALIGNED_WEEK_OF_MONTH: return plusDays((newValue - getLong(ALIGNED_WEEK_OF_MONTH)) * 7);
 246                 case ALIGNED_WEEK_OF_YEAR: return plusDays((newValue - getLong(ALIGNED_WEEK_OF_YEAR)) * 7);
 247                 case MONTH_OF_YEAR: return resolvePreviousValid(prolepticYear, nvalue, day);
 248                 case YEAR_OF_ERA: return resolvePreviousValid(prolepticYear >= 1 ? nvalue : 1 - nvalue, month, day);
 249                 case YEAR: return resolvePreviousValid(nvalue, month, day);
 250                 case ERA: return resolvePreviousValid(1 - prolepticYear, month, day);
 251             }
 252             throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
 253         }
 254         return field.adjustInto(this, newValue);
 255     }
 256 
 257     //-----------------------------------------------------------------------
 258     @Override
 259     public CopticDate plus(long amountToAdd, TemporalUnit unit) {
 260         if (unit instanceof ChronoUnit) {
 261             ChronoUnit f = (ChronoUnit) unit;
 262             switch (f) {
 263                 case DAYS: return plusDays(amountToAdd);
 264                 case WEEKS: return plusDays(Math.multiplyExact(amountToAdd, 7));
 265                 case MONTHS: return plusMonths(amountToAdd);
 266                 case YEARS: return plusYears(amountToAdd);
 267                 case DECADES: return plusYears(Math.multiplyExact(amountToAdd, 10));
 268                 case CENTURIES: return plusYears(Math.multiplyExact(amountToAdd, 100));
 269                 case MILLENNIA: return plusYears(Math.multiplyExact(amountToAdd, 1000));
 270             }
 271             throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
 272         }
 273         return unit.addTo(this, amountToAdd);
 274     }
 275 
 276     //-----------------------------------------------------------------------
 277     private CopticDate plusYears(long years) {
 278         return plusMonths(Math.multiplyExact(years, 13));
 279     }
 280 
 281     private CopticDate plusMonths(long months) {
 282         if (months == 0) {
 283             return this;
 284         }
 285         long curEm = prolepticYear * 13L + (month - 1);
 286         long calcEm = Math.addExact(curEm, months);
 287         int newYear = Math.toIntExact(Math.floorDiv(calcEm, 13));
 288         int newMonth = (int)Math.floorMod(calcEm, 13) + 1;
 289         return resolvePreviousValid(newYear, newMonth, day);
 290     }
 291 
 292     private CopticDate plusDays(long days) {
 293         if (days == 0) {
 294             return this;
 295         }
 296         return CopticDate.ofEpochDay(Math.addExact(toEpochDay(), days));
 297     }
 298 
 299     @Override
 300     public long until(Temporal endDateTime, TemporalUnit unit) {
 301         if (endDateTime instanceof ChronoLocalDate == false) {
 302             throw new DateTimeException("Unable to calculate period between objects of two different types");
 303         }
 304         ChronoLocalDate end = (ChronoLocalDate) endDateTime;
 305         if (getChronology().equals(end.getChronology()) == false) {
 306             throw new DateTimeException("Unable to calculate period between two different chronologies");
 307         }
 308         if (unit instanceof ChronoUnit) {
 309             return LocalDate.from(this).until(end, unit);  // TODO: this is wrong
 310         }
 311         return unit.between(this, endDateTime);
 312     }
 313 
 314     @Override
 315     public Period until(ChronoLocalDate endDate) {
 316         // TODO: untested
 317         CopticDate end = (CopticDate) getChronology().date(endDate);
 318         long totalMonths = (end.prolepticYear - this.prolepticYear) * 13 + (end.month - this.month);  // safe
 319         int days = end.day - this.day;
 320         if (totalMonths > 0 && days < 0) {
 321             totalMonths--;
 322             CopticDate calcDate = this.plusMonths(totalMonths);
 323             days = (int) (end.toEpochDay() - calcDate.toEpochDay());  // safe
 324         } else if (totalMonths < 0 && days > 0) {
 325             totalMonths++;
 326             days -= end.lengthOfMonth();
 327         }
 328         long years = totalMonths / 13;  // safe
 329         int months = (int) (totalMonths % 13);  // safe
 330         return Period.of(Math.toIntExact(years), months, days);
 331     }
 332 
 333     //-----------------------------------------------------------------------
 334     @Override
 335     public long toEpochDay() {
 336         long year = (long) prolepticYear;
 337         long copticEpochDay = ((year - 1) * 365) + Math.floorDiv(year, 4) + (get(ChronoField.DAY_OF_YEAR) - 1);
 338         return copticEpochDay - EPOCH_DAY_DIFFERENCE;
 339     }
 340 
 341     @Override
 342     public String toString() {
 343         // getLong() reduces chances of exceptions in toString()
 344         long yoe = getLong(YEAR_OF_ERA);
 345         long moy = getLong(MONTH_OF_YEAR);
 346         long dom = getLong(DAY_OF_MONTH);
 347         StringBuilder buf = new StringBuilder(30);
 348         buf.append(getChronology().toString())
 349                 .append(" ")
 350                 .append(getEra())
 351                 .append(" ")
 352                 .append(yoe)
 353                 .append(moy < 10 ? "-0" : "-").append(moy)
 354                 .append(dom < 10 ? "-0" : "-").append(dom);
 355         return buf.toString();
 356     }
 357 }