1 /*
   2  * Copyright (c) 2005, 2018, 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 package java.util;
  27 
  28 import java.io.IOException;
  29 import java.io.ObjectInputStream;
  30 import sun.util.locale.provider.CalendarDataUtility;
  31 import sun.util.calendar.BaseCalendar;
  32 import sun.util.calendar.CalendarDate;
  33 import sun.util.calendar.CalendarSystem;
  34 import sun.util.calendar.CalendarUtils;
  35 import sun.util.calendar.Era;
  36 import sun.util.calendar.Gregorian;
  37 import sun.util.calendar.LocalGregorianCalendar;
  38 import sun.util.calendar.ZoneInfo;
  39 
  40 /**
  41  * {@code JapaneseImperialCalendar} implements a Japanese
  42  * calendar system in which the imperial era-based year numbering is
  43  * supported from the Meiji era. The following are the eras supported
  44  * by this calendar system.
  45  * <pre>{@code
  46  * ERA value   Era name    Since (in Gregorian)
  47  * ------------------------------------------------------
  48  *     0       N/A         N/A
  49  *     1       Meiji       1868-01-01T00:00:00 local time
  50  *     2       Taisho      1912-07-30T00:00:00 local time
  51  *     3       Showa       1926-12-25T00:00:00 local time
  52  *     4       Heisei      1989-01-08T00:00:00 local time
  53  *     5       NewEra      2019-05-01T00:00:00 local time
  54  * ------------------------------------------------------
  55  * }</pre>
  56  *
  57  * <p>{@code ERA} value 0 specifies the years before Meiji and
  58  * the Gregorian year values are used. Unlike
  59  * {@link GregorianCalendar}, the Julian to Gregorian transition is not
  60  * supported because it doesn't make any sense to the Japanese
  61  * calendar systems used before Meiji. To represent the years before
  62  * Gregorian year 1, 0 and negative values are used. The Japanese
  63  * Imperial rescripts and government decrees don't specify how to deal
  64  * with time differences for applying the era transitions. This
  65  * calendar implementation assumes local time for all transitions.
  66  *
  67  * <p>A new era can be specified using property
  68  * jdk.calendar.japanese.supplemental.era. The new era is added to the
  69  * predefined eras. The syntax of the property is as follows.
  70  * <pre>
  71  *   {@code name=<name>,abbr=<abbr>,since=<time['u']>}
  72  * </pre>
  73  * where
  74  * <dl>
  75  * <dt>{@code <name>:}<dd>the full name of the new era (non-ASCII characters allowed,
  76  * either in platform's native encoding or in Unicode escape notation, {@code \\uXXXX})
  77  * <dt>{@code <abbr>:}<dd>the abbreviation of the new era (non-ASCII characters allowed,
  78  * either in platform's native encoding or in Unicode escape notation, {@code \\uXXXX})
  79  * <dt>{@code <time['u']>:}<dd>the start time of the new era represented by
  80  * milliseconds from 1970-01-01T00:00:00 local time or UTC if {@code 'u'} is
  81  * appended to the milliseconds value. (ASCII digits only)
  82  * </dl>
  83  *
  84  * <p>If the given era is invalid, such as the since value before the
  85  * beginning of the last predefined era, the given era will be
  86  * ignored.
  87  *
  88  * <p>The following is an example of the property usage.
  89  * <pre>
  90  *   java -Djdk.calendar.japanese.supplemental.era="name=NewEra,abbr=N,since=253374307200000"
  91  * </pre>
  92  * The property specifies an era change to NewEra at 9999-02-11T00:00:00 local time.
  93  *
  94  * @author Masayoshi Okutsu
  95  * @since 1.6
  96  */
  97 class JapaneseImperialCalendar extends Calendar {
  98     /*
  99      * Implementation Notes
 100      *
 101      * This implementation uses
 102      * sun.util.calendar.LocalGregorianCalendar to perform most of the
 103      * calendar calculations.
 104      */
 105 
 106     /**
 107      * The ERA constant designating the era before Meiji.
 108      */
 109     public static final int BEFORE_MEIJI = 0;
 110 
 111     /**
 112      * The ERA constant designating the Meiji era.
 113      */
 114     public static final int MEIJI = 1;
 115 
 116     /**
 117      * The ERA constant designating the Taisho era.
 118      */
 119     public static final int TAISHO = 2;
 120 
 121     /**
 122      * The ERA constant designating the Showa era.
 123      */
 124     public static final int SHOWA = 3;
 125 
 126     /**
 127      * The ERA constant designating the Heisei era.
 128      */
 129     public static final int HEISEI = 4;
 130 
 131     /**
 132      * The ERA constant designating the NewEra era.
 133      */
 134     private static final int NEWERA = 5;
 135 
 136     private static final int EPOCH_OFFSET   = 719163; // Fixed date of January 1, 1970 (Gregorian)
 137 
 138     // Useful millisecond constants.  Although ONE_DAY and ONE_WEEK can fit
 139     // into ints, they must be longs in order to prevent arithmetic overflow
 140     // when performing (bug 4173516).
 141     private static final int  ONE_SECOND = 1000;
 142     private static final int  ONE_MINUTE = 60*ONE_SECOND;
 143     private static final int  ONE_HOUR   = 60*ONE_MINUTE;
 144     private static final long ONE_DAY    = 24*ONE_HOUR;
 145 
 146     // Reference to the sun.util.calendar.LocalGregorianCalendar instance (singleton).
 147     private static final LocalGregorianCalendar jcal
 148         = (LocalGregorianCalendar) CalendarSystem.forName("japanese");
 149 
 150     // Gregorian calendar instance. This is required because era
 151     // transition dates are given in Gregorian dates.
 152     private static final Gregorian gcal = CalendarSystem.getGregorianCalendar();
 153 
 154     // The Era instance representing "before Meiji".
 155     private static final Era BEFORE_MEIJI_ERA = new Era("BeforeMeiji", "BM", Long.MIN_VALUE, false);
 156 
 157     // Imperial eras. The sun.util.calendar.LocalGregorianCalendar
 158     // doesn't have an Era representing before Meiji, which is
 159     // inconvenient for a Calendar. So, era[0] is a reference to
 160     // BEFORE_MEIJI_ERA.
 161     private static final Era[] eras;
 162 
 163     // Fixed date of the first date of each era.
 164     private static final long[] sinceFixedDates;
 165 
 166     // The current era
 167     private static final int currentEra;
 168 
 169     /*
 170      * <pre>
 171      *                                 Greatest       Least
 172      * Field name             Minimum   Minimum     Maximum     Maximum
 173      * ----------             -------   -------     -------     -------
 174      * ERA                          0         0           1           1
 175      * YEAR                -292275055         1           ?           ?
 176      * MONTH                        0         0          11          11
 177      * WEEK_OF_YEAR                 1         1          52*         53
 178      * WEEK_OF_MONTH                0         0           4*          6
 179      * DAY_OF_MONTH                 1         1          28*         31
 180      * DAY_OF_YEAR                  1         1         365*        366
 181      * DAY_OF_WEEK                  1         1           7           7
 182      * DAY_OF_WEEK_IN_MONTH        -1        -1           4*          6
 183      * AM_PM                        0         0           1           1
 184      * HOUR                         0         0          11          11
 185      * HOUR_OF_DAY                  0         0          23          23
 186      * MINUTE                       0         0          59          59
 187      * SECOND                       0         0          59          59
 188      * MILLISECOND                  0         0         999         999
 189      * ZONE_OFFSET             -13:00    -13:00       14:00       14:00
 190      * DST_OFFSET                0:00      0:00        0:20        2:00
 191      * </pre>
 192      * *: depends on eras
 193      */
 194     static final int MIN_VALUES[] = {
 195         0,              // ERA
 196         -292275055,     // YEAR
 197         JANUARY,        // MONTH
 198         1,              // WEEK_OF_YEAR
 199         0,              // WEEK_OF_MONTH
 200         1,              // DAY_OF_MONTH
 201         1,              // DAY_OF_YEAR
 202         SUNDAY,         // DAY_OF_WEEK
 203         1,              // DAY_OF_WEEK_IN_MONTH
 204         AM,             // AM_PM
 205         0,              // HOUR
 206         0,              // HOUR_OF_DAY
 207         0,              // MINUTE
 208         0,              // SECOND
 209         0,              // MILLISECOND
 210         -13*ONE_HOUR,   // ZONE_OFFSET (UNIX compatibility)
 211         0               // DST_OFFSET
 212     };
 213     static final int LEAST_MAX_VALUES[] = {
 214         0,              // ERA (initialized later)
 215         0,              // YEAR (initialized later)
 216         JANUARY,        // MONTH (Showa 64 ended in January.)
 217         0,              // WEEK_OF_YEAR (Showa 1 has only 6 days which could be 0 weeks.)
 218         4,              // WEEK_OF_MONTH
 219         28,             // DAY_OF_MONTH
 220         0,              // DAY_OF_YEAR (initialized later)
 221         SATURDAY,       // DAY_OF_WEEK
 222         4,              // DAY_OF_WEEK_IN
 223         PM,             // AM_PM
 224         11,             // HOUR
 225         23,             // HOUR_OF_DAY
 226         59,             // MINUTE
 227         59,             // SECOND
 228         999,            // MILLISECOND
 229         14*ONE_HOUR,    // ZONE_OFFSET
 230         20*ONE_MINUTE   // DST_OFFSET (historical least maximum)
 231     };
 232     static final int MAX_VALUES[] = {
 233         0,              // ERA
 234         292278994,      // YEAR
 235         DECEMBER,       // MONTH
 236         53,             // WEEK_OF_YEAR
 237         6,              // WEEK_OF_MONTH
 238         31,             // DAY_OF_MONTH
 239         366,            // DAY_OF_YEAR
 240         SATURDAY,       // DAY_OF_WEEK
 241         6,              // DAY_OF_WEEK_IN
 242         PM,             // AM_PM
 243         11,             // HOUR
 244         23,             // HOUR_OF_DAY
 245         59,             // MINUTE
 246         59,             // SECOND
 247         999,            // MILLISECOND
 248         14*ONE_HOUR,    // ZONE_OFFSET
 249         2*ONE_HOUR      // DST_OFFSET (double summer time)
 250     };
 251 
 252     // Proclaim serialization compatibility with JDK 1.6
 253     @SuppressWarnings("FieldNameHidesFieldInSuperclass")
 254     private static final long serialVersionUID = -3364572813905467929L;
 255 
 256     static {
 257         Era[] es = jcal.getEras();
 258         int length = es.length + 1;
 259         eras = new Era[length];
 260         sinceFixedDates = new long[length];
 261 
 262         // eras[BEFORE_MEIJI] and sinceFixedDate[BEFORE_MEIJI] are the
 263         // same as Gregorian.
 264         int index = BEFORE_MEIJI;
 265         int current = index;
 266         sinceFixedDates[index] = gcal.getFixedDate(BEFORE_MEIJI_ERA.getSinceDate());
 267         eras[index++] = BEFORE_MEIJI_ERA;
 268         for (Era e : es) {
 269             if(e.getSince(TimeZone.NO_TIMEZONE) < System.currentTimeMillis()) {
 270                 current = index;
 271             }
 272             CalendarDate d = e.getSinceDate();
 273             sinceFixedDates[index] = gcal.getFixedDate(d);
 274             eras[index++] = e;
 275         }
 276         currentEra = current;
 277 
 278         LEAST_MAX_VALUES[ERA] = MAX_VALUES[ERA] = eras.length - 1;
 279 
 280         // Calculate the least maximum year and least day of Year
 281         // values. The following code assumes that there's at most one
 282         // era transition in a Gregorian year.
 283         int year = Integer.MAX_VALUE;
 284         int dayOfYear = Integer.MAX_VALUE;
 285         CalendarDate date = gcal.newCalendarDate(TimeZone.NO_TIMEZONE);
 286         for (int i = 1; i < eras.length; i++) {
 287             long fd = sinceFixedDates[i];
 288             CalendarDate transitionDate = eras[i].getSinceDate();
 289             date.setDate(transitionDate.getYear(), BaseCalendar.JANUARY, 1);
 290             long fdd = gcal.getFixedDate(date);
 291             if (fd != fdd) {
 292                 dayOfYear = Math.min((int)(fd - fdd) + 1, dayOfYear);
 293             }
 294             date.setDate(transitionDate.getYear(), BaseCalendar.DECEMBER, 31);
 295             fdd = gcal.getFixedDate(date);
 296             if (fd != fdd) {
 297                 dayOfYear = Math.min((int)(fdd - fd) + 1, dayOfYear);
 298             }
 299             LocalGregorianCalendar.Date lgd = getCalendarDate(fd - 1);
 300             int y = lgd.getYear();
 301             // Unless the first year starts from January 1, the actual
 302             // max value could be one year short. For example, if it's
 303             // Showa 63 January 8, 63 is the actual max value since
 304             // Showa 64 January 8 doesn't exist.
 305             if (!(lgd.getMonth() == BaseCalendar.JANUARY && lgd.getDayOfMonth() == 1)) {
 306                 y--;
 307             }
 308             year = Math.min(y, year);
 309         }
 310         LEAST_MAX_VALUES[YEAR] = year; // Max year could be smaller than this value.
 311         LEAST_MAX_VALUES[DAY_OF_YEAR] = dayOfYear;
 312     }
 313 
 314     /**
 315      * jdate always has a sun.util.calendar.LocalGregorianCalendar.Date instance to
 316      * avoid overhead of creating it for each calculation.
 317      */
 318     private transient LocalGregorianCalendar.Date jdate;
 319 
 320     /**
 321      * Temporary int[2] to get time zone offsets. zoneOffsets[0] gets
 322      * the GMT offset value and zoneOffsets[1] gets the daylight saving
 323      * value.
 324      */
 325     private transient int[] zoneOffsets;
 326 
 327     /**
 328      * Temporary storage for saving original fields[] values in
 329      * non-lenient mode.
 330      */
 331     private transient int[] originalFields;
 332 
 333     /**
 334      * Constructs a {@code JapaneseImperialCalendar} based on the current time
 335      * in the given time zone with the given locale.
 336      *
 337      * @param zone the given time zone.
 338      * @param aLocale the given locale.
 339      */
 340     JapaneseImperialCalendar(TimeZone zone, Locale aLocale) {
 341         super(zone, aLocale);
 342         jdate = jcal.newCalendarDate(zone);
 343         setTimeInMillis(System.currentTimeMillis());
 344     }
 345 
 346     /**
 347      * Constructs an "empty" {@code JapaneseImperialCalendar}.
 348      *
 349      * @param zone    the given time zone
 350      * @param aLocale the given locale
 351      * @param flag    the flag requesting an empty instance
 352      */
 353     JapaneseImperialCalendar(TimeZone zone, Locale aLocale, boolean flag) {
 354         super(zone, aLocale);
 355         jdate = jcal.newCalendarDate(zone);
 356     }
 357 
 358     /**
 359      * Returns {@code "japanese"} as the calendar type of this {@code
 360      * JapaneseImperialCalendar}.
 361      *
 362      * @return {@code "japanese"}
 363      */
 364     @Override
 365     public String getCalendarType() {
 366         return "japanese";
 367     }
 368 
 369     /**
 370      * Compares this {@code JapaneseImperialCalendar} to the specified
 371      * {@code Object}. The result is {@code true} if and
 372      * only if the argument is a {@code JapaneseImperialCalendar} object
 373      * that represents the same time value (millisecond offset from
 374      * the <a href="Calendar.html#Epoch">Epoch</a>) under the same
 375      * {@code Calendar} parameters.
 376      *
 377      * @param obj the object to compare with.
 378      * @return {@code true} if this object is equal to {@code obj};
 379      * {@code false} otherwise.
 380      * @see Calendar#compareTo(Calendar)
 381      */
 382     @Override
 383     public boolean equals(Object obj) {
 384         return obj instanceof JapaneseImperialCalendar &&
 385             super.equals(obj);
 386     }
 387 
 388     /**
 389      * Generates the hash code for this
 390      * {@code JapaneseImperialCalendar} object.
 391      */
 392     @Override
 393     public int hashCode() {
 394         return super.hashCode() ^ jdate.hashCode();
 395     }
 396 
 397     /**
 398      * Adds the specified (signed) amount of time to the given calendar field,
 399      * based on the calendar's rules.
 400      *
 401      * <p><em>Add rule 1</em>. The value of {@code field}
 402      * after the call minus the value of {@code field} before the
 403      * call is {@code amount}, modulo any overflow that has occurred in
 404      * {@code field}. Overflow occurs when a field value exceeds its
 405      * range and, as a result, the next larger field is incremented or
 406      * decremented and the field value is adjusted back into its range.</p>
 407      *
 408      * <p><em>Add rule 2</em>. If a smaller field is expected to be
 409      * invariant, but it is impossible for it to be equal to its
 410      * prior value because of changes in its minimum or maximum after
 411      * {@code field} is changed, then its value is adjusted to be as close
 412      * as possible to its expected value. A smaller field represents a
 413      * smaller unit of time. {@code HOUR} is a smaller field than
 414      * {@code DAY_OF_MONTH}. No adjustment is made to smaller fields
 415      * that are not expected to be invariant. The calendar system
 416      * determines what fields are expected to be invariant.</p>
 417      *
 418      * @param field the calendar field.
 419      * @param amount the amount of date or time to be added to the field.
 420      * @exception IllegalArgumentException if {@code field} is
 421      * {@code ZONE_OFFSET}, {@code DST_OFFSET}, or unknown,
 422      * or if any calendar fields have out-of-range values in
 423      * non-lenient mode.
 424      */
 425     @Override
 426     public void add(int field, int amount) {
 427         // If amount == 0, do nothing even the given field is out of
 428         // range. This is tested by JCK.
 429         if (amount == 0) {
 430             return;   // Do nothing!
 431         }
 432 
 433         if (field < 0 || field >= ZONE_OFFSET) {
 434             throw new IllegalArgumentException();
 435         }
 436 
 437         // Sync the time and calendar fields.
 438         complete();
 439 
 440         if (field == YEAR) {
 441             LocalGregorianCalendar.Date d = (LocalGregorianCalendar.Date) jdate.clone();
 442             d.addYear(amount);
 443             pinDayOfMonth(d);
 444             set(ERA, getEraIndex(d));
 445             set(YEAR, d.getYear());
 446             set(MONTH, d.getMonth() - 1);
 447             set(DAY_OF_MONTH, d.getDayOfMonth());
 448         } else if (field == MONTH) {
 449             LocalGregorianCalendar.Date d = (LocalGregorianCalendar.Date) jdate.clone();
 450             d.addMonth(amount);
 451             pinDayOfMonth(d);
 452             set(ERA, getEraIndex(d));
 453             set(YEAR, d.getYear());
 454             set(MONTH, d.getMonth() - 1);
 455             set(DAY_OF_MONTH, d.getDayOfMonth());
 456         } else if (field == ERA) {
 457             int era = internalGet(ERA) + amount;
 458             if (era < 0) {
 459                 era = 0;
 460             } else if (era > eras.length - 1) {
 461                 era = eras.length - 1;
 462             }
 463             set(ERA, era);
 464         } else {
 465             long delta = amount;
 466             long timeOfDay = 0;
 467             switch (field) {
 468             // Handle the time fields here. Convert the given
 469             // amount to milliseconds and call setTimeInMillis.
 470             case HOUR:
 471             case HOUR_OF_DAY:
 472                 delta *= 60 * 60 * 1000;        // hours to milliseconds
 473                 break;
 474 
 475             case MINUTE:
 476                 delta *= 60 * 1000;             // minutes to milliseconds
 477                 break;
 478 
 479             case SECOND:
 480                 delta *= 1000;                  // seconds to milliseconds
 481                 break;
 482 
 483             case MILLISECOND:
 484                 break;
 485 
 486             // Handle week, day and AM_PM fields which involves
 487             // time zone offset change adjustment. Convert the
 488             // given amount to the number of days.
 489             case WEEK_OF_YEAR:
 490             case WEEK_OF_MONTH:
 491             case DAY_OF_WEEK_IN_MONTH:
 492                 delta *= 7;
 493                 break;
 494 
 495             case DAY_OF_MONTH: // synonym of DATE
 496             case DAY_OF_YEAR:
 497             case DAY_OF_WEEK:
 498                 break;
 499 
 500             case AM_PM:
 501                 // Convert the amount to the number of days (delta)
 502                 // and +12 or -12 hours (timeOfDay).
 503                 delta = amount / 2;
 504                 timeOfDay = 12 * (amount % 2);
 505                 break;
 506             }
 507 
 508             // The time fields don't require time zone offset change
 509             // adjustment.
 510             if (field >= HOUR) {
 511                 setTimeInMillis(time + delta);
 512                 return;
 513             }
 514 
 515             // The rest of the fields (week, day or AM_PM fields)
 516             // require time zone offset (both GMT and DST) change
 517             // adjustment.
 518 
 519             // Translate the current time to the fixed date and time
 520             // of the day.
 521             long fd = cachedFixedDate;
 522             timeOfDay += internalGet(HOUR_OF_DAY);
 523             timeOfDay *= 60;
 524             timeOfDay += internalGet(MINUTE);
 525             timeOfDay *= 60;
 526             timeOfDay += internalGet(SECOND);
 527             timeOfDay *= 1000;
 528             timeOfDay += internalGet(MILLISECOND);
 529             if (timeOfDay >= ONE_DAY) {
 530                 fd++;
 531                 timeOfDay -= ONE_DAY;
 532             } else if (timeOfDay < 0) {
 533                 fd--;
 534                 timeOfDay += ONE_DAY;
 535             }
 536 
 537             fd += delta; // fd is the expected fixed date after the calculation
 538             int zoneOffset = internalGet(ZONE_OFFSET) + internalGet(DST_OFFSET);
 539             setTimeInMillis((fd - EPOCH_OFFSET) * ONE_DAY + timeOfDay - zoneOffset);
 540             zoneOffset -= internalGet(ZONE_OFFSET) + internalGet(DST_OFFSET);
 541             // If the time zone offset has changed, then adjust the difference.
 542             if (zoneOffset != 0) {
 543                 setTimeInMillis(time + zoneOffset);
 544                 long fd2 = cachedFixedDate;
 545                 // If the adjustment has changed the date, then take
 546                 // the previous one.
 547                 if (fd2 != fd) {
 548                     setTimeInMillis(time - zoneOffset);
 549                 }
 550             }
 551         }
 552     }
 553 
 554     @Override
 555     public void roll(int field, boolean up) {
 556         roll(field, up ? +1 : -1);
 557     }
 558 
 559     /**
 560      * Adds a signed amount to the specified calendar field without changing larger fields.
 561      * A negative roll amount means to subtract from field without changing
 562      * larger fields. If the specified amount is 0, this method performs nothing.
 563      *
 564      * <p>This method calls {@link #complete()} before adding the
 565      * amount so that all the calendar fields are normalized. If there
 566      * is any calendar field having an out-of-range value in non-lenient mode, then an
 567      * {@code IllegalArgumentException} is thrown.
 568      *
 569      * @param field the calendar field.
 570      * @param amount the signed amount to add to {@code field}.
 571      * @exception IllegalArgumentException if {@code field} is
 572      * {@code ZONE_OFFSET}, {@code DST_OFFSET}, or unknown,
 573      * or if any calendar fields have out-of-range values in
 574      * non-lenient mode.
 575      * @see #roll(int,boolean)
 576      * @see #add(int,int)
 577      * @see #set(int,int)
 578      */
 579     @Override
 580     public void roll(int field, int amount) {
 581         // If amount == 0, do nothing even the given field is out of
 582         // range. This is tested by JCK.
 583         if (amount == 0) {
 584             return;
 585         }
 586 
 587         if (field < 0 || field >= ZONE_OFFSET) {
 588             throw new IllegalArgumentException();
 589         }
 590 
 591         // Sync the time and calendar fields.
 592         complete();
 593 
 594         int min = getMinimum(field);
 595         int max = getMaximum(field);
 596 
 597         switch (field) {
 598         case ERA:
 599         case AM_PM:
 600         case MINUTE:
 601         case SECOND:
 602         case MILLISECOND:
 603             // These fields are handled simply, since they have fixed
 604             // minima and maxima. Other fields are complicated, since
 605             // the range within they must roll varies depending on the
 606             // date, a time zone and the era transitions.
 607             break;
 608 
 609         case HOUR:
 610         case HOUR_OF_DAY:
 611             {
 612                 int unit = max + 1; // 12 or 24 hours
 613                 int h = internalGet(field);
 614                 int nh = (h + amount) % unit;
 615                 if (nh < 0) {
 616                     nh += unit;
 617                 }
 618                 time += ONE_HOUR * (nh - h);
 619 
 620                 // The day might have changed, which could happen if
 621                 // the daylight saving time transition brings it to
 622                 // the next day, although it's very unlikely. But we
 623                 // have to make sure not to change the larger fields.
 624                 CalendarDate d = jcal.getCalendarDate(time, getZone());
 625                 if (internalGet(DAY_OF_MONTH) != d.getDayOfMonth()) {
 626                     d.setEra(jdate.getEra());
 627                     d.setDate(internalGet(YEAR),
 628                               internalGet(MONTH) + 1,
 629                               internalGet(DAY_OF_MONTH));
 630                     if (field == HOUR) {
 631                         assert (internalGet(AM_PM) == PM);
 632                         d.addHours(+12); // restore PM
 633                     }
 634                     time = jcal.getTime(d);
 635                 }
 636                 int hourOfDay = d.getHours();
 637                 internalSet(field, hourOfDay % unit);
 638                 if (field == HOUR) {
 639                     internalSet(HOUR_OF_DAY, hourOfDay);
 640                 } else {
 641                     internalSet(AM_PM, hourOfDay / 12);
 642                     internalSet(HOUR, hourOfDay % 12);
 643                 }
 644 
 645                 // Time zone offset and/or daylight saving might have changed.
 646                 int zoneOffset = d.getZoneOffset();
 647                 int saving = d.getDaylightSaving();
 648                 internalSet(ZONE_OFFSET, zoneOffset - saving);
 649                 internalSet(DST_OFFSET, saving);
 650                 return;
 651             }
 652 
 653         case YEAR:
 654             min = getActualMinimum(field);
 655             max = getActualMaximum(field);
 656             break;
 657 
 658         case MONTH:
 659             // Rolling the month involves both pinning the final value to [0, 11]
 660             // and adjusting the DAY_OF_MONTH if necessary.  We only adjust the
 661             // DAY_OF_MONTH if, after updating the MONTH field, it is illegal.
 662             // E.g., <jan31>.roll(MONTH, 1) -> <feb28> or <feb29>.
 663             {
 664                 if (!isTransitionYear(jdate.getNormalizedYear())) {
 665                     int year = jdate.getYear();
 666                     if (year == getMaximum(YEAR)) {
 667                         CalendarDate jd = jcal.getCalendarDate(time, getZone());
 668                         CalendarDate d = jcal.getCalendarDate(Long.MAX_VALUE, getZone());
 669                         max = d.getMonth() - 1;
 670                         int n = getRolledValue(internalGet(field), amount, min, max);
 671                         if (n == max) {
 672                             // To avoid overflow, use an equivalent year.
 673                             jd.addYear(-400);
 674                             jd.setMonth(n + 1);
 675                             if (jd.getDayOfMonth() > d.getDayOfMonth()) {
 676                                 jd.setDayOfMonth(d.getDayOfMonth());
 677                                 jcal.normalize(jd);
 678                             }
 679                             if (jd.getDayOfMonth() == d.getDayOfMonth()
 680                                 && jd.getTimeOfDay() > d.getTimeOfDay()) {
 681                                 jd.setMonth(n + 1);
 682                                 jd.setDayOfMonth(d.getDayOfMonth() - 1);
 683                                 jcal.normalize(jd);
 684                                 // Month may have changed by the normalization.
 685                                 n = jd.getMonth() - 1;
 686                             }
 687                             set(DAY_OF_MONTH, jd.getDayOfMonth());
 688                         }
 689                         set(MONTH, n);
 690                     } else if (year == getMinimum(YEAR)) {
 691                         CalendarDate jd = jcal.getCalendarDate(time, getZone());
 692                         CalendarDate d = jcal.getCalendarDate(Long.MIN_VALUE, getZone());
 693                         min = d.getMonth() - 1;
 694                         int n = getRolledValue(internalGet(field), amount, min, max);
 695                         if (n == min) {
 696                             // To avoid underflow, use an equivalent year.
 697                             jd.addYear(+400);
 698                             jd.setMonth(n + 1);
 699                             if (jd.getDayOfMonth() < d.getDayOfMonth()) {
 700                                 jd.setDayOfMonth(d.getDayOfMonth());
 701                                 jcal.normalize(jd);
 702                             }
 703                             if (jd.getDayOfMonth() == d.getDayOfMonth()
 704                                 && jd.getTimeOfDay() < d.getTimeOfDay()) {
 705                                 jd.setMonth(n + 1);
 706                                 jd.setDayOfMonth(d.getDayOfMonth() + 1);
 707                                 jcal.normalize(jd);
 708                                 // Month may have changed by the normalization.
 709                                 n = jd.getMonth() - 1;
 710                             }
 711                             set(DAY_OF_MONTH, jd.getDayOfMonth());
 712                         }
 713                         set(MONTH, n);
 714                     } else {
 715                         int mon = (internalGet(MONTH) + amount) % 12;
 716                         if (mon < 0) {
 717                             mon += 12;
 718                         }
 719                         set(MONTH, mon);
 720 
 721                         // Keep the day of month in the range.  We
 722                         // don't want to spill over into the next
 723                         // month; e.g., we don't want jan31 + 1 mo ->
 724                         // feb31 -> mar3.
 725                         int monthLen = monthLength(mon);
 726                         if (internalGet(DAY_OF_MONTH) > monthLen) {
 727                             set(DAY_OF_MONTH, monthLen);
 728                         }
 729                     }
 730                 } else {
 731                     int eraIndex = getEraIndex(jdate);
 732                     CalendarDate transition = null;
 733                     if (jdate.getYear() == 1) {
 734                         transition = eras[eraIndex].getSinceDate();
 735                         min = transition.getMonth() - 1;
 736                     } else {
 737                         if (eraIndex < eras.length - 1) {
 738                             transition = eras[eraIndex + 1].getSinceDate();
 739                             if (transition.getYear() == jdate.getNormalizedYear()) {
 740                                 max = transition.getMonth() - 1;
 741                                 if (transition.getDayOfMonth() == 1) {
 742                                     max--;
 743                                 }
 744                             }
 745                         }
 746                     }
 747 
 748                     if (min == max) {
 749                         // The year has only one month. No need to
 750                         // process further. (Showa Gan-nen (year 1)
 751                         // and the last year have only one month.)
 752                         return;
 753                     }
 754                     int n = getRolledValue(internalGet(field), amount, min, max);
 755                     set(MONTH, n);
 756                     if (n == min) {
 757                         if (!(transition.getMonth() == BaseCalendar.JANUARY
 758                               && transition.getDayOfMonth() == 1)) {
 759                             if (jdate.getDayOfMonth() < transition.getDayOfMonth()) {
 760                                 set(DAY_OF_MONTH, transition.getDayOfMonth());
 761                             }
 762                         }
 763                     } else if (n == max && (transition.getMonth() - 1 == n)) {
 764                         int dom = transition.getDayOfMonth();
 765                         if (jdate.getDayOfMonth() >= dom) {
 766                             set(DAY_OF_MONTH, dom - 1);
 767                         }
 768                     }
 769                 }
 770                 return;
 771             }
 772 
 773         case WEEK_OF_YEAR:
 774             {
 775                 int y = jdate.getNormalizedYear();
 776                 max = getActualMaximum(WEEK_OF_YEAR);
 777                 set(DAY_OF_WEEK, internalGet(DAY_OF_WEEK)); // update stamp[field]
 778                 int woy = internalGet(WEEK_OF_YEAR);
 779                 int value = woy + amount;
 780                 if (!isTransitionYear(jdate.getNormalizedYear())) {
 781                     int year = jdate.getYear();
 782                     if (year == getMaximum(YEAR)) {
 783                         max = getActualMaximum(WEEK_OF_YEAR);
 784                     } else if (year == getMinimum(YEAR)) {
 785                         min = getActualMinimum(WEEK_OF_YEAR);
 786                         max = getActualMaximum(WEEK_OF_YEAR);
 787                         if (value > min && value < max) {
 788                             set(WEEK_OF_YEAR, value);
 789                             return;
 790                         }
 791 
 792                     }
 793                     // If the new value is in between min and max
 794                     // (exclusive), then we can use the value.
 795                     if (value > min && value < max) {
 796                         set(WEEK_OF_YEAR, value);
 797                         return;
 798                     }
 799                     long fd = cachedFixedDate;
 800                     // Make sure that the min week has the current DAY_OF_WEEK
 801                     long day1 = fd - (7 * (woy - min));
 802                     if (year != getMinimum(YEAR)) {
 803                         if (gcal.getYearFromFixedDate(day1) != y) {
 804                             min++;
 805                         }
 806                     } else {
 807                         CalendarDate d = jcal.getCalendarDate(Long.MIN_VALUE, getZone());
 808                         if (day1 < jcal.getFixedDate(d)) {
 809                             min++;
 810                         }
 811                     }
 812 
 813                     // Make sure the same thing for the max week
 814                     fd += 7 * (max - internalGet(WEEK_OF_YEAR));
 815                     if (gcal.getYearFromFixedDate(fd) != y) {
 816                         max--;
 817                     }
 818                     break;
 819                 }
 820 
 821                 // Handle transition here.
 822                 long fd = cachedFixedDate;
 823                 long day1 = fd - (7 * (woy - min));
 824                 // Make sure that the min week has the current DAY_OF_WEEK
 825                 LocalGregorianCalendar.Date d = getCalendarDate(day1);
 826                 if (!(d.getEra() == jdate.getEra() && d.getYear() == jdate.getYear())) {
 827                     min++;
 828                 }
 829 
 830                 // Make sure the same thing for the max week
 831                 fd += 7 * (max - woy);
 832                 jcal.getCalendarDateFromFixedDate(d, fd);
 833                 if (!(d.getEra() == jdate.getEra() && d.getYear() == jdate.getYear())) {
 834                     max--;
 835                 }
 836                 // value: the new WEEK_OF_YEAR which must be converted
 837                 // to month and day of month.
 838                 value = getRolledValue(woy, amount, min, max) - 1;
 839                 d = getCalendarDate(day1 + value * 7);
 840                 set(MONTH, d.getMonth() - 1);
 841                 set(DAY_OF_MONTH, d.getDayOfMonth());
 842                 return;
 843             }
 844 
 845         case WEEK_OF_MONTH:
 846             {
 847                 boolean isTransitionYear = isTransitionYear(jdate.getNormalizedYear());
 848                 // dow: relative day of week from the first day of week
 849                 int dow = internalGet(DAY_OF_WEEK) - getFirstDayOfWeek();
 850                 if (dow < 0) {
 851                     dow += 7;
 852                 }
 853 
 854                 long fd = cachedFixedDate;
 855                 long month1;     // fixed date of the first day (usually 1) of the month
 856                 int monthLength; // actual month length
 857                 if (isTransitionYear) {
 858                     month1 = getFixedDateMonth1(jdate, fd);
 859                     monthLength = actualMonthLength();
 860                 } else {
 861                     month1 = fd - internalGet(DAY_OF_MONTH) + 1;
 862                     monthLength = jcal.getMonthLength(jdate);
 863                 }
 864 
 865                 // the first day of week of the month.
 866                 long monthDay1st = LocalGregorianCalendar.getDayOfWeekDateOnOrBefore(month1 + 6,
 867                                                                                      getFirstDayOfWeek());
 868                 // if the week has enough days to form a week, the
 869                 // week starts from the previous month.
 870                 if ((int)(monthDay1st - month1) >= getMinimalDaysInFirstWeek()) {
 871                     monthDay1st -= 7;
 872                 }
 873                 max = getActualMaximum(field);
 874 
 875                 // value: the new WEEK_OF_MONTH value
 876                 int value = getRolledValue(internalGet(field), amount, 1, max) - 1;
 877 
 878                 // nfd: fixed date of the rolled date
 879                 long nfd = monthDay1st + value * 7 + dow;
 880 
 881                 // Unlike WEEK_OF_YEAR, we need to change day of week if the
 882                 // nfd is out of the month.
 883                 if (nfd < month1) {
 884                     nfd = month1;
 885                 } else if (nfd >= (month1 + monthLength)) {
 886                     nfd = month1 + monthLength - 1;
 887                 }
 888                 set(DAY_OF_MONTH, (int)(nfd - month1) + 1);
 889                 return;
 890             }
 891 
 892         case DAY_OF_MONTH:
 893             {
 894                 if (!isTransitionYear(jdate.getNormalizedYear())) {
 895                     max = jcal.getMonthLength(jdate);
 896                     break;
 897                 }
 898 
 899                 // TODO: Need to change the spec to be usable DAY_OF_MONTH rolling...
 900 
 901                 // Transition handling. We can't change year and era
 902                 // values here due to the Calendar roll spec!
 903                 long month1 = getFixedDateMonth1(jdate, cachedFixedDate);
 904 
 905                 // It may not be a regular month. Convert the date and range to
 906                 // the relative values, perform the roll, and
 907                 // convert the result back to the rolled date.
 908                 int value = getRolledValue((int)(cachedFixedDate - month1), amount,
 909                                            0, actualMonthLength() - 1);
 910                 LocalGregorianCalendar.Date d = getCalendarDate(month1 + value);
 911                 assert getEraIndex(d) == internalGetEra()
 912                     && d.getYear() == internalGet(YEAR) && d.getMonth()-1 == internalGet(MONTH);
 913                 set(DAY_OF_MONTH, d.getDayOfMonth());
 914                 return;
 915             }
 916 
 917         case DAY_OF_YEAR:
 918             {
 919                 max = getActualMaximum(field);
 920                 if (!isTransitionYear(jdate.getNormalizedYear())) {
 921                     break;
 922                 }
 923 
 924                 // Handle transition. We can't change year and era values
 925                 // here due to the Calendar roll spec.
 926                 int value = getRolledValue(internalGet(DAY_OF_YEAR), amount, min, max);
 927                 long jan0 = cachedFixedDate - internalGet(DAY_OF_YEAR);
 928                 LocalGregorianCalendar.Date d = getCalendarDate(jan0 + value);
 929                 assert getEraIndex(d) == internalGetEra() && d.getYear() == internalGet(YEAR);
 930                 set(MONTH, d.getMonth() - 1);
 931                 set(DAY_OF_MONTH, d.getDayOfMonth());
 932                 return;
 933             }
 934 
 935         case DAY_OF_WEEK:
 936             {
 937                 int normalizedYear = jdate.getNormalizedYear();
 938                 if (!isTransitionYear(normalizedYear) && !isTransitionYear(normalizedYear - 1)) {
 939                     // If the week of year is in the same year, we can
 940                     // just change DAY_OF_WEEK.
 941                     int weekOfYear = internalGet(WEEK_OF_YEAR);
 942                     if (weekOfYear > 1 && weekOfYear < 52) {
 943                         set(WEEK_OF_YEAR, internalGet(WEEK_OF_YEAR));
 944                         max = SATURDAY;
 945                         break;
 946                     }
 947                 }
 948 
 949                 // We need to handle it in a different way around year
 950                 // boundaries and in the transition year. Note that
 951                 // changing era and year values violates the roll
 952                 // rule: not changing larger calendar fields...
 953                 amount %= 7;
 954                 if (amount == 0) {
 955                     return;
 956                 }
 957                 long fd = cachedFixedDate;
 958                 long dowFirst = LocalGregorianCalendar.getDayOfWeekDateOnOrBefore(fd, getFirstDayOfWeek());
 959                 fd += amount;
 960                 if (fd < dowFirst) {
 961                     fd += 7;
 962                 } else if (fd >= dowFirst + 7) {
 963                     fd -= 7;
 964                 }
 965                 LocalGregorianCalendar.Date d = getCalendarDate(fd);
 966                 set(ERA, getEraIndex(d));
 967                 set(d.getYear(), d.getMonth() - 1, d.getDayOfMonth());
 968                 return;
 969             }
 970 
 971         case DAY_OF_WEEK_IN_MONTH:
 972             {
 973                 min = 1; // after having normalized, min should be 1.
 974                 if (!isTransitionYear(jdate.getNormalizedYear())) {
 975                     int dom = internalGet(DAY_OF_MONTH);
 976                     int monthLength = jcal.getMonthLength(jdate);
 977                     int lastDays = monthLength % 7;
 978                     max = monthLength / 7;
 979                     int x = (dom - 1) % 7;
 980                     if (x < lastDays) {
 981                         max++;
 982                     }
 983                     set(DAY_OF_WEEK, internalGet(DAY_OF_WEEK));
 984                     break;
 985                 }
 986 
 987                 // Transition year handling.
 988                 long fd = cachedFixedDate;
 989                 long month1 = getFixedDateMonth1(jdate, fd);
 990                 int monthLength = actualMonthLength();
 991                 int lastDays = monthLength % 7;
 992                 max = monthLength / 7;
 993                 int x = (int)(fd - month1) % 7;
 994                 if (x < lastDays) {
 995                     max++;
 996                 }
 997                 int value = getRolledValue(internalGet(field), amount, min, max) - 1;
 998                 fd = month1 + value * 7 + x;
 999                 LocalGregorianCalendar.Date d = getCalendarDate(fd);
1000                 set(DAY_OF_MONTH, d.getDayOfMonth());
1001                 return;
1002             }
1003         }
1004 
1005         set(field, getRolledValue(internalGet(field), amount, min, max));
1006     }
1007 
1008     @Override
1009     public String getDisplayName(int field, int style, Locale locale) {
1010         if (!checkDisplayNameParams(field, style, SHORT, NARROW_FORMAT, locale,
1011                                     ERA_MASK|YEAR_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) {
1012             return null;
1013         }
1014 
1015         int fieldValue = get(field);
1016 
1017         // "GanNen" is supported only in the LONG style.
1018         if (field == YEAR
1019             && (getBaseStyle(style) != LONG || fieldValue != 1 || get(ERA) == 0)) {
1020             return null;
1021         }
1022 
1023         String name = CalendarDataUtility.retrieveFieldValueName(getCalendarType(), field,
1024                                                                  fieldValue, style, locale);
1025         // If the ERA value is null, then
1026         // try to get its name or abbreviation from the Era instance.
1027         if (name == null && field == ERA && fieldValue < eras.length) {
1028             Era era = eras[fieldValue];
1029             name = (style == SHORT) ? era.getAbbreviation() : era.getName();
1030         }
1031         return name;
1032     }
1033 
1034     @Override
1035     public Map<String,Integer> getDisplayNames(int field, int style, Locale locale) {
1036         if (!checkDisplayNameParams(field, style, ALL_STYLES, NARROW_FORMAT, locale,
1037                                     ERA_MASK|YEAR_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) {
1038             return null;
1039         }
1040         Map<String, Integer> names;
1041         names = CalendarDataUtility.retrieveFieldValueNames(getCalendarType(), field, style, locale);
1042         // If strings[] has fewer than eras[], get more names from eras[].
1043         if (names != null) {
1044             if (field == ERA) {
1045                 int size = names.size();
1046                 if (style == ALL_STYLES) {
1047                     Set<Integer> values = new HashSet<>();
1048                     // count unique era values
1049                     for (String key : names.keySet()) {
1050                         values.add(names.get(key));
1051                     }
1052                     size = values.size();
1053                 }
1054                 if (size < eras.length) {
1055                     int baseStyle = getBaseStyle(style);
1056                     for (int i = 0; i < eras.length; i++) {
1057                         if (!names.values().contains(i)) {
1058                             Era era = eras[i];
1059                             if (baseStyle == ALL_STYLES || baseStyle == SHORT
1060                                     || baseStyle == NARROW_FORMAT) {
1061                                 names.put(era.getAbbreviation(), i);
1062                             }
1063                             if (baseStyle == ALL_STYLES || baseStyle == LONG) {
1064                                 names.put(era.getName(), i);
1065                             }
1066                         }
1067                     }
1068                 }
1069             }
1070         }
1071         return names;
1072     }
1073 
1074     /**
1075      * Returns the minimum value for the given calendar field of this
1076      * {@code Calendar} instance. The minimum value is
1077      * defined as the smallest value returned by the
1078      * {@link Calendar#get(int) get} method for any possible time value,
1079      * taking into consideration the current values of the
1080      * {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek},
1081      * {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek},
1082      * and {@link Calendar#getTimeZone() getTimeZone} methods.
1083      *
1084      * @param field the calendar field.
1085      * @return the minimum value for the given calendar field.
1086      * @see #getMaximum(int)
1087      * @see #getGreatestMinimum(int)
1088      * @see #getLeastMaximum(int)
1089      * @see #getActualMinimum(int)
1090      * @see #getActualMaximum(int)
1091      */
1092     public int getMinimum(int field) {
1093         return MIN_VALUES[field];
1094     }
1095 
1096     /**
1097      * Returns the maximum value for the given calendar field of this
1098      * {@code GregorianCalendar} instance. The maximum value is
1099      * defined as the largest value returned by the
1100      * {@link Calendar#get(int) get} method for any possible time value,
1101      * taking into consideration the current values of the
1102      * {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek},
1103      * {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek},
1104      * and {@link Calendar#getTimeZone() getTimeZone} methods.
1105      *
1106      * @param field the calendar field.
1107      * @return the maximum value for the given calendar field.
1108      * @see #getMinimum(int)
1109      * @see #getGreatestMinimum(int)
1110      * @see #getLeastMaximum(int)
1111      * @see #getActualMinimum(int)
1112      * @see #getActualMaximum(int)
1113      */
1114     public int getMaximum(int field) {
1115         switch (field) {
1116         case YEAR:
1117             {
1118                 // The value should depend on the time zone of this calendar.
1119                 LocalGregorianCalendar.Date d = jcal.getCalendarDate(Long.MAX_VALUE,
1120                                                                      getZone());
1121                 return Math.max(LEAST_MAX_VALUES[YEAR], d.getYear());
1122             }
1123         }
1124         return MAX_VALUES[field];
1125     }
1126 
1127     /**
1128      * Returns the highest minimum value for the given calendar field
1129      * of this {@code GregorianCalendar} instance. The highest
1130      * minimum value is defined as the largest value returned by
1131      * {@link #getActualMinimum(int)} for any possible time value,
1132      * taking into consideration the current values of the
1133      * {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek},
1134      * {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek},
1135      * and {@link Calendar#getTimeZone() getTimeZone} methods.
1136      *
1137      * @param field the calendar field.
1138      * @return the highest minimum value for the given calendar field.
1139      * @see #getMinimum(int)
1140      * @see #getMaximum(int)
1141      * @see #getLeastMaximum(int)
1142      * @see #getActualMinimum(int)
1143      * @see #getActualMaximum(int)
1144      */
1145     public int getGreatestMinimum(int field) {
1146         return field == YEAR ? 1 : MIN_VALUES[field];
1147     }
1148 
1149     /**
1150      * Returns the lowest maximum value for the given calendar field
1151      * of this {@code GregorianCalendar} instance. The lowest
1152      * maximum value is defined as the smallest value returned by
1153      * {@link #getActualMaximum(int)} for any possible time value,
1154      * taking into consideration the current values of the
1155      * {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek},
1156      * {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek},
1157      * and {@link Calendar#getTimeZone() getTimeZone} methods.
1158      *
1159      * @param field the calendar field
1160      * @return the lowest maximum value for the given calendar field.
1161      * @see #getMinimum(int)
1162      * @see #getMaximum(int)
1163      * @see #getGreatestMinimum(int)
1164      * @see #getActualMinimum(int)
1165      * @see #getActualMaximum(int)
1166      */
1167     public int getLeastMaximum(int field) {
1168         switch (field) {
1169         case YEAR:
1170             {
1171                 return Math.min(LEAST_MAX_VALUES[YEAR], getMaximum(YEAR));
1172             }
1173         }
1174         return LEAST_MAX_VALUES[field];
1175     }
1176 
1177     /**
1178      * Returns the minimum value that this calendar field could have,
1179      * taking into consideration the given time value and the current
1180      * values of the
1181      * {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek},
1182      * {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek},
1183      * and {@link Calendar#getTimeZone() getTimeZone} methods.
1184      *
1185      * @param field the calendar field
1186      * @return the minimum of the given field for the time value of
1187      * this {@code JapaneseImperialCalendar}
1188      * @see #getMinimum(int)
1189      * @see #getMaximum(int)
1190      * @see #getGreatestMinimum(int)
1191      * @see #getLeastMaximum(int)
1192      * @see #getActualMaximum(int)
1193      */
1194     public int getActualMinimum(int field) {
1195         if (!isFieldSet(YEAR_MASK|MONTH_MASK|WEEK_OF_YEAR_MASK, field)) {
1196             return getMinimum(field);
1197         }
1198 
1199         int value = 0;
1200         JapaneseImperialCalendar jc = getNormalizedCalendar();
1201         // Get a local date which includes time of day and time zone,
1202         // which are missing in jc.jdate.
1203         LocalGregorianCalendar.Date jd = jcal.getCalendarDate(jc.getTimeInMillis(),
1204                                                               getZone());
1205         int eraIndex = getEraIndex(jd);
1206         switch (field) {
1207         case YEAR:
1208             {
1209                 if (eraIndex > BEFORE_MEIJI) {
1210                     value = 1;
1211                     long since = eras[eraIndex].getSince(getZone());
1212                     CalendarDate d = jcal.getCalendarDate(since, getZone());
1213                     // Use the same year in jd to take care of leap
1214                     // years. i.e., both jd and d must agree on leap
1215                     // or common years.
1216                     jd.setYear(d.getYear());
1217                     jcal.normalize(jd);
1218                     assert jd.isLeapYear() == d.isLeapYear();
1219                     if (getYearOffsetInMillis(jd) < getYearOffsetInMillis(d)) {
1220                         value++;
1221                     }
1222                 } else {
1223                     value = getMinimum(field);
1224                     CalendarDate d = jcal.getCalendarDate(Long.MIN_VALUE, getZone());
1225                     // Use an equvalent year of d.getYear() if
1226                     // possible. Otherwise, ignore the leap year and
1227                     // common year difference.
1228                     int y = d.getYear();
1229                     if (y > 400) {
1230                         y -= 400;
1231                     }
1232                     jd.setYear(y);
1233                     jcal.normalize(jd);
1234                     if (getYearOffsetInMillis(jd) < getYearOffsetInMillis(d)) {
1235                         value++;
1236                     }
1237                 }
1238             }
1239             break;
1240 
1241         case MONTH:
1242             {
1243                 // In Before Meiji and Meiji, January is the first month.
1244                 if (eraIndex > MEIJI && jd.getYear() == 1) {
1245                     long since = eras[eraIndex].getSince(getZone());
1246                     CalendarDate d = jcal.getCalendarDate(since, getZone());
1247                     value = d.getMonth() - 1;
1248                     if (jd.getDayOfMonth() < d.getDayOfMonth()) {
1249                         value++;
1250                     }
1251                 }
1252             }
1253             break;
1254 
1255         case WEEK_OF_YEAR:
1256             {
1257                 value = 1;
1258                 CalendarDate d = jcal.getCalendarDate(Long.MIN_VALUE, getZone());
1259                 // shift 400 years to avoid underflow
1260                 d.addYear(+400);
1261                 jcal.normalize(d);
1262                 jd.setEra(d.getEra());
1263                 jd.setYear(d.getYear());
1264                 jcal.normalize(jd);
1265 
1266                 long jan1 = jcal.getFixedDate(d);
1267                 long fd = jcal.getFixedDate(jd);
1268                 int woy = getWeekNumber(jan1, fd);
1269                 long day1 = fd - (7 * (woy - 1));
1270                 if ((day1 < jan1) ||
1271                     (day1 == jan1 &&
1272                      jd.getTimeOfDay() < d.getTimeOfDay())) {
1273                     value++;
1274                 }
1275             }
1276             break;
1277         }
1278         return value;
1279     }
1280 
1281     /**
1282      * Returns the maximum value that this calendar field could have,
1283      * taking into consideration the given time value and the current
1284      * values of the
1285      * {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek},
1286      * {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek},
1287      * and
1288      * {@link Calendar#getTimeZone() getTimeZone} methods.
1289      * For example, if the date of this instance is Heisei 16February 1,
1290      * the actual maximum value of the {@code DAY_OF_MONTH} field
1291      * is 29 because Heisei 16 is a leap year, and if the date of this
1292      * instance is Heisei 17 February 1, it's 28.
1293      *
1294      * @param field the calendar field
1295      * @return the maximum of the given field for the time value of
1296      * this {@code JapaneseImperialCalendar}
1297      * @see #getMinimum(int)
1298      * @see #getMaximum(int)
1299      * @see #getGreatestMinimum(int)
1300      * @see #getLeastMaximum(int)
1301      * @see #getActualMinimum(int)
1302      */
1303     public int getActualMaximum(int field) {
1304         final int fieldsForFixedMax = ERA_MASK|DAY_OF_WEEK_MASK|HOUR_MASK|AM_PM_MASK|
1305             HOUR_OF_DAY_MASK|MINUTE_MASK|SECOND_MASK|MILLISECOND_MASK|
1306             ZONE_OFFSET_MASK|DST_OFFSET_MASK;
1307         if ((fieldsForFixedMax & (1<<field)) != 0) {
1308             return getMaximum(field);
1309         }
1310 
1311         JapaneseImperialCalendar jc = getNormalizedCalendar();
1312         LocalGregorianCalendar.Date date = jc.jdate;
1313         int normalizedYear = date.getNormalizedYear();
1314 
1315         int value = -1;
1316         switch (field) {
1317         case MONTH:
1318             {
1319                 value = DECEMBER;
1320                 if (isTransitionYear(date.getNormalizedYear())) {
1321                     // TODO: there may be multiple transitions in a year.
1322                     int eraIndex = getEraIndex(date);
1323                     if (date.getYear() != 1) {
1324                         eraIndex++;
1325                         assert eraIndex < eras.length;
1326                     }
1327                     long transition = sinceFixedDates[eraIndex];
1328                     long fd = jc.cachedFixedDate;
1329                     if (fd < transition) {
1330                         LocalGregorianCalendar.Date ldate
1331                             = (LocalGregorianCalendar.Date) date.clone();
1332                         jcal.getCalendarDateFromFixedDate(ldate, transition - 1);
1333                         value = ldate.getMonth() - 1;
1334                     }
1335                 } else {
1336                     LocalGregorianCalendar.Date d = jcal.getCalendarDate(Long.MAX_VALUE,
1337                                                                          getZone());
1338                     if (date.getEra() == d.getEra() && date.getYear() == d.getYear()) {
1339                         value = d.getMonth() - 1;
1340                     }
1341                 }
1342             }
1343             break;
1344 
1345         case DAY_OF_MONTH:
1346             value = jcal.getMonthLength(date);
1347             break;
1348 
1349         case DAY_OF_YEAR:
1350             {
1351                 if (isTransitionYear(date.getNormalizedYear())) {
1352                     // Handle transition year.
1353                     // TODO: there may be multiple transitions in a year.
1354                     int eraIndex = getEraIndex(date);
1355                     if (date.getYear() != 1) {
1356                         eraIndex++;
1357                         assert eraIndex < eras.length;
1358                     }
1359                     long transition = sinceFixedDates[eraIndex];
1360                     long fd = jc.cachedFixedDate;
1361                     CalendarDate d = gcal.newCalendarDate(TimeZone.NO_TIMEZONE);
1362                     d.setDate(date.getNormalizedYear(), BaseCalendar.JANUARY, 1);
1363                     if (fd < transition) {
1364                         value = (int)(transition - gcal.getFixedDate(d));
1365                     } else {
1366                         d.addYear(+1);
1367                         value = (int)(gcal.getFixedDate(d) - transition);
1368                     }
1369                 } else {
1370                     LocalGregorianCalendar.Date d = jcal.getCalendarDate(Long.MAX_VALUE,
1371                                                                          getZone());
1372                     if (date.getEra() == d.getEra() && date.getYear() == d.getYear()) {
1373                         long fd = jcal.getFixedDate(d);
1374                         long jan1 = getFixedDateJan1(d, fd);
1375                         value = (int)(fd - jan1) + 1;
1376                     } else if (date.getYear() == getMinimum(YEAR)) {
1377                         CalendarDate d1 = jcal.getCalendarDate(Long.MIN_VALUE, getZone());
1378                         long fd1 = jcal.getFixedDate(d1);
1379                         d1.addYear(1);
1380                         d1.setMonth(BaseCalendar.JANUARY).setDayOfMonth(1);
1381                         jcal.normalize(d1);
1382                         long fd2 = jcal.getFixedDate(d1);
1383                         value = (int)(fd2 - fd1);
1384                     } else {
1385                         value = jcal.getYearLength(date);
1386                     }
1387                 }
1388             }
1389             break;
1390 
1391         case WEEK_OF_YEAR:
1392             {
1393                 if (!isTransitionYear(date.getNormalizedYear())) {
1394                     LocalGregorianCalendar.Date jd = jcal.getCalendarDate(Long.MAX_VALUE,
1395                                                                           getZone());
1396                     if (date.getEra() == jd.getEra() && date.getYear() == jd.getYear()) {
1397                         long fd = jcal.getFixedDate(jd);
1398                         long jan1 = getFixedDateJan1(jd, fd);
1399                         value = getWeekNumber(jan1, fd);
1400                     } else if (date.getEra() == null && date.getYear() == getMinimum(YEAR)) {
1401                         CalendarDate d = jcal.getCalendarDate(Long.MIN_VALUE, getZone());
1402                         // shift 400 years to avoid underflow
1403                         d.addYear(+400);
1404                         jcal.normalize(d);
1405                         jd.setEra(d.getEra());
1406                         jd.setDate(d.getYear() + 1, BaseCalendar.JANUARY, 1);
1407                         jcal.normalize(jd);
1408                         long jan1 = jcal.getFixedDate(d);
1409                         long nextJan1 = jcal.getFixedDate(jd);
1410                         long nextJan1st = LocalGregorianCalendar.getDayOfWeekDateOnOrBefore(nextJan1 + 6,
1411                                                                                             getFirstDayOfWeek());
1412                         int ndays = (int)(nextJan1st - nextJan1);
1413                         if (ndays >= getMinimalDaysInFirstWeek()) {
1414                             nextJan1st -= 7;
1415                         }
1416                         value = getWeekNumber(jan1, nextJan1st);
1417                     } else {
1418                         // Get the day of week of January 1 of the year
1419                         CalendarDate d = gcal.newCalendarDate(TimeZone.NO_TIMEZONE);
1420                         d.setDate(date.getNormalizedYear(), BaseCalendar.JANUARY, 1);
1421                         int dayOfWeek = gcal.getDayOfWeek(d);
1422                         // Normalize the day of week with the firstDayOfWeek value
1423                         dayOfWeek -= getFirstDayOfWeek();
1424                         if (dayOfWeek < 0) {
1425                             dayOfWeek += 7;
1426                         }
1427                         value = 52;
1428                         int magic = dayOfWeek + getMinimalDaysInFirstWeek() - 1;
1429                         if ((magic == 6) ||
1430                             (date.isLeapYear() && (magic == 5 || magic == 12))) {
1431                             value++;
1432                         }
1433                     }
1434                     break;
1435                 }
1436 
1437                 if (jc == this) {
1438                     jc = (JapaneseImperialCalendar) jc.clone();
1439                 }
1440                 int max = getActualMaximum(DAY_OF_YEAR);
1441                 jc.set(DAY_OF_YEAR, max);
1442                 value = jc.get(WEEK_OF_YEAR);
1443                 if (value == 1 && max > 7) {
1444                     jc.add(WEEK_OF_YEAR, -1);
1445                     value = jc.get(WEEK_OF_YEAR);
1446                 }
1447             }
1448             break;
1449 
1450         case WEEK_OF_MONTH:
1451             {
1452                 LocalGregorianCalendar.Date jd = jcal.getCalendarDate(Long.MAX_VALUE,
1453                                                                       getZone());
1454                 if (!(date.getEra() == jd.getEra() && date.getYear() == jd.getYear())) {
1455                     CalendarDate d = gcal.newCalendarDate(TimeZone.NO_TIMEZONE);
1456                     d.setDate(date.getNormalizedYear(), date.getMonth(), 1);
1457                     int dayOfWeek = gcal.getDayOfWeek(d);
1458                     int monthLength = gcal.getMonthLength(d);
1459                     dayOfWeek -= getFirstDayOfWeek();
1460                     if (dayOfWeek < 0) {
1461                         dayOfWeek += 7;
1462                     }
1463                     int nDaysFirstWeek = 7 - dayOfWeek; // # of days in the first week
1464                     value = 3;
1465                     if (nDaysFirstWeek >= getMinimalDaysInFirstWeek()) {
1466                         value++;
1467                     }
1468                     monthLength -= nDaysFirstWeek + 7 * 3;
1469                     if (monthLength > 0) {
1470                         value++;
1471                         if (monthLength > 7) {
1472                             value++;
1473                         }
1474                     }
1475                 } else {
1476                     long fd = jcal.getFixedDate(jd);
1477                     long month1 = fd - jd.getDayOfMonth() + 1;
1478                     value = getWeekNumber(month1, fd);
1479                 }
1480             }
1481             break;
1482 
1483         case DAY_OF_WEEK_IN_MONTH:
1484             {
1485                 int ndays, dow1;
1486                 int dow = date.getDayOfWeek();
1487                 BaseCalendar.Date d = (BaseCalendar.Date) date.clone();
1488                 ndays = jcal.getMonthLength(d);
1489                 d.setDayOfMonth(1);
1490                 jcal.normalize(d);
1491                 dow1 = d.getDayOfWeek();
1492                 int x = dow - dow1;
1493                 if (x < 0) {
1494                     x += 7;
1495                 }
1496                 ndays -= x;
1497                 value = (ndays + 6) / 7;
1498             }
1499             break;
1500 
1501         case YEAR:
1502             {
1503                 CalendarDate jd = jcal.getCalendarDate(jc.getTimeInMillis(), getZone());
1504                 CalendarDate d;
1505                 int eraIndex = getEraIndex(date);
1506                 if (eraIndex == eras.length - 1) {
1507                     d = jcal.getCalendarDate(Long.MAX_VALUE, getZone());
1508                     value = d.getYear();
1509                     // Use an equivalent year for the
1510                     // getYearOffsetInMillis call to avoid overflow.
1511                     if (value > 400) {
1512                         jd.setYear(value - 400);
1513                     }
1514                 } else {
1515                     d = jcal.getCalendarDate(eras[eraIndex + 1].getSince(getZone()) - 1,
1516                                              getZone());
1517                     value = d.getYear();
1518                     // Use the same year as d.getYear() to be
1519                     // consistent with leap and common years.
1520                     jd.setYear(value);
1521                 }
1522                 jcal.normalize(jd);
1523                 if (getYearOffsetInMillis(jd) > getYearOffsetInMillis(d)) {
1524                     value--;
1525                 }
1526             }
1527             break;
1528 
1529         default:
1530             throw new ArrayIndexOutOfBoundsException(field);
1531         }
1532         return value;
1533     }
1534 
1535     /**
1536      * Returns the millisecond offset from the beginning of the
1537      * year. In the year for Long.MIN_VALUE, it's a pseudo value
1538      * beyond the limit. The given CalendarDate object must have been
1539      * normalized before calling this method.
1540      */
1541     private long getYearOffsetInMillis(CalendarDate date) {
1542         long t = (jcal.getDayOfYear(date) - 1) * ONE_DAY;
1543         return t + date.getTimeOfDay() - date.getZoneOffset();
1544     }
1545 
1546     public Object clone() {
1547         JapaneseImperialCalendar other = (JapaneseImperialCalendar) super.clone();
1548 
1549         other.jdate = (LocalGregorianCalendar.Date) jdate.clone();
1550         other.originalFields = null;
1551         other.zoneOffsets = null;
1552         return other;
1553     }
1554 
1555     public TimeZone getTimeZone() {
1556         TimeZone zone = super.getTimeZone();
1557         // To share the zone by the CalendarDate
1558         jdate.setZone(zone);
1559         return zone;
1560     }
1561 
1562     public void setTimeZone(TimeZone zone) {
1563         super.setTimeZone(zone);
1564         // To share the zone by the CalendarDate
1565         jdate.setZone(zone);
1566     }
1567 
1568     /**
1569      * The fixed date corresponding to jdate. If the value is
1570      * Long.MIN_VALUE, the fixed date value is unknown.
1571      */
1572     private transient long cachedFixedDate = Long.MIN_VALUE;
1573 
1574     /**
1575      * Converts the time value (millisecond offset from the <a
1576      * href="Calendar.html#Epoch">Epoch</a>) to calendar field values.
1577      * The time is <em>not</em>
1578      * recomputed first; to recompute the time, then the fields, call the
1579      * {@code complete} method.
1580      *
1581      * @see Calendar#complete
1582      */
1583     protected void computeFields() {
1584         int mask = 0;
1585         if (isPartiallyNormalized()) {
1586             // Determine which calendar fields need to be computed.
1587             mask = getSetStateFields();
1588             int fieldMask = ~mask & ALL_FIELDS;
1589             if (fieldMask != 0 || cachedFixedDate == Long.MIN_VALUE) {
1590                 mask |= computeFields(fieldMask,
1591                                       mask & (ZONE_OFFSET_MASK|DST_OFFSET_MASK));
1592                 assert mask == ALL_FIELDS;
1593             }
1594         } else {
1595             // Specify all fields
1596             mask = ALL_FIELDS;
1597             computeFields(mask, 0);
1598         }
1599         // After computing all the fields, set the field state to `COMPUTED'.
1600         setFieldsComputed(mask);
1601     }
1602 
1603     /**
1604      * This computeFields implements the conversion from UTC
1605      * (millisecond offset from the Epoch) to calendar
1606      * field values. fieldMask specifies which fields to change the
1607      * setting state to COMPUTED, although all fields are set to
1608      * the correct values. This is required to fix 4685354.
1609      *
1610      * @param fieldMask a bit mask to specify which fields to change
1611      * the setting state.
1612      * @param tzMask a bit mask to specify which time zone offset
1613      * fields to be used for time calculations
1614      * @return a new field mask that indicates what field values have
1615      * actually been set.
1616      */
1617     private int computeFields(int fieldMask, int tzMask) {
1618         int zoneOffset = 0;
1619         TimeZone tz = getZone();
1620         if (zoneOffsets == null) {
1621             zoneOffsets = new int[2];
1622         }
1623         if (tzMask != (ZONE_OFFSET_MASK|DST_OFFSET_MASK)) {
1624             if (tz instanceof ZoneInfo) {
1625                 zoneOffset = ((ZoneInfo)tz).getOffsets(time, zoneOffsets);
1626             } else {
1627                 zoneOffset = tz.getOffset(time);
1628                 zoneOffsets[0] = tz.getRawOffset();
1629                 zoneOffsets[1] = zoneOffset - zoneOffsets[0];
1630             }
1631         }
1632         if (tzMask != 0) {
1633             if (isFieldSet(tzMask, ZONE_OFFSET)) {
1634                 zoneOffsets[0] = internalGet(ZONE_OFFSET);
1635             }
1636             if (isFieldSet(tzMask, DST_OFFSET)) {
1637                 zoneOffsets[1] = internalGet(DST_OFFSET);
1638             }
1639             zoneOffset = zoneOffsets[0] + zoneOffsets[1];
1640         }
1641 
1642         // By computing time and zoneOffset separately, we can take
1643         // the wider range of time+zoneOffset than the previous
1644         // implementation.
1645         long fixedDate = zoneOffset / ONE_DAY;
1646         int timeOfDay = zoneOffset % (int)ONE_DAY;
1647         fixedDate += time / ONE_DAY;
1648         timeOfDay += (int) (time % ONE_DAY);
1649         if (timeOfDay >= ONE_DAY) {
1650             timeOfDay -= ONE_DAY;
1651             ++fixedDate;
1652         } else {
1653             while (timeOfDay < 0) {
1654                 timeOfDay += ONE_DAY;
1655                 --fixedDate;
1656             }
1657         }
1658         fixedDate += EPOCH_OFFSET;
1659 
1660         // See if we can use jdate to avoid date calculation.
1661         if (fixedDate != cachedFixedDate || fixedDate < 0) {
1662             jcal.getCalendarDateFromFixedDate(jdate, fixedDate);
1663             cachedFixedDate = fixedDate;
1664         }
1665         int era = getEraIndex(jdate);
1666         int year = jdate.getYear();
1667 
1668         // Always set the ERA and YEAR values.
1669         internalSet(ERA, era);
1670         internalSet(YEAR, year);
1671         int mask = fieldMask | (ERA_MASK|YEAR_MASK);
1672 
1673         int month =  jdate.getMonth() - 1; // 0-based
1674         int dayOfMonth = jdate.getDayOfMonth();
1675 
1676         // Set the basic date fields.
1677         if ((fieldMask & (MONTH_MASK|DAY_OF_MONTH_MASK|DAY_OF_WEEK_MASK))
1678             != 0) {
1679             internalSet(MONTH, month);
1680             internalSet(DAY_OF_MONTH, dayOfMonth);
1681             internalSet(DAY_OF_WEEK, jdate.getDayOfWeek());
1682             mask |= MONTH_MASK|DAY_OF_MONTH_MASK|DAY_OF_WEEK_MASK;
1683         }
1684 
1685         if ((fieldMask & (HOUR_OF_DAY_MASK|AM_PM_MASK|HOUR_MASK
1686                           |MINUTE_MASK|SECOND_MASK|MILLISECOND_MASK)) != 0) {
1687             if (timeOfDay != 0) {
1688                 int hours = timeOfDay / ONE_HOUR;
1689                 internalSet(HOUR_OF_DAY, hours);
1690                 internalSet(AM_PM, hours / 12); // Assume AM == 0
1691                 internalSet(HOUR, hours % 12);
1692                 int r = timeOfDay % ONE_HOUR;
1693                 internalSet(MINUTE, r / ONE_MINUTE);
1694                 r %= ONE_MINUTE;
1695                 internalSet(SECOND, r / ONE_SECOND);
1696                 internalSet(MILLISECOND, r % ONE_SECOND);
1697             } else {
1698                 internalSet(HOUR_OF_DAY, 0);
1699                 internalSet(AM_PM, AM);
1700                 internalSet(HOUR, 0);
1701                 internalSet(MINUTE, 0);
1702                 internalSet(SECOND, 0);
1703                 internalSet(MILLISECOND, 0);
1704             }
1705             mask |= (HOUR_OF_DAY_MASK|AM_PM_MASK|HOUR_MASK
1706                      |MINUTE_MASK|SECOND_MASK|MILLISECOND_MASK);
1707         }
1708 
1709         if ((fieldMask & (ZONE_OFFSET_MASK|DST_OFFSET_MASK)) != 0) {
1710             internalSet(ZONE_OFFSET, zoneOffsets[0]);
1711             internalSet(DST_OFFSET, zoneOffsets[1]);
1712             mask |= (ZONE_OFFSET_MASK|DST_OFFSET_MASK);
1713         }
1714 
1715         if ((fieldMask & (DAY_OF_YEAR_MASK|WEEK_OF_YEAR_MASK
1716                           |WEEK_OF_MONTH_MASK|DAY_OF_WEEK_IN_MONTH_MASK)) != 0) {
1717             int normalizedYear = jdate.getNormalizedYear();
1718             // If it's a year of an era transition, we need to handle
1719             // irregular year boundaries.
1720             boolean transitionYear = isTransitionYear(jdate.getNormalizedYear());
1721             int dayOfYear;
1722             long fixedDateJan1;
1723             if (transitionYear) {
1724                 fixedDateJan1 = getFixedDateJan1(jdate, fixedDate);
1725                 dayOfYear = (int)(fixedDate - fixedDateJan1) + 1;
1726             } else if (normalizedYear == MIN_VALUES[YEAR]) {
1727                 CalendarDate dx = jcal.getCalendarDate(Long.MIN_VALUE, getZone());
1728                 fixedDateJan1 = jcal.getFixedDate(dx);
1729                 dayOfYear = (int)(fixedDate - fixedDateJan1) + 1;
1730             } else {
1731                 dayOfYear = (int) jcal.getDayOfYear(jdate);
1732                 fixedDateJan1 = fixedDate - dayOfYear + 1;
1733             }
1734             long fixedDateMonth1 = transitionYear ?
1735                 getFixedDateMonth1(jdate, fixedDate) : fixedDate - dayOfMonth + 1;
1736 
1737             internalSet(DAY_OF_YEAR, dayOfYear);
1738             internalSet(DAY_OF_WEEK_IN_MONTH, (dayOfMonth - 1) / 7 + 1);
1739 
1740             int weekOfYear = getWeekNumber(fixedDateJan1, fixedDate);
1741 
1742             // The spec is to calculate WEEK_OF_YEAR in the
1743             // ISO8601-style. This creates problems, though.
1744             if (weekOfYear == 0) {
1745                 // If the date belongs to the last week of the
1746                 // previous year, use the week number of "12/31" of
1747                 // the "previous" year. Again, if the previous year is
1748                 // a transition year, we need to take care of it.
1749                 // Usually the previous day of the first day of a year
1750                 // is December 31, which is not always true in the
1751                 // Japanese imperial calendar system.
1752                 long fixedDec31 = fixedDateJan1 - 1;
1753                 long prevJan1;
1754                 LocalGregorianCalendar.Date d = getCalendarDate(fixedDec31);
1755                 if (!(transitionYear || isTransitionYear(d.getNormalizedYear()))) {
1756                     prevJan1 = fixedDateJan1 - 365;
1757                     if (d.isLeapYear()) {
1758                         --prevJan1;
1759                     }
1760                 } else if (transitionYear) {
1761                     if (jdate.getYear() == 1) {
1762                         // As of NewEra (since Meiji) there's no case
1763                         // that there are multiple transitions in a
1764                         // year.  Historically there was such
1765                         // case. There might be such case again in the
1766                         // future.
1767                         if (era > NEWERA) {
1768                             CalendarDate pd = eras[era - 1].getSinceDate();
1769                             if (normalizedYear == pd.getYear()) {
1770                                 d.setMonth(pd.getMonth()).setDayOfMonth(pd.getDayOfMonth());
1771                             }
1772                         } else {
1773                             d.setMonth(LocalGregorianCalendar.JANUARY).setDayOfMonth(1);
1774                         }
1775                         jcal.normalize(d);
1776                         prevJan1 = jcal.getFixedDate(d);
1777                     } else {
1778                         prevJan1 = fixedDateJan1 - 365;
1779                         if (d.isLeapYear()) {
1780                             --prevJan1;
1781                         }
1782                     }
1783                 } else {
1784                     CalendarDate cd = eras[getEraIndex(jdate)].getSinceDate();
1785                     d.setMonth(cd.getMonth()).setDayOfMonth(cd.getDayOfMonth());
1786                     jcal.normalize(d);
1787                     prevJan1 = jcal.getFixedDate(d);
1788                 }
1789                 weekOfYear = getWeekNumber(prevJan1, fixedDec31);
1790             } else {
1791                 if (!transitionYear) {
1792                     // Regular years
1793                     if (weekOfYear >= 52) {
1794                         long nextJan1 = fixedDateJan1 + 365;
1795                         if (jdate.isLeapYear()) {
1796                             nextJan1++;
1797                         }
1798                         long nextJan1st = LocalGregorianCalendar.getDayOfWeekDateOnOrBefore(nextJan1 + 6,
1799                                                                                             getFirstDayOfWeek());
1800                         int ndays = (int)(nextJan1st - nextJan1);
1801                         if (ndays >= getMinimalDaysInFirstWeek() && fixedDate >= (nextJan1st - 7)) {
1802                             // The first days forms a week in which the date is included.
1803                             weekOfYear = 1;
1804                         }
1805                     }
1806                 } else {
1807                     LocalGregorianCalendar.Date d = (LocalGregorianCalendar.Date) jdate.clone();
1808                     long nextJan1;
1809                     if (jdate.getYear() == 1) {
1810                         d.addYear(+1);
1811                         d.setMonth(LocalGregorianCalendar.JANUARY).setDayOfMonth(1);
1812                         nextJan1 = jcal.getFixedDate(d);
1813                     } else {
1814                         int nextEraIndex = getEraIndex(d) + 1;
1815                         CalendarDate cd = eras[nextEraIndex].getSinceDate();
1816                         d.setEra(eras[nextEraIndex]);
1817                         d.setDate(1, cd.getMonth(), cd.getDayOfMonth());
1818                         jcal.normalize(d);
1819                         nextJan1 = jcal.getFixedDate(d);
1820                     }
1821                     long nextJan1st = LocalGregorianCalendar.getDayOfWeekDateOnOrBefore(nextJan1 + 6,
1822                                                                                         getFirstDayOfWeek());
1823                     int ndays = (int)(nextJan1st - nextJan1);
1824                     if (ndays >= getMinimalDaysInFirstWeek() && fixedDate >= (nextJan1st - 7)) {
1825                         // The first days forms a week in which the date is included.
1826                         weekOfYear = 1;
1827                     }
1828                 }
1829             }
1830             internalSet(WEEK_OF_YEAR, weekOfYear);
1831             internalSet(WEEK_OF_MONTH, getWeekNumber(fixedDateMonth1, fixedDate));
1832             mask |= (DAY_OF_YEAR_MASK|WEEK_OF_YEAR_MASK|WEEK_OF_MONTH_MASK|DAY_OF_WEEK_IN_MONTH_MASK);
1833         }
1834         return mask;
1835     }
1836 
1837     /**
1838      * Returns the number of weeks in a period between fixedDay1 and
1839      * fixedDate. The getFirstDayOfWeek-getMinimalDaysInFirstWeek rule
1840      * is applied to calculate the number of weeks.
1841      *
1842      * @param fixedDay1 the fixed date of the first day of the period
1843      * @param fixedDate the fixed date of the last day of the period
1844      * @return the number of weeks of the given period
1845      */
1846     private int getWeekNumber(long fixedDay1, long fixedDate) {
1847         // We can always use `jcal' since Julian and Gregorian are the
1848         // same thing for this calculation.
1849         long fixedDay1st = LocalGregorianCalendar.getDayOfWeekDateOnOrBefore(fixedDay1 + 6,
1850                                                                              getFirstDayOfWeek());
1851         int ndays = (int)(fixedDay1st - fixedDay1);
1852         assert ndays <= 7;
1853         if (ndays >= getMinimalDaysInFirstWeek()) {
1854             fixedDay1st -= 7;
1855         }
1856         int normalizedDayOfPeriod = (int)(fixedDate - fixedDay1st);
1857         if (normalizedDayOfPeriod >= 0) {
1858             return normalizedDayOfPeriod / 7 + 1;
1859         }
1860         return CalendarUtils.floorDivide(normalizedDayOfPeriod, 7) + 1;
1861     }
1862 
1863     /**
1864      * Converts calendar field values to the time value (millisecond
1865      * offset from the <a href="Calendar.html#Epoch">Epoch</a>).
1866      *
1867      * @exception IllegalArgumentException if any calendar fields are invalid.
1868      */
1869     protected void computeTime() {
1870         // In non-lenient mode, perform brief checking of calendar
1871         // fields which have been set externally. Through this
1872         // checking, the field values are stored in originalFields[]
1873         // to see if any of them are normalized later.
1874         if (!isLenient()) {
1875             if (originalFields == null) {
1876                 originalFields = new int[FIELD_COUNT];
1877             }
1878             for (int field = 0; field < FIELD_COUNT; field++) {
1879                 int value = internalGet(field);
1880                 if (isExternallySet(field)) {
1881                     // Quick validation for any out of range values
1882                     if (value < getMinimum(field) || value > getMaximum(field)) {
1883                         throw new IllegalArgumentException(getFieldName(field));
1884                     }
1885                 }
1886                 originalFields[field] = value;
1887             }
1888         }
1889 
1890         // Let the super class determine which calendar fields to be
1891         // used to calculate the time.
1892         int fieldMask = selectFields();
1893 
1894         int year;
1895         int era;
1896 
1897         if (isSet(ERA)) {
1898             era = internalGet(ERA);
1899             year = isSet(YEAR) ? internalGet(YEAR) : 1;
1900         } else {
1901             if (isSet(YEAR)) {
1902                 era = currentEra;
1903                 year = internalGet(YEAR);
1904             } else {
1905                 // Equivalent to 1970 (Gregorian)
1906                 era = SHOWA;
1907                 year = 45;
1908             }
1909         }
1910 
1911         // Calculate the time of day. We rely on the convention that
1912         // an UNSET field has 0.
1913         long timeOfDay = 0;
1914         if (isFieldSet(fieldMask, HOUR_OF_DAY)) {
1915             timeOfDay += (long) internalGet(HOUR_OF_DAY);
1916         } else {
1917             timeOfDay += internalGet(HOUR);
1918             // The default value of AM_PM is 0 which designates AM.
1919             if (isFieldSet(fieldMask, AM_PM)) {
1920                 timeOfDay += 12 * internalGet(AM_PM);
1921             }
1922         }
1923         timeOfDay *= 60;
1924         timeOfDay += internalGet(MINUTE);
1925         timeOfDay *= 60;
1926         timeOfDay += internalGet(SECOND);
1927         timeOfDay *= 1000;
1928         timeOfDay += internalGet(MILLISECOND);
1929 
1930         // Convert the time of day to the number of days and the
1931         // millisecond offset from midnight.
1932         long fixedDate = timeOfDay / ONE_DAY;
1933         timeOfDay %= ONE_DAY;
1934         while (timeOfDay < 0) {
1935             timeOfDay += ONE_DAY;
1936             --fixedDate;
1937         }
1938 
1939         // Calculate the fixed date since January 1, 1 (Gregorian).
1940         fixedDate += getFixedDate(era, year, fieldMask);
1941 
1942         // millis represents local wall-clock time in milliseconds.
1943         long millis = (fixedDate - EPOCH_OFFSET) * ONE_DAY + timeOfDay;
1944 
1945         // Compute the time zone offset and DST offset.  There are two potential
1946         // ambiguities here.  We'll assume a 2:00 am (wall time) switchover time
1947         // for discussion purposes here.
1948         // 1. The transition into DST.  Here, a designated time of 2:00 am - 2:59 am
1949         //    can be in standard or in DST depending.  However, 2:00 am is an invalid
1950         //    representation (the representation jumps from 1:59:59 am Std to 3:00:00 am DST).
1951         //    We assume standard time.
1952         // 2. The transition out of DST.  Here, a designated time of 1:00 am - 1:59 am
1953         //    can be in standard or DST.  Both are valid representations (the rep
1954         //    jumps from 1:59:59 DST to 1:00:00 Std).
1955         //    Again, we assume standard time.
1956         // We use the TimeZone object, unless the user has explicitly set the ZONE_OFFSET
1957         // or DST_OFFSET fields; then we use those fields.
1958         TimeZone zone = getZone();
1959         if (zoneOffsets == null) {
1960             zoneOffsets = new int[2];
1961         }
1962         int tzMask = fieldMask & (ZONE_OFFSET_MASK|DST_OFFSET_MASK);
1963         if (tzMask != (ZONE_OFFSET_MASK|DST_OFFSET_MASK)) {
1964             if (zone instanceof ZoneInfo) {
1965                 ((ZoneInfo)zone).getOffsetsByWall(millis, zoneOffsets);
1966             } else {
1967                 zone.getOffsets(millis - zone.getRawOffset(), zoneOffsets);
1968             }
1969         }
1970         if (tzMask != 0) {
1971             if (isFieldSet(tzMask, ZONE_OFFSET)) {
1972                 zoneOffsets[0] = internalGet(ZONE_OFFSET);
1973             }
1974             if (isFieldSet(tzMask, DST_OFFSET)) {
1975                 zoneOffsets[1] = internalGet(DST_OFFSET);
1976             }
1977         }
1978 
1979         // Adjust the time zone offset values to get the UTC time.
1980         millis -= zoneOffsets[0] + zoneOffsets[1];
1981 
1982         // Set this calendar's time in milliseconds
1983         time = millis;
1984 
1985         int mask = computeFields(fieldMask | getSetStateFields(), tzMask);
1986 
1987         if (!isLenient()) {
1988             for (int field = 0; field < FIELD_COUNT; field++) {
1989                 if (!isExternallySet(field)) {
1990                     continue;
1991                 }
1992                 if (originalFields[field] != internalGet(field)) {
1993                     int wrongValue = internalGet(field);
1994                     // Restore the original field values
1995                     System.arraycopy(originalFields, 0, fields, 0, fields.length);
1996                     throw new IllegalArgumentException(getFieldName(field) + "=" + wrongValue
1997                                                        + ", expected " + originalFields[field]);
1998                 }
1999             }
2000         }
2001         setFieldsNormalized(mask);
2002     }
2003 
2004     /**
2005      * Computes the fixed date under either the Gregorian or the
2006      * Julian calendar, using the given year and the specified calendar fields.
2007      *
2008      * @param era era index
2009      * @param year the normalized year number, with 0 indicating the
2010      * year 1 BCE, -1 indicating 2 BCE, etc.
2011      * @param fieldMask the calendar fields to be used for the date calculation
2012      * @return the fixed date
2013      * @see Calendar#selectFields
2014      */
2015     private long getFixedDate(int era, int year, int fieldMask) {
2016         int month = JANUARY;
2017         int firstDayOfMonth = 1;
2018         if (isFieldSet(fieldMask, MONTH)) {
2019             // No need to check if MONTH has been set (no isSet(MONTH)
2020             // call) since its unset value happens to be JANUARY (0).
2021             month = internalGet(MONTH);
2022 
2023             // If the month is out of range, adjust it into range.
2024             if (month > DECEMBER) {
2025                 year += month / 12;
2026                 month %= 12;
2027             } else if (month < JANUARY) {
2028                 int[] rem = new int[1];
2029                 year += CalendarUtils.floorDivide(month, 12, rem);
2030                 month = rem[0];
2031             }
2032         } else {
2033             if (year == 1 && era != 0) {
2034                 CalendarDate d = eras[era].getSinceDate();
2035                 month = d.getMonth() - 1;
2036                 firstDayOfMonth = d.getDayOfMonth();
2037             }
2038         }
2039 
2040         // Adjust the base date if year is the minimum value.
2041         if (year == MIN_VALUES[YEAR]) {
2042             CalendarDate dx = jcal.getCalendarDate(Long.MIN_VALUE, getZone());
2043             int m = dx.getMonth() - 1;
2044             if (month < m) {
2045                 month = m;
2046             }
2047             if (month == m) {
2048                 firstDayOfMonth = dx.getDayOfMonth();
2049             }
2050         }
2051 
2052         LocalGregorianCalendar.Date date = jcal.newCalendarDate(TimeZone.NO_TIMEZONE);
2053         date.setEra(era > 0 ? eras[era] : null);
2054         date.setDate(year, month + 1, firstDayOfMonth);
2055         jcal.normalize(date);
2056 
2057         // Get the fixed date since Jan 1, 1 (Gregorian). We are on
2058         // the first day of either `month' or January in 'year'.
2059         long fixedDate = jcal.getFixedDate(date);
2060 
2061         if (isFieldSet(fieldMask, MONTH)) {
2062             // Month-based calculations
2063             if (isFieldSet(fieldMask, DAY_OF_MONTH)) {
2064                 // We are on the "first day" of the month (which may
2065                 // not be 1). Just add the offset if DAY_OF_MONTH is
2066                 // set. If the isSet call returns false, that means
2067                 // DAY_OF_MONTH has been selected just because of the
2068                 // selected combination. We don't need to add any
2069                 // since the default value is the "first day".
2070                 if (isSet(DAY_OF_MONTH)) {
2071                     // To avoid underflow with DAY_OF_MONTH-firstDayOfMonth, add
2072                     // DAY_OF_MONTH, then subtract firstDayOfMonth.
2073                     fixedDate += internalGet(DAY_OF_MONTH);
2074                     fixedDate -= firstDayOfMonth;
2075                 }
2076             } else {
2077                 if (isFieldSet(fieldMask, WEEK_OF_MONTH)) {
2078                     long firstDayOfWeek = LocalGregorianCalendar.getDayOfWeekDateOnOrBefore(fixedDate + 6,
2079                                                                                             getFirstDayOfWeek());
2080                     // If we have enough days in the first week, then
2081                     // move to the previous week.
2082                     if ((firstDayOfWeek - fixedDate) >= getMinimalDaysInFirstWeek()) {
2083                         firstDayOfWeek -= 7;
2084                     }
2085                     if (isFieldSet(fieldMask, DAY_OF_WEEK)) {
2086                         firstDayOfWeek = LocalGregorianCalendar.getDayOfWeekDateOnOrBefore(firstDayOfWeek + 6,
2087                                                                                            internalGet(DAY_OF_WEEK));
2088                     }
2089                     // In lenient mode, we treat days of the previous
2090                     // months as a part of the specified
2091                     // WEEK_OF_MONTH. See 4633646.
2092                     fixedDate = firstDayOfWeek + 7 * (internalGet(WEEK_OF_MONTH) - 1);
2093                 } else {
2094                     int dayOfWeek;
2095                     if (isFieldSet(fieldMask, DAY_OF_WEEK)) {
2096                         dayOfWeek = internalGet(DAY_OF_WEEK);
2097                     } else {
2098                         dayOfWeek = getFirstDayOfWeek();
2099                     }
2100                     // We are basing this on the day-of-week-in-month.  The only
2101                     // trickiness occurs if the day-of-week-in-month is
2102                     // negative.
2103                     int dowim;
2104                     if (isFieldSet(fieldMask, DAY_OF_WEEK_IN_MONTH)) {
2105                         dowim = internalGet(DAY_OF_WEEK_IN_MONTH);
2106                     } else {
2107                         dowim = 1;
2108                     }
2109                     if (dowim >= 0) {
2110                         fixedDate = LocalGregorianCalendar.getDayOfWeekDateOnOrBefore(fixedDate + (7 * dowim) - 1,
2111                                                                                       dayOfWeek);
2112                     } else {
2113                         // Go to the first day of the next week of
2114                         // the specified week boundary.
2115                         int lastDate = monthLength(month, year) + (7 * (dowim + 1));
2116                         // Then, get the day of week date on or before the last date.
2117                         fixedDate = LocalGregorianCalendar.getDayOfWeekDateOnOrBefore(fixedDate + lastDate - 1,
2118                                                                                       dayOfWeek);
2119                     }
2120                 }
2121             }
2122         } else {
2123             // We are on the first day of the year.
2124             if (isFieldSet(fieldMask, DAY_OF_YEAR)) {
2125                 if (isTransitionYear(date.getNormalizedYear())) {
2126                     fixedDate = getFixedDateJan1(date, fixedDate);
2127                 }
2128                 // Add the offset, then subtract 1. (Make sure to avoid underflow.)
2129                 fixedDate += internalGet(DAY_OF_YEAR);
2130                 fixedDate--;
2131             } else {
2132                 long firstDayOfWeek = LocalGregorianCalendar.getDayOfWeekDateOnOrBefore(fixedDate + 6,
2133                                                                                         getFirstDayOfWeek());
2134                 // If we have enough days in the first week, then move
2135                 // to the previous week.
2136                 if ((firstDayOfWeek - fixedDate) >= getMinimalDaysInFirstWeek()) {
2137                     firstDayOfWeek -= 7;
2138                 }
2139                 if (isFieldSet(fieldMask, DAY_OF_WEEK)) {
2140                     int dayOfWeek = internalGet(DAY_OF_WEEK);
2141                     if (dayOfWeek != getFirstDayOfWeek()) {
2142                         firstDayOfWeek = LocalGregorianCalendar.getDayOfWeekDateOnOrBefore(firstDayOfWeek + 6,
2143                                                                                            dayOfWeek);
2144                     }
2145                 }
2146                 fixedDate = firstDayOfWeek + 7 * ((long)internalGet(WEEK_OF_YEAR) - 1);
2147             }
2148         }
2149         return fixedDate;
2150     }
2151 
2152     /**
2153      * Returns the fixed date of the first day of the year (usually
2154      * January 1) before the specified date.
2155      *
2156      * @param date the date for which the first day of the year is
2157      * calculated. The date has to be in the cut-over year.
2158      * @param fixedDate the fixed date representation of the date
2159      */
2160     private long getFixedDateJan1(LocalGregorianCalendar.Date date, long fixedDate) {
2161         Era era = date.getEra();
2162         if (date.getEra() != null && date.getYear() == 1) {
2163             for (int eraIndex = getEraIndex(date); eraIndex > 0; eraIndex--) {
2164                 CalendarDate d = eras[eraIndex].getSinceDate();
2165                 long fd = gcal.getFixedDate(d);
2166                 // There might be multiple era transitions in a year.
2167                 if (fd > fixedDate) {
2168                     continue;
2169                 }
2170                 return fd;
2171             }
2172         }
2173         CalendarDate d = gcal.newCalendarDate(TimeZone.NO_TIMEZONE);
2174         d.setDate(date.getNormalizedYear(), Gregorian.JANUARY, 1);
2175         return gcal.getFixedDate(d);
2176     }
2177 
2178     /**
2179      * Returns the fixed date of the first date of the month (usually
2180      * the 1st of the month) before the specified date.
2181      *
2182      * @param date the date for which the first day of the month is
2183      * calculated. The date must be in the era transition year.
2184      * @param fixedDate the fixed date representation of the date
2185      */
2186     private long getFixedDateMonth1(LocalGregorianCalendar.Date date,
2187                                           long fixedDate) {
2188         int eraIndex = getTransitionEraIndex(date);
2189         if (eraIndex != -1) {
2190             long transition = sinceFixedDates[eraIndex];
2191             // If the given date is on or after the transition date, then
2192             // return the transition date.
2193             if (transition <= fixedDate) {
2194                 return transition;
2195             }
2196         }
2197 
2198         // Otherwise, we can use the 1st day of the month.
2199         return fixedDate - date.getDayOfMonth() + 1;
2200     }
2201 
2202     /**
2203      * Returns a LocalGregorianCalendar.Date produced from the specified fixed date.
2204      *
2205      * @param fd the fixed date
2206      */
2207     private static LocalGregorianCalendar.Date getCalendarDate(long fd) {
2208         LocalGregorianCalendar.Date d = jcal.newCalendarDate(TimeZone.NO_TIMEZONE);
2209         jcal.getCalendarDateFromFixedDate(d, fd);
2210         return d;
2211     }
2212 
2213     /**
2214      * Returns the length of the specified month in the specified
2215      * Gregorian year. The year number must be normalized.
2216      *
2217      * @see GregorianCalendar#isLeapYear(int)
2218      */
2219     private int monthLength(int month, int gregorianYear) {
2220         return CalendarUtils.isGregorianLeapYear(gregorianYear) ?
2221             GregorianCalendar.LEAP_MONTH_LENGTH[month] : GregorianCalendar.MONTH_LENGTH[month];
2222     }
2223 
2224     /**
2225      * Returns the length of the specified month in the year provided
2226      * by internalGet(YEAR).
2227      *
2228      * @see GregorianCalendar#isLeapYear(int)
2229      */
2230     private int monthLength(int month) {
2231         assert jdate.isNormalized();
2232         return jdate.isLeapYear() ?
2233             GregorianCalendar.LEAP_MONTH_LENGTH[month] : GregorianCalendar.MONTH_LENGTH[month];
2234     }
2235 
2236     private int actualMonthLength() {
2237         int length = jcal.getMonthLength(jdate);
2238         int eraIndex = getTransitionEraIndex(jdate);
2239         if (eraIndex == -1) {
2240             long transitionFixedDate = sinceFixedDates[eraIndex];
2241             CalendarDate d = eras[eraIndex].getSinceDate();
2242             if (transitionFixedDate <= cachedFixedDate) {
2243                 length -= d.getDayOfMonth() - 1;
2244             } else {
2245                 length = d.getDayOfMonth() - 1;
2246             }
2247         }
2248         return length;
2249     }
2250 
2251     /**
2252      * Returns the index to the new era if the given date is in a
2253      * transition month.  For example, if the give date is Heisei 1
2254      * (1989) January 20, then the era index for Heisei is
2255      * returned. Likewise, if the given date is Showa 64 (1989)
2256      * January 3, then the era index for Heisei is returned. If the
2257      * given date is not in any transition month, then -1 is returned.
2258      */
2259     private static int getTransitionEraIndex(LocalGregorianCalendar.Date date) {
2260         int eraIndex = getEraIndex(date);
2261         CalendarDate transitionDate = eras[eraIndex].getSinceDate();
2262         if (transitionDate.getYear() == date.getNormalizedYear() &&
2263             transitionDate.getMonth() == date.getMonth()) {
2264             return eraIndex;
2265         }
2266         if (eraIndex < eras.length - 1) {
2267             transitionDate = eras[++eraIndex].getSinceDate();
2268             if (transitionDate.getYear() == date.getNormalizedYear() &&
2269                 transitionDate.getMonth() == date.getMonth()) {
2270                 return eraIndex;
2271             }
2272         }
2273         return -1;
2274     }
2275 
2276     private boolean isTransitionYear(int normalizedYear) {
2277         for (int i = eras.length - 1; i > 0; i--) {
2278             int transitionYear = eras[i].getSinceDate().getYear();
2279             if (normalizedYear == transitionYear) {
2280                 return true;
2281             }
2282             if (normalizedYear > transitionYear) {
2283                 break;
2284             }
2285         }
2286         return false;
2287     }
2288 
2289     private static int getEraIndex(LocalGregorianCalendar.Date date) {
2290         Era era = date.getEra();
2291         for (int i = eras.length - 1; i > 0; i--) {
2292             if (eras[i] == era) {
2293                 return i;
2294             }
2295         }
2296         return 0;
2297     }
2298 
2299     /**
2300      * Returns this object if it's normalized (all fields and time are
2301      * in sync). Otherwise, a cloned object is returned after calling
2302      * complete() in lenient mode.
2303      */
2304     private JapaneseImperialCalendar getNormalizedCalendar() {
2305         JapaneseImperialCalendar jc;
2306         if (isFullyNormalized()) {
2307             jc = this;
2308         } else {
2309             // Create a clone and normalize the calendar fields
2310             jc = (JapaneseImperialCalendar) this.clone();
2311             jc.setLenient(true);
2312             jc.complete();
2313         }
2314         return jc;
2315     }
2316 
2317     /**
2318      * After adjustments such as add(MONTH), add(YEAR), we don't want the
2319      * month to jump around.  E.g., we don't want Jan 31 + 1 month to go to Mar
2320      * 3, we want it to go to Feb 28.  Adjustments which might run into this
2321      * problem call this method to retain the proper month.
2322      */
2323     private void pinDayOfMonth(LocalGregorianCalendar.Date date) {
2324         int year = date.getYear();
2325         int dom = date.getDayOfMonth();
2326         if (year != getMinimum(YEAR)) {
2327             date.setDayOfMonth(1);
2328             jcal.normalize(date);
2329             int monthLength = jcal.getMonthLength(date);
2330             if (dom > monthLength) {
2331                 date.setDayOfMonth(monthLength);
2332             } else {
2333                 date.setDayOfMonth(dom);
2334             }
2335             jcal.normalize(date);
2336         } else {
2337             LocalGregorianCalendar.Date d = jcal.getCalendarDate(Long.MIN_VALUE, getZone());
2338             LocalGregorianCalendar.Date realDate = jcal.getCalendarDate(time, getZone());
2339             long tod = realDate.getTimeOfDay();
2340             // Use an equivalent year.
2341             realDate.addYear(+400);
2342             realDate.setMonth(date.getMonth());
2343             realDate.setDayOfMonth(1);
2344             jcal.normalize(realDate);
2345             int monthLength = jcal.getMonthLength(realDate);
2346             if (dom > monthLength) {
2347                 realDate.setDayOfMonth(monthLength);
2348             } else {
2349                 if (dom < d.getDayOfMonth()) {
2350                     realDate.setDayOfMonth(d.getDayOfMonth());
2351                 } else {
2352                     realDate.setDayOfMonth(dom);
2353                 }
2354             }
2355             if (realDate.getDayOfMonth() == d.getDayOfMonth() && tod < d.getTimeOfDay()) {
2356                 realDate.setDayOfMonth(Math.min(dom + 1, monthLength));
2357             }
2358             // restore the year.
2359             date.setDate(year, realDate.getMonth(), realDate.getDayOfMonth());
2360             // Don't normalize date here so as not to cause underflow.
2361         }
2362     }
2363 
2364     /**
2365      * Returns the new value after 'roll'ing the specified value and amount.
2366      */
2367     private static int getRolledValue(int value, int amount, int min, int max) {
2368         assert value >= min && value <= max;
2369         int range = max - min + 1;
2370         amount %= range;
2371         int n = value + amount;
2372         if (n > max) {
2373             n -= range;
2374         } else if (n < min) {
2375             n += range;
2376         }
2377         assert n >= min && n <= max;
2378         return n;
2379     }
2380 
2381     /**
2382      * Returns the ERA.  We need a special method for this because the
2383      * default ERA is the current era, but a zero (unset) ERA means before Meiji.
2384      */
2385     private int internalGetEra() {
2386         return isSet(ERA) ? internalGet(ERA) : currentEra;
2387     }
2388 
2389     /**
2390      * Updates internal state.
2391      */
2392     private void readObject(ObjectInputStream stream)
2393             throws IOException, ClassNotFoundException {
2394         stream.defaultReadObject();
2395         if (jdate == null) {
2396             jdate = jcal.newCalendarDate(getZone());
2397             cachedFixedDate = Long.MIN_VALUE;
2398         }
2399     }
2400 }