Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/time/format/DateTimePrintContext.java
38918 views
/*1* Copyright (c) 2012, 2013, 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) 2011-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.format;6263import static java.time.temporal.ChronoField.EPOCH_DAY;64import static java.time.temporal.ChronoField.INSTANT_SECONDS;65import static java.time.temporal.ChronoField.OFFSET_SECONDS;6667import java.time.DateTimeException;68import java.time.Instant;69import java.time.ZoneId;70import java.time.ZoneOffset;71import java.time.chrono.ChronoLocalDate;72import java.time.chrono.Chronology;73import java.time.chrono.IsoChronology;74import java.time.temporal.ChronoField;75import java.time.temporal.TemporalAccessor;76import java.time.temporal.TemporalField;77import java.time.temporal.TemporalQueries;78import java.time.temporal.TemporalQuery;79import java.time.temporal.ValueRange;80import java.util.Locale;81import java.util.Objects;8283/**84* Context object used during date and time printing.85* <p>86* This class provides a single wrapper to items used in the format.87*88* @implSpec89* This class is a mutable context intended for use from a single thread.90* Usage of the class is thread-safe within standard printing as the framework creates91* a new instance of the class for each format and printing is single-threaded.92*93* @since 1.894*/95final class DateTimePrintContext {9697/**98* The temporal being output.99*/100private TemporalAccessor temporal;101/**102* The formatter, not null.103*/104private DateTimeFormatter formatter;105/**106* Whether the current formatter is optional.107*/108private int optional;109110/**111* Creates a new instance of the context.112*113* @param temporal the temporal object being output, not null114* @param formatter the formatter controlling the format, not null115*/116DateTimePrintContext(TemporalAccessor temporal, DateTimeFormatter formatter) {117super();118this.temporal = adjust(temporal, formatter);119this.formatter = formatter;120}121122private static TemporalAccessor adjust(final TemporalAccessor temporal, DateTimeFormatter formatter) {123// normal case first (early return is an optimization)124Chronology overrideChrono = formatter.getChronology();125ZoneId overrideZone = formatter.getZone();126if (overrideChrono == null && overrideZone == null) {127return temporal;128}129130// ensure minimal change (early return is an optimization)131Chronology temporalChrono = temporal.query(TemporalQueries.chronology());132ZoneId temporalZone = temporal.query(TemporalQueries.zoneId());133if (Objects.equals(overrideChrono, temporalChrono)) {134overrideChrono = null;135}136if (Objects.equals(overrideZone, temporalZone)) {137overrideZone = null;138}139if (overrideChrono == null && overrideZone == null) {140return temporal;141}142143// make adjustment144final Chronology effectiveChrono = (overrideChrono != null ? overrideChrono : temporalChrono);145if (overrideZone != null) {146// if have zone and instant, calculation is simple, defaulting chrono if necessary147if (temporal.isSupported(INSTANT_SECONDS)) {148Chronology chrono = (effectiveChrono != null ? effectiveChrono : IsoChronology.INSTANCE);149return chrono.zonedDateTime(Instant.from(temporal), overrideZone);150}151// block changing zone on OffsetTime, and similar problem cases152if (overrideZone.normalized() instanceof ZoneOffset && temporal.isSupported(OFFSET_SECONDS) &&153temporal.get(OFFSET_SECONDS) != overrideZone.getRules().getOffset(Instant.EPOCH).getTotalSeconds()) {154throw new DateTimeException("Unable to apply override zone '" + overrideZone +155"' because the temporal object being formatted has a different offset but" +156" does not represent an instant: " + temporal);157}158}159final ZoneId effectiveZone = (overrideZone != null ? overrideZone : temporalZone);160final ChronoLocalDate effectiveDate;161if (overrideChrono != null) {162if (temporal.isSupported(EPOCH_DAY)) {163effectiveDate = effectiveChrono.date(temporal);164} else {165// check for date fields other than epoch-day, ignoring case of converting null to ISO166if (!(overrideChrono == IsoChronology.INSTANCE && temporalChrono == null)) {167for (ChronoField f : ChronoField.values()) {168if (f.isDateBased() && temporal.isSupported(f)) {169throw new DateTimeException("Unable to apply override chronology '" + overrideChrono +170"' because the temporal object being formatted contains date fields but" +171" does not represent a whole date: " + temporal);172}173}174}175effectiveDate = null;176}177} else {178effectiveDate = null;179}180181// combine available data182// this is a non-standard temporal that is almost a pure delegate183// this better handles map-like underlying temporal instances184return new TemporalAccessor() {185@Override186public boolean isSupported(TemporalField field) {187if (effectiveDate != null && field.isDateBased()) {188return effectiveDate.isSupported(field);189}190return temporal.isSupported(field);191}192@Override193public ValueRange range(TemporalField field) {194if (effectiveDate != null && field.isDateBased()) {195return effectiveDate.range(field);196}197return temporal.range(field);198}199@Override200public long getLong(TemporalField field) {201if (effectiveDate != null && field.isDateBased()) {202return effectiveDate.getLong(field);203}204return temporal.getLong(field);205}206@SuppressWarnings("unchecked")207@Override208public <R> R query(TemporalQuery<R> query) {209if (query == TemporalQueries.chronology()) {210return (R) effectiveChrono;211}212if (query == TemporalQueries.zoneId()) {213return (R) effectiveZone;214}215if (query == TemporalQueries.precision()) {216return temporal.query(query);217}218return query.queryFrom(this);219}220};221}222223//-----------------------------------------------------------------------224/**225* Gets the temporal object being output.226*227* @return the temporal object, not null228*/229TemporalAccessor getTemporal() {230return temporal;231}232233/**234* Gets the locale.235* <p>236* This locale is used to control localization in the format output except237* where localization is controlled by the DecimalStyle.238*239* @return the locale, not null240*/241Locale getLocale() {242return formatter.getLocale();243}244245/**246* Gets the DecimalStyle.247* <p>248* The DecimalStyle controls the localization of numeric output.249*250* @return the DecimalStyle, not null251*/252DecimalStyle getDecimalStyle() {253return formatter.getDecimalStyle();254}255256//-----------------------------------------------------------------------257/**258* Starts the printing of an optional segment of the input.259*/260void startOptional() {261this.optional++;262}263264/**265* Ends the printing of an optional segment of the input.266*/267void endOptional() {268this.optional--;269}270271/**272* Gets a value using a query.273*274* @param query the query to use, not null275* @return the result, null if not found and optional is true276* @throws DateTimeException if the type is not available and the section is not optional277*/278<R> R getValue(TemporalQuery<R> query) {279R result = temporal.query(query);280if (result == null && optional == 0) {281throw new DateTimeException("Unable to extract value: " + temporal.getClass());282}283return result;284}285286/**287* Gets the value of the specified field.288* <p>289* This will return the value for the specified field.290*291* @param field the field to find, not null292* @return the value, null if not found and optional is true293* @throws DateTimeException if the field is not available and the section is not optional294*/295Long getValue(TemporalField field) {296try {297return temporal.getLong(field);298} catch (DateTimeException ex) {299if (optional > 0) {300return null;301}302throw ex;303}304}305306//-----------------------------------------------------------------------307/**308* Returns a string version of the context for debugging.309*310* @return a string representation of the context, not null311*/312@Override313public String toString() {314return temporal.toString();315}316317}318319320