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