1 /*
   2  * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  * This file is available under and governed by the GNU General Public
  28  * License version 2 only, as published by the Free Software Foundation.
  29  * However, the following notice accompanied the original version of this
  30  * file:
  31  *
  32  * Copyright (c) 2011-2012, Stephen Colebourne & Michael Nascimento Santos
  33  *
  34  * All rights reserved.
  35  *
  36  * Redistribution and use in source and binary forms, with or without
  37  * modification, are permitted provided that the following conditions are met:
  38  *
  39  *  * Redistributions of source code must retain the above copyright notice,
  40  *    this list of conditions and the following disclaimer.
  41  *
  42  *  * Redistributions in binary form must reproduce the above copyright notice,
  43  *    this list of conditions and the following disclaimer in the documentation
  44  *    and/or other materials provided with the distribution.
  45  *
  46  *  * Neither the name of JSR-310 nor the names of its contributors
  47  *    may be used to endorse or promote products derived from this software
  48  *    without specific prior written permission.
  49  *
  50  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  51  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  52  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  53  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  54  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  55  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  56  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  57  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  58  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  59  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  60  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  61  */
  62 package java.time.format;
  63 
  64 import static java.time.temporal.ChronoField.EPOCH_DAY;
  65 import static java.time.temporal.ChronoField.INSTANT_SECONDS;
  66 
  67 import java.time.DateTimeException;
  68 import java.time.Instant;
  69 import java.time.ZoneId;
  70 import java.time.chrono.Chronology;
  71 import java.time.temporal.ChronoField;
  72 import java.time.chrono.ChronoLocalDate;
  73 import java.time.temporal.Queries;
  74 import java.time.temporal.TemporalAccessor;
  75 import java.time.temporal.TemporalField;
  76 import java.time.temporal.TemporalQuery;
  77 import java.time.temporal.ValueRange;
  78 import java.util.Locale;
  79 import java.util.Objects;
  80 
  81 /**
  82  * Context object used during date and time printing.
  83  * <p>
  84  * This class provides a single wrapper to items used in the format.
  85  *
  86  * <h3>Specification for implementors</h3>
  87  * This class is a mutable context intended for use from a single thread.
  88  * Usage of the class is thread-safe within standard printing as the framework creates
  89  * a new instance of the class for each format and printing is single-threaded.
  90  *
  91  * @since 1.8
  92  */
  93 final class DateTimePrintContext {
  94 
  95     /**
  96      * The temporal being output.
  97      */
  98     private TemporalAccessor temporal;
  99     /**
 100      * The formatter, not null.
 101      */
 102     private DateTimeFormatter formatter;
 103     /**
 104      * Whether the current formatter is optional.
 105      */
 106     private int optional;
 107 
 108     /**
 109      * Creates a new instance of the context.
 110      *
 111      * @param temporal  the temporal object being output, not null
 112      * @param formatter  the formatter controlling the format, not null
 113      */
 114     DateTimePrintContext(TemporalAccessor temporal, DateTimeFormatter formatter) {
 115         super();
 116         this.temporal = adjust(temporal, formatter);
 117         this.formatter = formatter;
 118     }
 119 
 120     private static TemporalAccessor adjust(final TemporalAccessor temporal, DateTimeFormatter formatter) {
 121         // normal case first
 122         Chronology overrideChrono = formatter.getChronology();
 123         ZoneId overrideZone = formatter.getZone();
 124         if (overrideChrono == null && overrideZone == null) {
 125             return temporal;
 126         }
 127 
 128         // ensure minimal change
 129         Chronology temporalChrono = Chronology.from(temporal);  // default to ISO, handles Instant
 130         ZoneId temporalZone = temporal.query(Queries.zone());  // zone then offset, handles OffsetDateTime
 131         if (temporal.isSupported(EPOCH_DAY) == false || Objects.equals(overrideChrono, temporalChrono)) {
 132             overrideChrono = null;
 133         }
 134         if (temporal.isSupported(INSTANT_SECONDS) == false || Objects.equals(overrideZone, temporalZone)) {
 135             overrideZone = null;
 136         }
 137         if (overrideChrono == null && overrideZone == null) {
 138             return temporal;
 139         }
 140 
 141         // make adjustment
 142         if (overrideChrono != null && overrideZone != null) {
 143             return overrideChrono.zonedDateTime(Instant.from(temporal), overrideZone);
 144         } else if (overrideZone != null) {
 145             return temporalChrono.zonedDateTime(Instant.from(temporal), overrideZone);
 146         } else {  // overrideChrono != null
 147             // need class here to handle non-standard cases
 148             final ChronoLocalDate date = overrideChrono.date(temporal);
 149             return new TemporalAccessor() {
 150                 @Override
 151                 public boolean isSupported(TemporalField field) {
 152                     return temporal.isSupported(field);
 153                 }
 154                 @Override
 155                 public ValueRange range(TemporalField field) {
 156                     if (field instanceof ChronoField) {
 157                         if (((ChronoField) field).isDateField()) {
 158                             return date.range(field);
 159                         } else {
 160                             return temporal.range(field);
 161                         }
 162                     }
 163                     return field.rangeRefinedBy(this);
 164                 }
 165                 @Override
 166                 public long getLong(TemporalField field) {
 167                     if (field instanceof ChronoField) {
 168                         if (((ChronoField) field).isDateField()) {
 169                             return date.getLong(field);
 170                         } else {
 171                             return temporal.getLong(field);
 172                         }
 173                     }
 174                     return field.getFrom(this);
 175                 }
 176                 @SuppressWarnings("unchecked")
 177                 @Override
 178                 public <R> R query(TemporalQuery<R> query) {
 179                     if (query == Queries.chronology()) {
 180                         return (R) date.getChronology();
 181                     }
 182                     if (query == Queries.zoneId() || query == Queries.precision()) {
 183                         return temporal.query(query);
 184                     }
 185                     return query.queryFrom(this);
 186                 }
 187             };
 188         }
 189     }
 190 
 191     //-----------------------------------------------------------------------
 192     /**
 193      * Gets the temporal object being output.
 194      *
 195      * @return the temporal object, not null
 196      */
 197     TemporalAccessor getTemporal() {
 198         return temporal;
 199     }
 200 
 201     /**
 202      * Gets the locale.
 203      * <p>
 204      * This locale is used to control localization in the format output except
 205      * where localization is controlled by the symbols.
 206      *
 207      * @return the locale, not null
 208      */
 209     Locale getLocale() {
 210         return formatter.getLocale();
 211     }
 212 
 213     /**
 214      * Gets the formatting symbols.
 215      * <p>
 216      * The symbols control the localization of numeric output.
 217      *
 218      * @return the formatting symbols, not null
 219      */
 220     DateTimeFormatSymbols getSymbols() {
 221         return formatter.getSymbols();
 222     }
 223 
 224     //-----------------------------------------------------------------------
 225     /**
 226      * Starts the printing of an optional segment of the input.
 227      */
 228     void startOptional() {
 229         this.optional++;
 230     }
 231 
 232     /**
 233      * Ends the printing of an optional segment of the input.
 234      */
 235     void endOptional() {
 236         this.optional--;
 237     }
 238 
 239     /**
 240      * Gets a value using a query.
 241      *
 242      * @param query  the query to use, not null
 243      * @return the result, null if not found and optional is true
 244      * @throws DateTimeException if the type is not available and the section is not optional
 245      */
 246     <R> R getValue(TemporalQuery<R> query) {
 247         R result = temporal.query(query);
 248         if (result == null && optional == 0) {
 249             throw new DateTimeException("Unable to extract value: " + temporal.getClass());
 250         }
 251         return result;
 252     }
 253 
 254     /**
 255      * Gets the value of the specified field.
 256      * <p>
 257      * This will return the value for the specified field.
 258      *
 259      * @param field  the field to find, not null
 260      * @return the value, null if not found and optional is true
 261      * @throws DateTimeException if the field is not available and the section is not optional
 262      */
 263     Long getValue(TemporalField field) {
 264         try {
 265             return temporal.getLong(field);
 266         } catch (DateTimeException ex) {
 267             if (optional > 0) {
 268                 return null;
 269             }
 270             throw ex;
 271         }
 272     }
 273 
 274     //-----------------------------------------------------------------------
 275     /**
 276      * Returns a string version of the context for debugging.
 277      *
 278      * @return a string representation of the context, not null
 279      */
 280     @Override
 281     public String toString() {
 282         return temporal.toString();
 283     }
 284 
 285 }