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.temporal.Chrono;
  71 import java.time.temporal.ChronoField;
  72 import java.time.temporal.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 print.
  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 print 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 print, 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         Chrono<?> overrideChrono = formatter.getChrono();
 123         ZoneId overrideZone = formatter.getZone();
 124         if (overrideChrono == null && overrideZone == null) {
 125             return temporal;
 126         }
 127 
 128         // ensure minimal change
 129         Chrono<?> temporalChrono = Chrono.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 like OffsetDate
 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.doRange(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.doGet(this);
 175                 }
 176                 @Override
 177                 public <R> R query(TemporalQuery<R> query) {
 178                     if (query == Queries.zoneId() || query == Queries.chrono() || query == Queries.precision()) {
 179                         return temporal.query(query);
 180                     }
 181                     return query.queryFrom(this);
 182                 }
 183             };
 184         }
 185     }
 186 
 187     //-----------------------------------------------------------------------
 188     /**
 189      * Gets the temporal object being output.
 190      *
 191      * @return the temporal object, not null
 192      */
 193     TemporalAccessor getTemporal() {
 194         return temporal;
 195     }
 196 
 197     /**
 198      * Gets the locale.
 199      * <p>
 200      * This locale is used to control localization in the print output except
 201      * where localization is controlled by the symbols.
 202      *
 203      * @return the locale, not null
 204      */
 205     Locale getLocale() {
 206         return formatter.getLocale();
 207     }
 208 
 209     /**
 210      * Gets the formatting symbols.
 211      * <p>
 212      * The symbols control the localization of numeric output.
 213      *
 214      * @return the formatting symbols, not null
 215      */
 216     DateTimeFormatSymbols getSymbols() {
 217         return formatter.getSymbols();
 218     }
 219 
 220     //-----------------------------------------------------------------------
 221     /**
 222      * Starts the printing of an optional segment of the input.
 223      */
 224     void startOptional() {
 225         this.optional++;
 226     }
 227 
 228     /**
 229      * Ends the printing of an optional segment of the input.
 230      */
 231     void endOptional() {
 232         this.optional--;
 233     }
 234 
 235     /**
 236      * Gets a value using a query.
 237      *
 238      * @param query  the query to use, not null
 239      * @return the result, null if not found and optional is true
 240      * @throws DateTimeException if the type is not available and the section is not optional
 241      */
 242     <R> R getValue(TemporalQuery<R> query) {
 243         R result = temporal.query(query);
 244         if (result == null && optional == 0) {
 245             throw new DateTimeException("Unable to extract value: " + temporal.getClass());
 246         }
 247         return result;
 248     }
 249 
 250     /**
 251      * Gets the value of the specified field.
 252      * <p>
 253      * This will return the value for the specified field.
 254      *
 255      * @param field  the field to find, not null
 256      * @return the value, null if not found and optional is true
 257      * @throws DateTimeException if the field is not available and the section is not optional
 258      */
 259     Long getValue(TemporalField field) {
 260         try {
 261             return temporal.getLong(field);
 262         } catch (DateTimeException ex) {
 263             if (optional > 0) {
 264                 return null;
 265             }
 266             throw ex;
 267         }
 268     }
 269 
 270     //-----------------------------------------------------------------------
 271     /**
 272      * Returns a string version of the context for debugging.
 273      *
 274      * @return a string representation of the context, not null
 275      */
 276     @Override
 277     public String toString() {
 278         return temporal.toString();
 279     }
 280 
 281 }