Path: blob/master/src/java.base/share/classes/java/time/chrono/AbstractChronology.java
41159 views
/*1* Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* This file is available under and governed by the GNU General Public27* License version 2 only, as published by the Free Software Foundation.28* However, the following notice accompanied the original version of this29* file:30*31* Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos32*33* All rights reserved.34*35* Redistribution and use in source and binary forms, with or without36* modification, are permitted provided that the following conditions are met:37*38* * Redistributions of source code must retain the above copyright notice,39* this list of conditions and the following disclaimer.40*41* * Redistributions in binary form must reproduce the above copyright notice,42* this list of conditions and the following disclaimer in the documentation43* and/or other materials provided with the distribution.44*45* * Neither the name of JSR-310 nor the names of its contributors46* may be used to endorse or promote products derived from this software47* without specific prior written permission.48*49* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS50* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT51* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR52* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR53* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,54* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,55* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR56* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF57* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING58* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS59* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.60*/61package java.time.chrono;6263import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH;64import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR;65import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_MONTH;66import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_YEAR;67import static java.time.temporal.ChronoField.DAY_OF_MONTH;68import static java.time.temporal.ChronoField.DAY_OF_WEEK;69import static java.time.temporal.ChronoField.DAY_OF_YEAR;70import static java.time.temporal.ChronoField.EPOCH_DAY;71import static java.time.temporal.ChronoField.ERA;72import static java.time.temporal.ChronoField.MONTH_OF_YEAR;73import static java.time.temporal.ChronoField.PROLEPTIC_MONTH;74import static java.time.temporal.ChronoField.YEAR;75import static java.time.temporal.ChronoField.YEAR_OF_ERA;76import static java.time.temporal.ChronoUnit.DAYS;77import static java.time.temporal.ChronoUnit.MONTHS;78import static java.time.temporal.ChronoUnit.WEEKS;79import static java.time.temporal.TemporalAdjusters.nextOrSame;8081import java.io.DataInput;82import java.io.DataOutput;83import java.io.IOException;84import java.io.InvalidObjectException;85import java.io.ObjectInputStream;86import java.io.ObjectStreamException;87import java.io.Serializable;88import java.time.DateTimeException;89import java.time.DayOfWeek;90import java.time.format.ResolverStyle;91import java.time.temporal.ChronoField;92import java.time.temporal.TemporalAdjusters;93import java.time.temporal.TemporalField;94import java.time.temporal.ValueRange;95import java.util.Comparator;96import java.util.HashSet;97import java.util.List;98import java.util.Locale;99import java.util.Map;100import java.util.Objects;101import java.util.ServiceLoader;102import java.util.Set;103import java.util.concurrent.ConcurrentHashMap;104105import sun.util.logging.PlatformLogger;106107/**108* An abstract implementation of a calendar system, used to organize and identify dates.109* <p>110* The main date and time API is built on the ISO calendar system.111* The chronology operates behind the scenes to represent the general concept of a calendar system.112* <p>113* See {@link Chronology} for more details.114*115* @implSpec116* This class is separated from the {@code Chronology} interface so that the static methods117* are not inherited. While {@code Chronology} can be implemented directly, it is strongly118* recommended to extend this abstract class instead.119* <p>120* This class must be implemented with care to ensure other classes operate correctly.121* All implementations that can be instantiated must be final, immutable and thread-safe.122* Subclasses should be Serializable wherever possible.123*124* @since 1.8125*/126public abstract class AbstractChronology implements Chronology {127128/**129* Map of available calendars by ID.130*/131private static final ConcurrentHashMap<String, Chronology> CHRONOS_BY_ID = new ConcurrentHashMap<>();132/**133* Map of available calendars by calendar type.134*/135private static final ConcurrentHashMap<String, Chronology> CHRONOS_BY_TYPE = new ConcurrentHashMap<>();136137/**138* Register a Chronology by its ID and type for lookup by {@link #of(String)}.139* Chronologies must not be registered until they are completely constructed.140* Specifically, not in the constructor of Chronology.141*142* @param chrono the chronology to register; not null143* @return the already registered Chronology if any, may be null144*/145static Chronology registerChrono(Chronology chrono) {146return registerChrono(chrono, chrono.getId());147}148149/**150* Register a Chronology by ID and type for lookup by {@link #of(String)}.151* Chronos must not be registered until they are completely constructed.152* Specifically, not in the constructor of Chronology.153*154* @param chrono the chronology to register; not null155* @param id the ID to register the chronology; not null156* @return the already registered Chronology if any, may be null157*/158static Chronology registerChrono(Chronology chrono, String id) {159Chronology prev = CHRONOS_BY_ID.putIfAbsent(id, chrono);160if (prev == null) {161String type = chrono.getCalendarType();162if (type != null) {163CHRONOS_BY_TYPE.putIfAbsent(type, chrono);164}165}166return prev;167}168169/**170* Initialization of the maps from id and type to Chronology.171* The ServiceLoader is used to find and register any implementations172* of {@link java.time.chrono.AbstractChronology} found in the bootclass loader.173* The built-in chronologies are registered explicitly.174* Calendars configured via the Thread's context classloader are local175* to that thread and are ignored.176* <p>177* The initialization is done only once using the registration178* of the IsoChronology as the test and the final step.179* Multiple threads may perform the initialization concurrently.180* Only the first registration of each Chronology is retained by the181* ConcurrentHashMap.182* @return true if the cache was initialized183*/184private static boolean initCache() {185if (CHRONOS_BY_ID.get("ISO") == null) {186// Initialization is incomplete187188// Register built-in Chronologies189registerChrono(HijrahChronology.INSTANCE);190registerChrono(JapaneseChronology.INSTANCE);191registerChrono(MinguoChronology.INSTANCE);192registerChrono(ThaiBuddhistChronology.INSTANCE);193194// Register Chronologies from the ServiceLoader195@SuppressWarnings("rawtypes")196ServiceLoader<AbstractChronology> loader = ServiceLoader.load(AbstractChronology.class, null);197for (AbstractChronology chrono : loader) {198String id = chrono.getId();199if (id.equals("ISO") || registerChrono(chrono) != null) {200// Log the attempt to replace an existing Chronology201PlatformLogger logger = PlatformLogger.getLogger("java.time.chrono");202logger.warning("Ignoring duplicate Chronology, from ServiceLoader configuration " + id);203}204}205206// finally, register IsoChronology to mark initialization is complete207registerChrono(IsoChronology.INSTANCE);208return true;209}210return false;211}212213//-----------------------------------------------------------------------214/**215* Obtains an instance of {@code Chronology} from a locale.216* <p>217* See {@link Chronology#ofLocale(Locale)}.218*219* @param locale the locale to use to obtain the calendar system, not null220* @return the calendar system associated with the locale, not null221* @throws java.time.DateTimeException if the locale-specified calendar cannot be found222*/223static Chronology ofLocale(Locale locale) {224Objects.requireNonNull(locale, "locale");225String type = locale.getUnicodeLocaleType("ca");226if (type == null || "iso".equals(type) || "iso8601".equals(type)) {227return IsoChronology.INSTANCE;228}229// Not pre-defined; lookup by the type230do {231Chronology chrono = CHRONOS_BY_TYPE.get(type);232if (chrono != null) {233return chrono;234}235// If not found, do the initialization (once) and repeat the lookup236} while (initCache());237238// Look for a Chronology using ServiceLoader of the Thread's ContextClassLoader239// Application provided Chronologies must not be cached240@SuppressWarnings("rawtypes")241ServiceLoader<Chronology> loader = ServiceLoader.load(Chronology.class);242for (Chronology chrono : loader) {243if (type.equals(chrono.getCalendarType())) {244return chrono;245}246}247throw new DateTimeException("Unknown calendar system: " + type);248}249250//-----------------------------------------------------------------------251/**252* Obtains an instance of {@code Chronology} from a chronology ID or253* calendar system type.254* <p>255* See {@link Chronology#of(String)}.256*257* @param id the chronology ID or calendar system type, not null258* @return the chronology with the identifier requested, not null259* @throws java.time.DateTimeException if the chronology cannot be found260*/261static Chronology of(String id) {262Objects.requireNonNull(id, "id");263do {264Chronology chrono = of0(id);265if (chrono != null) {266return chrono;267}268// If not found, do the initialization (once) and repeat the lookup269} while (initCache());270271// Look for a Chronology using ServiceLoader of the Thread's ContextClassLoader272// Application provided Chronologies must not be cached273@SuppressWarnings("rawtypes")274ServiceLoader<Chronology> loader = ServiceLoader.load(Chronology.class);275for (Chronology chrono : loader) {276if (id.equals(chrono.getId()) || id.equals(chrono.getCalendarType())) {277return chrono;278}279}280throw new DateTimeException("Unknown chronology: " + id);281}282283/**284* Obtains an instance of {@code Chronology} from a chronology ID or285* calendar system type.286*287* @param id the chronology ID or calendar system type, not null288* @return the chronology with the identifier requested, or {@code null} if not found289*/290private static Chronology of0(String id) {291Chronology chrono = CHRONOS_BY_ID.get(id);292if (chrono == null) {293chrono = CHRONOS_BY_TYPE.get(id);294}295return chrono;296}297298/**299* Returns the available chronologies.300* <p>301* Each returned {@code Chronology} is available for use in the system.302* The set of chronologies includes the system chronologies and303* any chronologies provided by the application via ServiceLoader304* configuration.305*306* @return the independent, modifiable set of the available chronology IDs, not null307*/308static Set<Chronology> getAvailableChronologies() {309initCache(); // force initialization310HashSet<Chronology> chronos = new HashSet<>(CHRONOS_BY_ID.values());311312/// Add in Chronologies from the ServiceLoader configuration313@SuppressWarnings("rawtypes")314ServiceLoader<Chronology> loader = ServiceLoader.load(Chronology.class);315for (Chronology chrono : loader) {316chronos.add(chrono);317}318return chronos;319}320321//-----------------------------------------------------------------------322/**323* Creates an instance.324*/325protected AbstractChronology() {326}327328//-----------------------------------------------------------------------329/**330* Resolves parsed {@code ChronoField} values into a date during parsing.331* <p>332* Most {@code TemporalField} implementations are resolved using the333* resolve method on the field. By contrast, the {@code ChronoField} class334* defines fields that only have meaning relative to the chronology.335* As such, {@code ChronoField} date fields are resolved here in the336* context of a specific chronology.337* <p>338* {@code ChronoField} instances are resolved by this method, which may339* be overridden in subclasses.340* <ul>341* <li>{@code EPOCH_DAY} - If present, this is converted to a date and342* all other date fields are then cross-checked against the date.343* <li>{@code PROLEPTIC_MONTH} - If present, then it is split into the344* {@code YEAR} and {@code MONTH_OF_YEAR}. If the mode is strict or smart345* then the field is validated.346* <li>{@code YEAR_OF_ERA} and {@code ERA} - If both are present, then they347* are combined to form a {@code YEAR}. In lenient mode, the {@code YEAR_OF_ERA}348* range is not validated, in smart and strict mode it is. The {@code ERA} is349* validated for range in all three modes. If only the {@code YEAR_OF_ERA} is350* present, and the mode is smart or lenient, then the last available era351* is assumed. In strict mode, no era is assumed and the {@code YEAR_OF_ERA} is352* left untouched. If only the {@code ERA} is present, then it is left untouched.353* <li>{@code YEAR}, {@code MONTH_OF_YEAR} and {@code DAY_OF_MONTH} -354* If all three are present, then they are combined to form a date.355* In all three modes, the {@code YEAR} is validated.356* If the mode is smart or strict, then the month and day are validated.357* If the mode is lenient, then the date is combined in a manner equivalent to358* creating a date on the first day of the first month in the requested year,359* then adding the difference in months, then the difference in days.360* If the mode is smart, and the day-of-month is greater than the maximum for361* the year-month, then the day-of-month is adjusted to the last day-of-month.362* If the mode is strict, then the three fields must form a valid date.363* <li>{@code YEAR} and {@code DAY_OF_YEAR} -364* If both are present, then they are combined to form a date.365* In all three modes, the {@code YEAR} is validated.366* If the mode is lenient, then the date is combined in a manner equivalent to367* creating a date on the first day of the requested year, then adding368* the difference in days.369* If the mode is smart or strict, then the two fields must form a valid date.370* <li>{@code YEAR}, {@code MONTH_OF_YEAR}, {@code ALIGNED_WEEK_OF_MONTH} and371* {@code ALIGNED_DAY_OF_WEEK_IN_MONTH} -372* If all four are present, then they are combined to form a date.373* In all three modes, the {@code YEAR} is validated.374* If the mode is lenient, then the date is combined in a manner equivalent to375* creating a date on the first day of the first month in the requested year, then adding376* the difference in months, then the difference in weeks, then in days.377* If the mode is smart or strict, then the all four fields are validated to378* their outer ranges. The date is then combined in a manner equivalent to379* creating a date on the first day of the requested year and month, then adding380* the amount in weeks and days to reach their values. If the mode is strict,381* the date is additionally validated to check that the day and week adjustment382* did not change the month.383* <li>{@code YEAR}, {@code MONTH_OF_YEAR}, {@code ALIGNED_WEEK_OF_MONTH} and384* {@code DAY_OF_WEEK} - If all four are present, then they are combined to385* form a date. The approach is the same as described above for386* years, months and weeks in {@code ALIGNED_DAY_OF_WEEK_IN_MONTH}.387* The day-of-week is adjusted as the next or same matching day-of-week once388* the years, months and weeks have been handled.389* <li>{@code YEAR}, {@code ALIGNED_WEEK_OF_YEAR} and {@code ALIGNED_DAY_OF_WEEK_IN_YEAR} -390* If all three are present, then they are combined to form a date.391* In all three modes, the {@code YEAR} is validated.392* If the mode is lenient, then the date is combined in a manner equivalent to393* creating a date on the first day of the requested year, then adding394* the difference in weeks, then in days.395* If the mode is smart or strict, then the all three fields are validated to396* their outer ranges. The date is then combined in a manner equivalent to397* creating a date on the first day of the requested year, then adding398* the amount in weeks and days to reach their values. If the mode is strict,399* the date is additionally validated to check that the day and week adjustment400* did not change the year.401* <li>{@code YEAR}, {@code ALIGNED_WEEK_OF_YEAR} and {@code DAY_OF_WEEK} -402* If all three are present, then they are combined to form a date.403* The approach is the same as described above for years and weeks in404* {@code ALIGNED_DAY_OF_WEEK_IN_YEAR}. The day-of-week is adjusted as the405* next or same matching day-of-week once the years and weeks have been handled.406* </ul>407* <p>408* The default implementation is suitable for most calendar systems.409* If {@link java.time.temporal.ChronoField#YEAR_OF_ERA} is found without an {@link java.time.temporal.ChronoField#ERA}410* then the last era in {@link #eras()} is used.411* The implementation assumes a 7 day week, that the first day-of-month412* has the value 1, that first day-of-year has the value 1, and that the413* first of the month and year always exists.414*415* @param fieldValues the map of fields to values, which can be updated, not null416* @param resolverStyle the requested type of resolve, not null417* @return the resolved date, null if insufficient information to create a date418* @throws java.time.DateTimeException if the date cannot be resolved, typically419* because of a conflict in the input data420*/421@Override422public ChronoLocalDate resolveDate(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {423// check epoch-day before inventing era424if (fieldValues.containsKey(EPOCH_DAY)) {425return dateEpochDay(fieldValues.remove(EPOCH_DAY));426}427428// fix proleptic month before inventing era429resolveProlepticMonth(fieldValues, resolverStyle);430431// invent era if necessary to resolve year-of-era432ChronoLocalDate resolved = resolveYearOfEra(fieldValues, resolverStyle);433if (resolved != null) {434return resolved;435}436437// build date438if (fieldValues.containsKey(YEAR)) {439if (fieldValues.containsKey(MONTH_OF_YEAR)) {440if (fieldValues.containsKey(DAY_OF_MONTH)) {441return resolveYMD(fieldValues, resolverStyle);442}443if (fieldValues.containsKey(ALIGNED_WEEK_OF_MONTH)) {444if (fieldValues.containsKey(ALIGNED_DAY_OF_WEEK_IN_MONTH)) {445return resolveYMAA(fieldValues, resolverStyle);446}447if (fieldValues.containsKey(DAY_OF_WEEK)) {448return resolveYMAD(fieldValues, resolverStyle);449}450}451}452if (fieldValues.containsKey(DAY_OF_YEAR)) {453return resolveYD(fieldValues, resolverStyle);454}455if (fieldValues.containsKey(ALIGNED_WEEK_OF_YEAR)) {456if (fieldValues.containsKey(ALIGNED_DAY_OF_WEEK_IN_YEAR)) {457return resolveYAA(fieldValues, resolverStyle);458}459if (fieldValues.containsKey(DAY_OF_WEEK)) {460return resolveYAD(fieldValues, resolverStyle);461}462}463}464return null;465}466467void resolveProlepticMonth(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {468Long pMonth = fieldValues.remove(PROLEPTIC_MONTH);469if (pMonth != null) {470if (resolverStyle != ResolverStyle.LENIENT) {471PROLEPTIC_MONTH.checkValidValue(pMonth);472}473// first day-of-month is likely to be safest for setting proleptic-month474// cannot add to year zero, as not all chronologies have a year zero475ChronoLocalDate chronoDate = dateNow()476.with(DAY_OF_MONTH, 1).with(PROLEPTIC_MONTH, pMonth);477addFieldValue(fieldValues, MONTH_OF_YEAR, chronoDate.get(MONTH_OF_YEAR));478addFieldValue(fieldValues, YEAR, chronoDate.get(YEAR));479}480}481482ChronoLocalDate resolveYearOfEra(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {483Long yoeLong = fieldValues.remove(YEAR_OF_ERA);484if (yoeLong != null) {485Long eraLong = fieldValues.remove(ERA);486int yoe;487if (resolverStyle != ResolverStyle.LENIENT) {488yoe = range(YEAR_OF_ERA).checkValidIntValue(yoeLong, YEAR_OF_ERA);489} else {490yoe = Math.toIntExact(yoeLong);491}492if (eraLong != null) {493Era eraObj = eraOf(range(ERA).checkValidIntValue(eraLong, ERA));494addFieldValue(fieldValues, YEAR, prolepticYear(eraObj, yoe));495} else {496if (fieldValues.containsKey(YEAR)) {497int year = range(YEAR).checkValidIntValue(fieldValues.get(YEAR), YEAR);498ChronoLocalDate chronoDate = dateYearDay(year, 1);499addFieldValue(fieldValues, YEAR, prolepticYear(chronoDate.getEra(), yoe));500} else if (resolverStyle == ResolverStyle.STRICT) {501// do not invent era if strict502// reinstate the field removed earlier, no cross-check issues503fieldValues.put(YEAR_OF_ERA, yoeLong);504} else {505List<Era> eras = eras();506if (eras.isEmpty()) {507addFieldValue(fieldValues, YEAR, yoe);508} else {509Era eraObj = eras.get(eras.size() - 1);510addFieldValue(fieldValues, YEAR, prolepticYear(eraObj, yoe));511}512}513}514} else if (fieldValues.containsKey(ERA)) {515range(ERA).checkValidValue(fieldValues.get(ERA), ERA); // always validated516}517return null;518}519520ChronoLocalDate resolveYMD(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {521int y = range(YEAR).checkValidIntValue(fieldValues.remove(YEAR), YEAR);522if (resolverStyle == ResolverStyle.LENIENT) {523long months = Math.subtractExact(fieldValues.remove(MONTH_OF_YEAR), 1);524long days = Math.subtractExact(fieldValues.remove(DAY_OF_MONTH), 1);525return date(y, 1, 1).plus(months, MONTHS).plus(days, DAYS);526}527int moy = range(MONTH_OF_YEAR).checkValidIntValue(fieldValues.remove(MONTH_OF_YEAR), MONTH_OF_YEAR);528ValueRange domRange = range(DAY_OF_MONTH);529int dom = domRange.checkValidIntValue(fieldValues.remove(DAY_OF_MONTH), DAY_OF_MONTH);530if (resolverStyle == ResolverStyle.SMART) { // previous valid531try {532return date(y, moy, dom);533} catch (DateTimeException ex) {534return date(y, moy, 1).with(TemporalAdjusters.lastDayOfMonth());535}536}537return date(y, moy, dom);538}539540ChronoLocalDate resolveYD(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {541int y = range(YEAR).checkValidIntValue(fieldValues.remove(YEAR), YEAR);542if (resolverStyle == ResolverStyle.LENIENT) {543long days = Math.subtractExact(fieldValues.remove(DAY_OF_YEAR), 1);544return dateYearDay(y, 1).plus(days, DAYS);545}546int doy = range(DAY_OF_YEAR).checkValidIntValue(fieldValues.remove(DAY_OF_YEAR), DAY_OF_YEAR);547return dateYearDay(y, doy); // smart is same as strict548}549550ChronoLocalDate resolveYMAA(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {551int y = range(YEAR).checkValidIntValue(fieldValues.remove(YEAR), YEAR);552if (resolverStyle == ResolverStyle.LENIENT) {553long months = Math.subtractExact(fieldValues.remove(MONTH_OF_YEAR), 1);554long weeks = Math.subtractExact(fieldValues.remove(ALIGNED_WEEK_OF_MONTH), 1);555long days = Math.subtractExact(fieldValues.remove(ALIGNED_DAY_OF_WEEK_IN_MONTH), 1);556return date(y, 1, 1).plus(months, MONTHS).plus(weeks, WEEKS).plus(days, DAYS);557}558int moy = range(MONTH_OF_YEAR).checkValidIntValue(fieldValues.remove(MONTH_OF_YEAR), MONTH_OF_YEAR);559int aw = range(ALIGNED_WEEK_OF_MONTH).checkValidIntValue(fieldValues.remove(ALIGNED_WEEK_OF_MONTH), ALIGNED_WEEK_OF_MONTH);560int ad = range(ALIGNED_DAY_OF_WEEK_IN_MONTH).checkValidIntValue(fieldValues.remove(ALIGNED_DAY_OF_WEEK_IN_MONTH), ALIGNED_DAY_OF_WEEK_IN_MONTH);561ChronoLocalDate date = date(y, moy, 1).plus((aw - 1) * 7 + (ad - 1), DAYS);562if (resolverStyle == ResolverStyle.STRICT && date.get(MONTH_OF_YEAR) != moy) {563throw new DateTimeException("Strict mode rejected resolved date as it is in a different month");564}565return date;566}567568ChronoLocalDate resolveYMAD(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {569int y = range(YEAR).checkValidIntValue(fieldValues.remove(YEAR), YEAR);570if (resolverStyle == ResolverStyle.LENIENT) {571long months = Math.subtractExact(fieldValues.remove(MONTH_OF_YEAR), 1);572long weeks = Math.subtractExact(fieldValues.remove(ALIGNED_WEEK_OF_MONTH), 1);573long dow = Math.subtractExact(fieldValues.remove(DAY_OF_WEEK), 1);574return resolveAligned(date(y, 1, 1), months, weeks, dow);575}576int moy = range(MONTH_OF_YEAR).checkValidIntValue(fieldValues.remove(MONTH_OF_YEAR), MONTH_OF_YEAR);577int aw = range(ALIGNED_WEEK_OF_MONTH).checkValidIntValue(fieldValues.remove(ALIGNED_WEEK_OF_MONTH), ALIGNED_WEEK_OF_MONTH);578int dow = range(DAY_OF_WEEK).checkValidIntValue(fieldValues.remove(DAY_OF_WEEK), DAY_OF_WEEK);579ChronoLocalDate date = date(y, moy, 1).plus((aw - 1) * 7, DAYS).with(nextOrSame(DayOfWeek.of(dow)));580if (resolverStyle == ResolverStyle.STRICT && date.get(MONTH_OF_YEAR) != moy) {581throw new DateTimeException("Strict mode rejected resolved date as it is in a different month");582}583return date;584}585586ChronoLocalDate resolveYAA(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {587int y = range(YEAR).checkValidIntValue(fieldValues.remove(YEAR), YEAR);588if (resolverStyle == ResolverStyle.LENIENT) {589long weeks = Math.subtractExact(fieldValues.remove(ALIGNED_WEEK_OF_YEAR), 1);590long days = Math.subtractExact(fieldValues.remove(ALIGNED_DAY_OF_WEEK_IN_YEAR), 1);591return dateYearDay(y, 1).plus(weeks, WEEKS).plus(days, DAYS);592}593int aw = range(ALIGNED_WEEK_OF_YEAR).checkValidIntValue(fieldValues.remove(ALIGNED_WEEK_OF_YEAR), ALIGNED_WEEK_OF_YEAR);594int ad = range(ALIGNED_DAY_OF_WEEK_IN_YEAR).checkValidIntValue(fieldValues.remove(ALIGNED_DAY_OF_WEEK_IN_YEAR), ALIGNED_DAY_OF_WEEK_IN_YEAR);595ChronoLocalDate date = dateYearDay(y, 1).plus((aw - 1) * 7 + (ad - 1), DAYS);596if (resolverStyle == ResolverStyle.STRICT && date.get(YEAR) != y) {597throw new DateTimeException("Strict mode rejected resolved date as it is in a different year");598}599return date;600}601602ChronoLocalDate resolveYAD(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {603int y = range(YEAR).checkValidIntValue(fieldValues.remove(YEAR), YEAR);604if (resolverStyle == ResolverStyle.LENIENT) {605long weeks = Math.subtractExact(fieldValues.remove(ALIGNED_WEEK_OF_YEAR), 1);606long dow = Math.subtractExact(fieldValues.remove(DAY_OF_WEEK), 1);607return resolveAligned(dateYearDay(y, 1), 0, weeks, dow);608}609int aw = range(ALIGNED_WEEK_OF_YEAR).checkValidIntValue(fieldValues.remove(ALIGNED_WEEK_OF_YEAR), ALIGNED_WEEK_OF_YEAR);610int dow = range(DAY_OF_WEEK).checkValidIntValue(fieldValues.remove(DAY_OF_WEEK), DAY_OF_WEEK);611ChronoLocalDate date = dateYearDay(y, 1).plus((aw - 1) * 7, DAYS).with(nextOrSame(DayOfWeek.of(dow)));612if (resolverStyle == ResolverStyle.STRICT && date.get(YEAR) != y) {613throw new DateTimeException("Strict mode rejected resolved date as it is in a different year");614}615return date;616}617618ChronoLocalDate resolveAligned(ChronoLocalDate base, long months, long weeks, long dow) {619ChronoLocalDate date = base.plus(months, MONTHS).plus(weeks, WEEKS);620if (dow > 7) {621date = date.plus((dow - 1) / 7, WEEKS);622dow = ((dow - 1) % 7) + 1;623} else if (dow < 1) {624date = date.plus(Math.subtractExact(dow, 7) / 7, WEEKS);625dow = ((dow + 6) % 7) + 1;626}627return date.with(nextOrSame(DayOfWeek.of((int) dow)));628}629630/**631* Adds a field-value pair to the map, checking for conflicts.632* <p>633* If the field is not already present, then the field-value pair is added to the map.634* If the field is already present and it has the same value as that specified, no action occurs.635* If the field is already present and it has a different value to that specified, then636* an exception is thrown.637*638* @param field the field to add, not null639* @param value the value to add, not null640* @throws java.time.DateTimeException if the field is already present with a different value641*/642void addFieldValue(Map<TemporalField, Long> fieldValues, ChronoField field, long value) {643Long old = fieldValues.get(field); // check first for better error message644if (old != null && old.longValue() != value) {645throw new DateTimeException("Conflict found: " + field + " " + old + " differs from " + field + " " + value);646}647fieldValues.put(field, value);648}649650//-----------------------------------------------------------------------651/**652* Compares this chronology to another chronology.653* <p>654* The comparison order first by the chronology ID string, then by any655* additional information specific to the subclass.656* It is "consistent with equals", as defined by {@link Comparable}.657*658* @implSpec659* This implementation compares the chronology ID.660* Subclasses must compare any additional state that they store.661*662* @param other the other chronology to compare to, not null663* @return the comparator value, negative if less, positive if greater664*/665@Override666public int compareTo(Chronology other) {667return getId().compareTo(other.getId());668}669670/**671* Checks if this chronology is equal to another chronology.672* <p>673* The comparison is based on the entire state of the object.674*675* @implSpec676* This implementation checks the type and calls677* {@link #compareTo(java.time.chrono.Chronology)}.678*679* @param obj the object to check, null returns false680* @return true if this is equal to the other chronology681*/682@Override683public boolean equals(Object obj) {684if (this == obj) {685return true;686}687if (obj instanceof AbstractChronology) {688return compareTo((AbstractChronology) obj) == 0;689}690return false;691}692693/**694* A hash code for this chronology.695* <p>696* The hash code should be based on the entire state of the object.697*698* @implSpec699* This implementation is based on the chronology ID and class.700* Subclasses should add any additional state that they store.701*702* @return a suitable hash code703*/704@Override705public int hashCode() {706return getClass().hashCode() ^ getId().hashCode();707}708709//-----------------------------------------------------------------------710/**711* Outputs this chronology as a {@code String}, using the chronology ID.712*713* @return a string representation of this chronology, not null714*/715@Override716public String toString() {717return getId();718}719720//-----------------------------------------------------------------------721/**722* Writes the Chronology using a723* <a href="{@docRoot}/serialized-form.html#java.time.chrono.Ser">dedicated serialized form</a>.724* <pre>725* out.writeByte(1); // identifies this as a Chronology726* out.writeUTF(getId());727* </pre>728*729* @return the instance of {@code Ser}, not null730*/731@java.io.Serial732Object writeReplace() {733return new Ser(Ser.CHRONO_TYPE, (Serializable)this);734}735736/**737* Defend against malicious streams.738*739* @param s the stream to read740* @throws java.io.InvalidObjectException always741*/742@java.io.Serial743private void readObject(ObjectInputStream s) throws ObjectStreamException {744throw new InvalidObjectException("Deserialization via serialization delegate");745}746747void writeExternal(DataOutput out) throws IOException {748out.writeUTF(getId());749}750751static Chronology readExternal(DataInput in) throws IOException {752String id = in.readUTF();753return Chronology.of(id);754}755756}757758759