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) 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.temporal;
  63 
  64 import java.time.DateTimeException;
  65 import java.util.Objects;
  66 
  67 /**
  68  * Framework-level interface defining read-only access to a temporal object,
  69  * such as a date, time, offset or some combination of these.
  70  * <p>
  71  * This is the base interface type for date, time and offset objects.
  72  * It is implemented by those classes that can provide information
  73  * as {@linkplain TemporalField fields} or {@linkplain TemporalQuery queries}.
  74  * <p>
  75  * Most date and time information can be represented as a number.
  76  * These are modeled using {@code TemporalField} with the number held using
  77  * a {@code long} to handle large values. Year, month and day-of-month are
  78  * simple examples of fields, but they also include instant and offsets.
  79  * See {@link ChronoField} for the standard set of fields.
  80  * <p>
  81  * Two pieces of date/time information cannot be represented by numbers,
  82  * the {@linkplain java.time.chrono.Chronology chronology} and the
  83  * {@linkplain java.time.ZoneId time-zone}.
  84  * These can be accessed via {@linkplain #query(TemporalQuery) queries} using
  85  * the static methods defined on {@link TemporalQuery}.
  86  * <p>
  87  * A sub-interface, {@link Temporal}, extends this definition to one that also
  88  * supports adjustment and manipulation on more complete temporal objects.
  89  * <p>
  90  * This interface is a framework-level interface that should not be widely
  91  * used in application code. Instead, applications should create and pass
  92  * around instances of concrete types, such as {@code LocalDate}.
  93  * There are many reasons for this, part of which is that implementations
  94  * of this interface may be in calendar systems other than ISO.
  95  * See {@link java.time.chrono.ChronoLocalDate} for a fuller discussion of the issues.
  96  *
  97  * @implSpec
  98  * This interface places no restrictions on the mutability of implementations,
  99  * however immutability is strongly recommended.
 100  *
 101  * @since 1.8
 102  */
 103 public interface TemporalAccessor {
 104 
 105     /**
 106      * Checks if the specified field is supported.
 107      * <p>
 108      * This checks if the date-time can be queried for the specified field.
 109      * If false, then calling the {@link #range(TemporalField) range} and {@link #get(TemporalField) get}
 110      * methods will throw an exception.
 111      *
 112      * @implSpec
 113      * Implementations must check and handle all fields defined in {@link ChronoField}.
 114      * If the field is supported, then true must be returned, otherwise false must be returned.
 115      * <p>
 116      * If the field is not a {@code ChronoField}, then the result of this method
 117      * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
 118      * passing {@code this} as the argument.
 119      * <p>
 120      * Implementations must ensure that no observable state is altered when this
 121      * read-only method is invoked.
 122      *
 123      * @param field  the field to check, null returns false
 124      * @return true if this date-time can be queried for the field, false if not
 125      */
 126     boolean isSupported(TemporalField field);
 127 
 128     /**
 129      * Gets the range of valid values for the specified field.
 130      * <p>
 131      * All fields can be expressed as a {@code long} integer.
 132      * This method returns an object that describes the valid range for that value.
 133      * The value of this temporal object is used to enhance the accuracy of the returned range.
 134      * If the date-time cannot return the range, because the field is unsupported or for
 135      * some other reason, an exception will be thrown.
 136      * <p>
 137      * Note that the result only describes the minimum and maximum valid values
 138      * and it is important not to read too much into them. For example, there
 139      * could be values within the range that are invalid for the field.
 140      *
 141      * @implSpec
 142      * Implementations must check and handle all fields defined in {@link ChronoField}.
 143      * If the field is supported, then the range of the field must be returned.
 144      * If unsupported, then an {@code UnsupportedTemporalTypeException} must be thrown.
 145      * <p>
 146      * If the field is not a {@code ChronoField}, then the result of this method
 147      * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
 148      * passing {@code this} as the argument.
 149      * <p>
 150      * Implementations must ensure that no observable state is altered when this
 151      * read-only method is invoked.
 152      * <p>
 153      * The default implementation must behave equivalent to this code:
 154      * <pre>
 155      *  if (field instanceof ChronoField) {
 156      *    if (isSupported(field)) {
 157      *      return field.range();
 158      *    }
 159      *    throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
 160      *  }
 161      *  return field.rangeRefinedBy(this);
 162      * </pre>
 163      *
 164      * @param field  the field to query the range for, not null
 165      * @return the range of valid values for the field, not null
 166      * @throws DateTimeException if the range for the field cannot be obtained
 167      * @throws UnsupportedTemporalTypeException if the field is not supported
 168      */
 169     default ValueRange range(TemporalField field) {
 170         if (field instanceof ChronoField) {
 171             if (isSupported(field)) {
 172                 return field.range();
 173             }
 174             throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
 175         }
 176         Objects.requireNonNull(field, "field");
 177         return field.rangeRefinedBy(this);
 178     }
 179 
 180     /**
 181      * Gets the value of the specified field as an {@code int}.
 182      * <p>
 183      * This queries the date-time for the value of the specified field.
 184      * The returned value will always be within the valid range of values for the field.
 185      * If the date-time cannot return the value, because the field is unsupported or for
 186      * some other reason, an exception will be thrown.
 187      *
 188      * @implSpec
 189      * Implementations must check and handle all fields defined in {@link ChronoField}.
 190      * If the field is supported and has an {@code int} range, then the value of
 191      * the field must be returned.
 192      * If unsupported, then an {@code UnsupportedTemporalTypeException} must be thrown.
 193      * <p>
 194      * If the field is not a {@code ChronoField}, then the result of this method
 195      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
 196      * passing {@code this} as the argument.
 197      * <p>
 198      * Implementations must ensure that no observable state is altered when this
 199      * read-only method is invoked.
 200      * <p>
 201      * The default implementation must behave equivalent to this code:
 202      * <pre>
 203      *  if (range(field).isIntValue()) {
 204      *    return range(field).checkValidIntValue(getLong(field), field);
 205      *  }
 206      *  throw new UnsupportedTemporalTypeException("Invalid field " + field + " + for get() method, use getLong() instead");
 207      * </pre>
 208      *
 209      * @param field  the field to get, not null
 210      * @return the value for the field, within the valid range of values
 211      * @throws DateTimeException if a value for the field cannot be obtained or
 212      *         the value is outside the range of valid values for the field
 213      * @throws UnsupportedTemporalTypeException if the field is not supported or
 214      *         the range of values exceeds an {@code int}
 215      * @throws ArithmeticException if numeric overflow occurs
 216      */
 217     default int get(TemporalField field) {
 218         ValueRange range = range(field);
 219         if (range.isIntValue() == false) {
 220             throw new UnsupportedTemporalTypeException("Invalid field " + field + " for get() method, use getLong() instead");
 221         }
 222         long value = getLong(field);
 223         if (range.isValidValue(value) == false) {
 224             throw new DateTimeException("Invalid value for " + field + " (valid values " + range + "): " + value);
 225         }
 226         return (int) value;
 227     }
 228 
 229     /**
 230      * Gets the value of the specified field as a {@code long}.
 231      * <p>
 232      * This queries the date-time for the value of the specified field.
 233      * The returned value may be outside the valid range of values for the field.
 234      * If the date-time cannot return the value, because the field is unsupported or for
 235      * some other reason, an exception will be thrown.
 236      *
 237      * @implSpec
 238      * Implementations must check and handle all fields defined in {@link ChronoField}.
 239      * If the field is supported, then the value of the field must be returned.
 240      * If unsupported, then an {@code UnsupportedTemporalTypeException} must be thrown.
 241      * <p>
 242      * If the field is not a {@code ChronoField}, then the result of this method
 243      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
 244      * passing {@code this} as the argument.
 245      * <p>
 246      * Implementations must ensure that no observable state is altered when this
 247      * read-only method is invoked.
 248      *
 249      * @param field  the field to get, not null
 250      * @return the value for the field
 251      * @throws DateTimeException if a value for the field cannot be obtained
 252      * @throws UnsupportedTemporalTypeException if the field is not supported
 253      * @throws ArithmeticException if numeric overflow occurs
 254      */
 255     long getLong(TemporalField field);
 256 
 257     /**
 258      * Queries this date-time.
 259      * <p>
 260      * This queries this date-time using the specified query strategy object.
 261      * <p>
 262      * Queries are a key tool for extracting information from date-times.
 263      * They exists to externalize the process of querying, permitting different
 264      * approaches, as per the strategy design pattern.
 265      * Examples might be a query that checks if the date is the day before February 29th
 266      * in a leap year, or calculates the number of days to your next birthday.
 267      * <p>
 268      * The most common query implementations are method references, such as
 269      * {@code LocalDate::from} and {@code ZoneId::from}.
 270      * Additional implementations are provided as static methods on {@link TemporalQuery}.
 271      *
 272      * @implSpec
 273      * The default implementation must behave equivalent to this code:
 274      * <pre>
 275      *  if (query == TemporalQueries.zoneId() ||
 276      *        query == TemporalQueries.chronology() || query == TemporalQueries.precision()) {
 277      *    return null;
 278      *  }
 279      *  return query.queryFrom(this);
 280      * </pre>
 281      * Future versions are permitted to add further queries to the if statement.
 282      * <p>
 283      * All classes implementing this interface and overriding this method must call
 284      * {@code TemporalAccessor.super.query(query)}. JDK classes may avoid calling
 285      * super if they provide behavior equivalent to the default behaviour, however
 286      * non-JDK classes may not utilize this optimization and must call {@code super}.
 287      * <p>
 288      * If the implementation can supply a value for one of the queries listed in the
 289      * if statement of the default implementation, then it must do so.
 290      * For example, an application-defined {@code HourMin} class storing the hour
 291      * and minute must override this method as follows:
 292      * <pre>
 293      *  if (query == TemporalQueries.precision()) {
 294      *    return MINUTES;
 295      *  }
 296      *  return TemporalAccessor.super.query(query);
 297      * </pre>
 298      * <p>
 299      * Implementations must ensure that no observable state is altered when this
 300      * read-only method is invoked.
 301      *
 302      * @param <R> the type of the result
 303      * @param query  the query to invoke, not null
 304      * @return the query result, null may be returned (defined by the query)
 305      * @throws DateTimeException if unable to query
 306      * @throws ArithmeticException if numeric overflow occurs
 307      */
 308     default <R> R query(TemporalQuery<R> query) {
 309         if (query == TemporalQueries.zoneId()
 310                 || query == TemporalQueries.chronology()
 311                 || query == TemporalQueries.precision()) {
 312             return null;
 313         }
 314         return query.queryFrom(this);
 315     }
 316 
 317 }