1 /*
   2  * Copyright (c) 2012, 2013, 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.calendar;
  58 
  59 import java.io.Serializable;
  60 import java.time.DateTimeException;
  61 import java.time.LocalDate;
  62 import java.time.temporal.Chrono;
  63 import java.time.temporal.ChronoField;
  64 import java.time.temporal.ChronoLocalDate;
  65 import java.time.temporal.Era;
  66 import java.time.temporal.ISOChrono;
  67 import java.time.temporal.TemporalAccessor;
  68 import java.time.temporal.ValueRange;
  69 import java.time.temporal.Year;
  70 import java.util.Arrays;
  71 import java.util.Calendar;
  72 import java.util.HashMap;
  73 import java.util.List;
  74 import java.util.Locale;
  75 import java.util.Map;
  76 
  77 import sun.util.calendar.CalendarSystem;
  78 import sun.util.calendar.LocalGregorianCalendar;
  79 
  80 /**
  81  * The Japanese Imperial calendar system.
  82  * <p>
  83  * This chronology defines the rules of the Japanese Imperial calendar system.
  84  * This calendar system is primarily used in Japan.
  85  * The Japanese Imperial calendar system is the same as the ISO calendar system
  86  * apart from the era-based year numbering.
  87  * <p>
  88  * Only Meiji (1865-04-07 - 1868-09-07) and later eras are supported.
  89  * Older eras are handled as an unknown era where the year-of-era is the ISO year.
  90  *
  91  * <h3>Specification for implementors</h3>
  92  * This class is immutable and thread-safe.
  93  *
  94  * @since 1.8
  95  */
  96 public final class JapaneseChrono extends Chrono<JapaneseChrono> implements Serializable {
  97     // TODO: definition for unknown era may break requirement that year-of-era >= 1
  98 
  99     static final LocalGregorianCalendar JCAL =
 100         (LocalGregorianCalendar) CalendarSystem.forName("japanese");
 101 
 102     // Locale for creating a JapaneseImpericalCalendar.
 103     static final Locale LOCALE = Locale.forLanguageTag("ja-JP-u-ca-japanese");
 104 
 105     /**
 106      * Singleton instance for Japanese chronology.
 107      */
 108     public static final JapaneseChrono INSTANCE = new JapaneseChrono();
 109 
 110     /**
 111      * The singleton instance for the before Meiji era ( - 1868-09-07)
 112      * which has the value -999.
 113      */
 114     public static final Era<JapaneseChrono> ERA_SEIREKI = JapaneseEra.SEIREKI;
 115     /**
 116      * The singleton instance for the Meiji era (1868-09-08 - 1912-07-29)
 117      * which has the value -1.
 118      */
 119     public static final Era<JapaneseChrono> ERA_MEIJI = JapaneseEra.MEIJI;
 120     /**
 121      * The singleton instance for the Taisho era (1912-07-30 - 1926-12-24)
 122      * which has the value 0.
 123      */
 124     public static final Era<JapaneseChrono> ERA_TAISHO = JapaneseEra.TAISHO;
 125     /**
 126      * The singleton instance for the Showa era (1926-12-25 - 1989-01-07)
 127      * which has the value 1.
 128      */
 129     public static final Era<JapaneseChrono> ERA_SHOWA = JapaneseEra.SHOWA;
 130     /**
 131      * The singleton instance for the Heisei era (1989-01-08 - current)
 132      * which has the value 2.
 133      */
 134     public static final Era<JapaneseChrono> ERA_HEISEI = JapaneseEra.HEISEI;
 135     /**
 136      * Serialization version.
 137      */
 138     private static final long serialVersionUID = 459996390165777884L;
 139 
 140     //-----------------------------------------------------------------------
 141     /**
 142      * Restricted constructor.
 143      */
 144     private JapaneseChrono() {
 145     }
 146 
 147     /**
 148      * Resolve singleton.
 149      *
 150      * @return the singleton instance, not null
 151      */
 152     private Object readResolve() {
 153         return INSTANCE;
 154     }
 155 
 156     //-----------------------------------------------------------------------
 157     /**
 158      * Gets the ID of the chronology - 'Japanese'.
 159      * <p>
 160      * The ID uniquely identifies the {@code Chrono}.
 161      * It can be used to lookup the {@code Chrono} using {@link #of(String)}.
 162      *
 163      * @return the chronology ID - 'Japanese'
 164      * @see #getCalendarType()
 165      */
 166     @Override
 167     public String getId() {
 168         return "Japanese";
 169     }
 170 
 171     /**
 172      * Gets the calendar type of the underlying calendar system - 'japanese'.
 173      * <p>
 174      * The calendar type is an identifier defined by the
 175      * <em>Unicode Locale Data Markup Language (LDML)</em> specification.
 176      * It can be used to lookup the {@code Chrono} using {@link #of(String)}.
 177      * It can also be used as part of a locale, accessible via
 178      * {@link Locale#getUnicodeLocaleType(String)} with the key 'ca'.
 179      *
 180      * @return the calendar system type - 'japanese'
 181      * @see #getId()
 182      */
 183     @Override
 184     public String getCalendarType() {
 185         return "japanese";
 186     }
 187 
 188     //-----------------------------------------------------------------------
 189     @Override
 190     public ChronoLocalDate<JapaneseChrono> date(Era<JapaneseChrono> era, int yearOfEra, int month, int dayOfMonth) {
 191         if (era instanceof JapaneseEra == false) {
 192             throw new DateTimeException("Era must be JapaneseEra");
 193         }
 194         return JapaneseDate.of((JapaneseEra) era, yearOfEra, month, dayOfMonth);
 195     }
 196 
 197     @Override
 198     public ChronoLocalDate<JapaneseChrono> date(int prolepticYear, int month, int dayOfMonth) {
 199         return new JapaneseDate(LocalDate.of(prolepticYear, month, dayOfMonth));
 200     }
 201 
 202     @Override
 203     public ChronoLocalDate<JapaneseChrono> dateYearDay(int prolepticYear, int dayOfYear) {
 204         LocalDate date = LocalDate.ofYearDay(prolepticYear, dayOfYear);
 205         return date(prolepticYear, date.getMonthValue(), date.getDayOfMonth());
 206     }
 207 
 208     @Override
 209     public ChronoLocalDate<JapaneseChrono> date(TemporalAccessor temporal) {
 210         if (temporal instanceof JapaneseDate) {
 211             return (JapaneseDate) temporal;
 212         }
 213         return new JapaneseDate(LocalDate.from(temporal));
 214     }
 215 
 216     //-----------------------------------------------------------------------
 217     /**
 218      * Checks if the specified year is a leap year.
 219      * <p>
 220      * Japanese calendar leap years occur exactly in line with ISO leap years.
 221      * This method does not validate the year passed in, and only has a
 222      * well-defined result for years in the supported range.
 223      *
 224      * @param prolepticYear  the proleptic-year to check, not validated for range
 225      * @return true if the year is a leap year
 226      */
 227     @Override
 228     public boolean isLeapYear(long prolepticYear) {
 229         return ISOChrono.INSTANCE.isLeapYear(prolepticYear);
 230     }
 231 
 232     @Override
 233     public int prolepticYear(Era<JapaneseChrono> era, int yearOfEra) {
 234         if (era instanceof JapaneseEra == false) {
 235             throw new DateTimeException("Era must be JapaneseEra");
 236         }
 237         JapaneseEra jera = (JapaneseEra) era;
 238         int gregorianYear = jera.getPrivateEra().getSinceDate().getYear() + yearOfEra - 1;
 239         if (yearOfEra == 1) {
 240             return gregorianYear;
 241         }
 242         LocalGregorianCalendar.Date jdate = JCAL.newCalendarDate(null);
 243         jdate.setEra(jera.getPrivateEra()).setDate(yearOfEra, 1, 1);
 244         JCAL.normalize(jdate);
 245         if (jdate.getNormalizedYear() == gregorianYear) {
 246             return gregorianYear;
 247         }
 248         throw new DateTimeException("invalid yearOfEra value");
 249     }
 250 
 251     /**
 252      * Returns the calendar system era object from the given numeric value.
 253      *
 254      * See the description of each Era for the numeric values of:
 255      * {@link #ERA_HEISEI}, {@link #ERA_SHOWA},{@link #ERA_TAISHO},
 256      * {@link #ERA_MEIJI}), only Meiji and later eras are supported.
 257      * Prior to Meiji {@link #ERA_SEIREKI} is used.
 258      *
 259      * @param eraValue  the era value
 260      * @return the Japanese {@code Era} for the given numeric era value
 261      * @throws DateTimeException if {@code eraValue} is invalid
 262      */
 263     @Override
 264     public Era<JapaneseChrono> eraOf(int eraValue) {
 265         return JapaneseEra.of(eraValue);
 266     }
 267 
 268     @Override
 269     public List<Era<JapaneseChrono>> eras() {
 270         return Arrays.<Era<JapaneseChrono>>asList(JapaneseEra.values());
 271     }
 272 
 273     //-----------------------------------------------------------------------
 274     @Override
 275     public ValueRange range(ChronoField field) {
 276         switch (field) {
 277             case DAY_OF_MONTH:
 278             case DAY_OF_WEEK:
 279             case MICRO_OF_DAY:
 280             case MICRO_OF_SECOND:
 281             case HOUR_OF_DAY:
 282             case HOUR_OF_AMPM:
 283             case MINUTE_OF_DAY:
 284             case MINUTE_OF_HOUR:
 285             case SECOND_OF_DAY:
 286             case SECOND_OF_MINUTE:
 287             case MILLI_OF_DAY:
 288             case MILLI_OF_SECOND:
 289             case NANO_OF_DAY:
 290             case NANO_OF_SECOND:
 291             case CLOCK_HOUR_OF_DAY:
 292             case CLOCK_HOUR_OF_AMPM:
 293             case EPOCH_DAY:
 294             case EPOCH_MONTH:
 295                 return field.range();
 296         }
 297         Calendar jcal = Calendar.getInstance(LOCALE);
 298         int fieldIndex;
 299         switch (field) {
 300             case ERA:
 301                 return ValueRange.of(jcal.getMinimum(Calendar.ERA) - JapaneseEra.ERA_OFFSET,
 302                         jcal.getMaximum(Calendar.ERA) - JapaneseEra.ERA_OFFSET);
 303             case YEAR:
 304             case YEAR_OF_ERA:
 305                 return ValueRange.of(Year.MIN_VALUE, jcal.getGreatestMinimum(Calendar.YEAR),
 306                         jcal.getLeastMaximum(Calendar.YEAR), Year.MAX_VALUE);
 307             case MONTH_OF_YEAR:
 308                 return ValueRange.of(jcal.getMinimum(Calendar.MONTH) + 1, jcal.getGreatestMinimum(Calendar.MONTH) + 1,
 309                         jcal.getLeastMaximum(Calendar.MONTH) + 1, jcal.getMaximum(Calendar.MONTH) + 1);
 310             case DAY_OF_YEAR:
 311                 fieldIndex = Calendar.DAY_OF_YEAR;
 312                 break;
 313             default:
 314                  // TODO: review the remaining fields
 315                 throw new UnsupportedOperationException("Unimplementable field: " + field);
 316         }
 317         return ValueRange.of(jcal.getMinimum(fieldIndex), jcal.getGreatestMinimum(fieldIndex),
 318                 jcal.getLeastMaximum(fieldIndex), jcal.getMaximum(fieldIndex));
 319     }
 320 
 321 }