Path: blob/master/src/java.base/share/classes/java/time/format/DateTimePrintContext.java
41159 views
/*1* Copyright (c) 2012, 2016, 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 = Objects.requireNonNullElse(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}220221@Override222public String toString() {223return temporal +224(effectiveChrono != null ? " with chronology " + effectiveChrono : "") +225(effectiveZone != null ? " with zone " + effectiveZone : "");226}227};228}229230//-----------------------------------------------------------------------231/**232* Gets the temporal object being output.233*234* @return the temporal object, not null235*/236TemporalAccessor getTemporal() {237return temporal;238}239240/**241* Gets the locale.242* <p>243* This locale is used to control localization in the format output except244* where localization is controlled by the DecimalStyle.245*246* @return the locale, not null247*/248Locale getLocale() {249return formatter.getLocale();250}251252/**253* Gets the DecimalStyle.254* <p>255* The DecimalStyle controls the localization of numeric output.256*257* @return the DecimalStyle, not null258*/259DecimalStyle getDecimalStyle() {260return formatter.getDecimalStyle();261}262263//-----------------------------------------------------------------------264/**265* Starts the printing of an optional segment of the input.266*/267void startOptional() {268this.optional++;269}270271/**272* Ends the printing of an optional segment of the input.273*/274void endOptional() {275this.optional--;276}277278/**279* Gets a value using a query.280*281* @param query the query to use, not null282* @return the result, null if not found and optional is true283* @throws DateTimeException if the type is not available and the section is not optional284*/285<R> R getValue(TemporalQuery<R> query) {286R result = temporal.query(query);287if (result == null && optional == 0) {288throw new DateTimeException("Unable to extract " +289query + " from temporal " + temporal);290}291return result;292}293294/**295* Gets the value of the specified field.296* <p>297* This will return the value for the specified field.298*299* @param field the field to find, not null300* @return the value, null if not found and optional is true301* @throws DateTimeException if the field is not available and the section is not optional302*/303Long getValue(TemporalField field) {304if (optional > 0 && !temporal.isSupported(field)) {305return null;306}307return temporal.getLong(field);308}309310//-----------------------------------------------------------------------311/**312* Returns a string version of the context for debugging.313*314* @return a string representation of the context, not null315*/316@Override317public String toString() {318return temporal.toString();319}320321}322323324