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 import static java.time.temporal.ChronoField.OFFSET_SECONDS; 67 68 import java.time.DateTimeException; 69 import java.time.Instant; 70 import java.time.ZoneId; 71 import java.time.ZoneOffset; 72 import java.time.chrono.ChronoLocalDate; 73 import java.time.chrono.Chronology; 74 import java.time.chrono.IsoChronology; 75 import java.time.temporal.ChronoField; 76 import java.time.temporal.TemporalAccessor; 77 import java.time.temporal.TemporalField; 78 import java.time.temporal.TemporalQuery; 79 import java.time.temporal.ValueRange; 80 import java.util.Locale; 81 import java.util.Objects; 82 83 /** 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 * <h3>Specification for implementors</h3> 89 * 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 creates 91 * a new instance of the class for each format and printing is single-threaded. 92 * 93 * @since 1.8 94 */ 95 final class DateTimePrintContext { 96 97 /** 98 * The temporal being output. 99 */ 100 private TemporalAccessor temporal; 101 /** 102 * The formatter, not null. 103 */ 104 private DateTimeFormatter formatter; 105 /** 106 * Whether the current formatter is optional. 107 */ 108 private int optional; 109 110 /** 111 * Creates a new instance of the context. 112 * 113 * @param temporal the temporal object being output, not null 114 * @param formatter the formatter controlling the format, not null 115 */ 116 DateTimePrintContext(TemporalAccessor temporal, DateTimeFormatter formatter) { 117 super(); 118 this.temporal = adjust(temporal, formatter); 119 this.formatter = formatter; 120 } 121 122 private static TemporalAccessor adjust(final TemporalAccessor temporal, DateTimeFormatter formatter) { 123 // normal case first (early return is an optimization) 124 Chronology overrideChrono = formatter.getChronology(); 125 ZoneId overrideZone = formatter.getZone(); 126 if (overrideChrono == null && overrideZone == null) { 127 return temporal; 128 } 129 130 // ensure minimal change (early return is an optimization) 131 Chronology temporalChrono = temporal.query(TemporalQuery.chronology()); 132 ZoneId temporalZone = temporal.query(TemporalQuery.zoneId()); 133 if (Objects.equals(overrideChrono, temporalChrono)) { 134 overrideChrono = null; 135 } 136 if (Objects.equals(overrideZone, temporalZone)) { 137 overrideZone = null; 138 } 139 if (overrideChrono == null && overrideZone == null) { 140 return temporal; 141 } 142 143 // make adjustment 144 final Chronology effectiveChrono = (overrideChrono != null ? overrideChrono : temporalChrono); 145 if (overrideZone != null) { 146 // if have zone and instant, calculation is simple, defaulting chrono if necessary 147 if (temporal.isSupported(INSTANT_SECONDS)) { 148 Chronology chrono = (effectiveChrono != null ? effectiveChrono : IsoChronology.INSTANCE); 149 return chrono.zonedDateTime(Instant.from(temporal), overrideZone); 150 } 151 // block changing zone on OffsetTime, and similar problem cases 152 if (overrideZone.normalized() instanceof ZoneOffset && temporal.isSupported(OFFSET_SECONDS) && 153 temporal.get(OFFSET_SECONDS) != overrideZone.getRules().getOffset(Instant.EPOCH).getTotalSeconds()) { 154 throw 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 } 159 final ZoneId effectiveZone = (overrideZone != null ? overrideZone : temporalZone); 160 final ChronoLocalDate<?> effectiveDate; 161 if (overrideChrono != null) { 162 if (temporal.isSupported(EPOCH_DAY)) { 163 effectiveDate = effectiveChrono.date(temporal); 164 } else { 165 // check for date fields other than epoch-day, ignoring case of converting null to ISO 166 if (!(overrideChrono == IsoChronology.INSTANCE && temporalChrono == null)) { 167 for (ChronoField f : ChronoField.values()) { 168 if (f.isDateBased() && temporal.isSupported(f)) { 169 throw 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 } 175 effectiveDate = null; 176 } 177 } else { 178 effectiveDate = null; 179 } 180 181 // combine available data 182 // this is a non-standard temporal that is almost a pure delegate 183 // this better handles map-like underlying temporal instances 184 return new TemporalAccessor() { 185 @Override 186 public boolean isSupported(TemporalField field) { 187 if (effectiveDate != null && field.isDateBased()) { 188 return effectiveDate.isSupported(field); 189 } 190 return temporal.isSupported(field); 191 } 192 @Override 193 public ValueRange range(TemporalField field) { 194 if (effectiveDate != null && field.isDateBased()) { 195 return effectiveDate.range(field); 196 } 197 return temporal.range(field); 198 } 199 @Override 200 public long getLong(TemporalField field) { 201 if (effectiveDate != null && field.isDateBased()) { 202 return effectiveDate.getLong(field); 203 } 204 return temporal.getLong(field); 205 } 206 @SuppressWarnings("unchecked") 207 @Override 208 public <R> R query(TemporalQuery<R> query) { 209 if (query == TemporalQuery.chronology()) { 210 return (R) effectiveChrono; 211 } 212 if (query == TemporalQuery.zoneId()) { 213 return (R) effectiveZone; 214 } 215 if (query == TemporalQuery.precision()) { 216 return temporal.query(query); 217 } 218 return query.queryFrom(this); 219 } 220 }; 221 } 222 223 //----------------------------------------------------------------------- 224 /** 225 * Gets the temporal object being output. 226 * 227 * @return the temporal object, not null 228 */ 229 TemporalAccessor getTemporal() { 230 return temporal; 231 } 232 233 /** 234 * Gets the locale. 235 * <p> 236 * This locale is used to control localization in the format output except 237 * where localization is controlled by the symbols. 238 * 239 * @return the locale, not null 240 */ 241 Locale getLocale() { 242 return formatter.getLocale(); 243 } 244 245 /** 246 * Gets the formatting symbols. 247 * <p> 248 * The symbols control the localization of numeric output. 249 * 250 * @return the formatting symbols, not null 251 */ 252 DateTimeFormatSymbols getSymbols() { 253 return formatter.getSymbols(); 254 } 255 256 //----------------------------------------------------------------------- 257 /** 258 * Starts the printing of an optional segment of the input. 259 */ 260 void startOptional() { 261 this.optional++; 262 } 263 264 /** 265 * Ends the printing of an optional segment of the input. 266 */ 267 void endOptional() { 268 this.optional--; 269 } 270 271 /** 272 * Gets a value using a query. 273 * 274 * @param query the query to use, not null 275 * @return the result, null if not found and optional is true 276 * @throws DateTimeException if the type is not available and the section is not optional 277 */ 278 <R> R getValue(TemporalQuery<R> query) { 279 R result = temporal.query(query); 280 if (result == null && optional == 0) { 281 throw new DateTimeException("Unable to extract value: " + temporal.getClass()); 282 } 283 return result; 284 } 285 286 /** 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 null 292 * @return the value, null if not found and optional is true 293 * @throws DateTimeException if the field is not available and the section is not optional 294 */ 295 Long getValue(TemporalField field) { 296 try { 297 return temporal.getLong(field); 298 } catch (DateTimeException ex) { 299 if (optional > 0) { 300 return null; 301 } 302 throw ex; 303 } 304 } 305 306 //----------------------------------------------------------------------- 307 /** 308 * Returns a string version of the context for debugging. 309 * 310 * @return a string representation of the context, not null 311 */ 312 @Override 313 public String toString() { 314 return temporal.toString(); 315 } 316 317 }