All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.threeten.bp.Clock.scala Maven / Gradle / Ivy

/*
 * Copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 *  * Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 *  * Neither the name of JSR-310 nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.threeten.bp

import org.threeten.bp.LocalTime.NANOS_PER_MINUTE
import org.threeten.bp.LocalTime.NANOS_PER_SECOND
import java.io.Serializable
import java.util.Objects

object Clock {

  /**
   * Obtains a clock that returns the current instant using the best available system clock,
   * converting to date and time using the UTC time-zone.
   *
   * This clock, rather than {@link #systemDefaultZone()}, should be used when you need the current
   * instant without the date or time.
   *
   * This clock is based on the best available system clock. This may use {@link
   * System#currentTimeMillis()}, or a higher resolution clock if one is available.
   *
   * Conversion from instant to date or time uses the {@link ZoneOffset#UTC UTC time-zone}.
   *
   * The returned implementation is immutable, thread-safe and {@code Serializable}. It is
   * equivalent to {@code system(ZoneOffset.UTC)}.
   *
   * @return
   *   a clock that uses the best available system clock in the UTC zone, not null
   */
  def systemUTC: Clock = new Clock.SystemClock(ZoneOffset.UTC)

  /**
   * Obtains a clock that returns the current instant using the best available system clock,
   * converting to date and time using the default time-zone.
   *
   * This clock is based on the best available system clock. This may use {@link
   * System#currentTimeMillis()}, or a higher resolution clock if one is available.
   *
   * Using this method hard codes a dependency to the default time-zone into your application. It is
   * recommended to avoid this and use a specific time-zone whenever possible. The {@link
   * #systemUTC() UTC clock} should be used when you need the current instant without the date or
   * time.
   *
   * The returned implementation is immutable, thread-safe and {@code Serializable}. It is
   * equivalent to {@code system(ZoneId.systemDefault())}.
   *
   * @return
   *   a clock that uses the best available system clock in the default zone, not null
   * @see
   *   ZoneId#systemDefault()
   */
  def systemDefaultZone: Clock = new Clock.SystemClock(ZoneId.systemDefault)

  /**
   * Obtains a clock that returns the current instant using best available system clock.
   *
   * This clock is based on the best available system clock. This may use {@link
   * System#currentTimeMillis()}, or a higher resolution clock if one is available.
   *
   * Conversion from instant to date or time uses the specified time-zone.
   *
   * The returned implementation is immutable, thread-safe and {@code Serializable}.
   *
   * @param zone
   *   the time-zone to use to convert the instant to date-time, not null
   * @return
   *   a clock that uses the best available system clock in the specified zone, not null
   */
  def system(zone: ZoneId): Clock = {
    Objects.requireNonNull(zone, "zone")
    new Clock.SystemClock(zone)
  }

  /**
   * Obtains a clock that returns the current instant ticking in whole seconds using best available
   * system clock.
   *
   * This clock will always have the nano-of-second field set to zero. This ensures that the visible
   * time ticks in whole seconds. The underlying clock is the best available system clock,
   * equivalent to using {@link #system(ZoneId)}.
   *
   * Implementations may use a caching strategy for performance reasons. As such, it is possible
   * that the start of the second observed via this clock will be later than that observed directly
   * via the underlying clock.
   *
   * The returned implementation is immutable, thread-safe and {@code Serializable}. It is
   * equivalent to {@code tick(system(zone), Duration.ofSeconds(1))}.
   *
   * @param zone
   *   the time-zone to use to convert the instant to date-time, not null
   * @return
   *   a clock that ticks in whole seconds using the specified zone, not null
   */
  def tickSeconds(zone: ZoneId): Clock = new Clock.TickClock(system(zone), NANOS_PER_SECOND)

  /**
   * Obtains a clock that returns the current instant ticking in whole minutes using best available
   * system clock.
   *
   * This clock will always have the nano-of-second and second-of-minute fields set to zero. This
   * ensures that the visible time ticks in whole minutes. The underlying clock is the best
   * available system clock, equivalent to using {@link #system(ZoneId)}.
   *
   * Implementations may use a caching strategy for performance reasons. As such, it is possible
   * that the start of the minute observed via this clock will be later than that observed directly
   * via the underlying clock.
   *
   * The returned implementation is immutable, thread-safe and {@code Serializable}. It is
   * equivalent to {@code tick(system(zone), Duration.ofMinutes(1))}.
   *
   * @param zone
   *   the time-zone to use to convert the instant to date-time, not null
   * @return
   *   a clock that ticks in whole minutes using the specified zone, not null
   */
  def tickMinutes(zone: ZoneId): Clock = new Clock.TickClock(system(zone), NANOS_PER_MINUTE)

  /**
   * Obtains a clock that returns instants from the specified clock truncated to the nearest
   * occurrence of the specified duration.
   *
   * This clock will only tick as per the specified duration. Thus, if the duration is half a
   * second, the clock will return instants truncated to the half second.
   *
   * The tick duration must be positive. If it has a part smaller than a whole millisecond, then the
   * whole duration must divide into one second without leaving a remainder. All normal tick
   * durations will match these criteria, including any multiple of hours, minutes, seconds and
   * milliseconds, and sensible nanosecond durations, such as 20ns, 250,000ns and 500,000ns.
   *
   * A duration of zero or one nanosecond would have no truncation effect. Passing one of these will
   * return the underlying clock.
   *
   * Implementations may use a caching strategy for performance reasons. As such, it is possible
   * that the start of the requested duration observed via this clock will be later than that
   * observed directly via the underlying clock.
   *
   * The returned implementation is immutable, thread-safe and {@code Serializable} providing that
   * the base clock is.
   *
   * @param baseClock
   *   the base clock to base the ticking clock on, not null
   * @param tickDuration
   *   the duration of each visible tick, not negative, not null
   * @return
   *   a clock that ticks in whole units of the duration, not null
   * @throws IllegalArgumentException
   *   if the duration is negative, or has a part smaller than a whole millisecond such that the
   *   whole duration is not divisible into one second
   * @throws ArithmeticException
   *   if the duration is too large to be represented as nanos
   */
  def tick(baseClock: Clock, tickDuration: Duration): Clock = {
    Objects.requireNonNull(baseClock, "baseClock")
    Objects.requireNonNull(tickDuration, "tickDuration")
    if (tickDuration.isNegative)
      throw new IllegalArgumentException("Tick duration must not be negative")
    val tickNanos: Long = tickDuration.toNanos
    if (tickNanos % 1000000 == 0) {} else if (1000000000 % tickNanos == 0) {} else
      throw new IllegalArgumentException("Invalid tick duration")
    if (tickNanos <= 1)
      return baseClock
    new Clock.TickClock(baseClock, tickNanos)
  }

  /**
   * Obtains a clock that always returns the same instant.
   *
   * This clock simply returns the specified instant. As such, it is not a clock in the conventional
   * sense. The main use case for this is in testing, where the fixed clock ensures tests are not
   * dependent on the current clock.
   *
   * The returned implementation is immutable, thread-safe and {@code Serializable}.
   *
   * @param fixedInstant
   *   the instant to use as the clock, not null
   * @param zone
   *   the time-zone to use to convert the instant to date-time, not null
   * @return
   *   a clock that always returns the same instant, not null
   */
  def fixed(fixedInstant: Instant, zone: ZoneId): Clock = {
    Objects.requireNonNull(fixedInstant, "fixedInstant")
    Objects.requireNonNull(zone, "zone")
    new Clock.FixedClock(fixedInstant, zone)
  }

  /**
   * Obtains a clock that returns instants from the specified clock with the specified duration
   * added
   *
   * This clock wraps another clock, returning instants that are later by the specified duration. If
   * the duration is negative, the instants will be earlier than the current date and time. The main
   * use case for this is to simulate running in the future or in the past.
   *
   * A duration of zero would have no offsetting effect. Passing zero will return the underlying
   * clock.
   *
   * The returned implementation is immutable, thread-safe and {@code Serializable} providing that
   * the base clock is.
   *
   * @param baseClock
   *   the base clock to add the duration to, not null
   * @param offsetDuration
   *   the duration to add, not null
   * @return
   *   a clock based on the base clock with the duration added, not null
   */
  def offset(baseClock: Clock, offsetDuration: Duration): Clock = {
    Objects.requireNonNull(baseClock, "baseClock")
    Objects.requireNonNull(offsetDuration, "offsetDuration")
    if (offsetDuration == Duration.ZERO)
      baseClock
    else
      new Clock.OffsetClock(baseClock, offsetDuration)
  }

  /**
   * Implementation of a clock that always returns the latest time from {@link
   * System#currentTimeMillis()}.
   */
  @SerialVersionUID(6740630888130243051L)
  private[bp] final class SystemClock(val zone: ZoneId) extends Clock with Serializable {
    if (zone == null) throw new NullPointerException("'zone' can not be null")

    def getZone: ZoneId = zone

    def withZone(zone: ZoneId): Clock =
      if (zone == this.zone) this
      else new Clock.SystemClock(zone)

    override def millis: Long = System.currentTimeMillis

    def instant: Instant = Instant.ofEpochMilli(millis)

    override def equals(obj: Any): Boolean =
      obj match {
        case clock: SystemClock => zone == clock.zone
        case _                  => false
      }

    override def hashCode: Int = zone.hashCode + 1

    override def toString: String = s"SystemClock[$zone]"
  }

  /**
   * Implementation of a clock that always returns the same instant. This is typically used for
   * testing.
   */
  @SerialVersionUID(7430389292664866958L)
  private[bp] final class FixedClock(val instant: Instant, val zone: ZoneId)
      extends Clock
      with Serializable {
    if (zone == null) throw new NullPointerException("'zone' can not be null")

    def getZone: ZoneId = zone

    def withZone(zone: ZoneId): Clock =
      if (zone == this.zone) this
      else new Clock.FixedClock(instant, zone)

    override def millis: Long = instant.toEpochMilli

    override def equals(obj: Any): Boolean =
      obj match {
        case other: FixedClock => (instant == other.instant) && (zone == other.zone)
        case _                 => false
      }

    override def hashCode: Int = instant.hashCode ^ zone.hashCode

    override def toString: String = s"FixedClock[$instant,$zone]"
  }

  /**
   * Implementation of a clock that adds an offset to an underlying clock.
   */
  @SerialVersionUID(2007484719125426256L)
  private[bp] final class OffsetClock(val baseClock: Clock, val offset: Duration)
      extends Clock
      with Serializable {

    def getZone: ZoneId = baseClock.getZone

    def withZone(zone: ZoneId): Clock =
      if (zone == baseClock.getZone) this
      else new Clock.OffsetClock(baseClock.withZone(zone), offset)

    override def millis: Long = Math.addExact(baseClock.millis, offset.toMillis)

    def instant: Instant = baseClock.instant.plus(offset)

    override def equals(obj: Any): Boolean =
      obj match {
        case other: OffsetClock => (baseClock == other.baseClock) && (offset == other.offset)
        case _                  => false
      }

    override def hashCode: Int = baseClock.hashCode ^ offset.hashCode

    override def toString: String = s"OffsetClock[$baseClock,$offset]"
  }

  /**
   * Implementation of a clock that adds an offset to an underlying clock.
   */
  @SerialVersionUID(6504659149906368850L)
  private[bp] final class TickClock(val baseClock: Clock, val tickNanos: Long)
      extends Clock
      with Serializable {

    def getZone: ZoneId = baseClock.getZone

    def withZone(zone: ZoneId): Clock =
      if (zone == baseClock.getZone) this
      else new Clock.TickClock(baseClock.withZone(zone), tickNanos)

    override def millis: Long = {
      val millis: Long = baseClock.millis
      millis - Math.floorMod(millis, tickNanos / 1000000L)
    }

    def instant: Instant = {
      if ((tickNanos % 1000000) == 0) {
        val millis: Long = baseClock.millis
        return Instant.ofEpochMilli(millis - Math.floorMod(millis, tickNanos / 1000000L))
      }
      val instant: Instant = baseClock.instant
      val nanos: Long  = instant.getNano.toLong
      val adjust: Long = Math.floorMod(nanos, tickNanos)
      instant.minusNanos(adjust)
    }

    override def equals(obj: Any): Boolean =
      obj match {
        case other: TickClock => (baseClock == other.baseClock) && tickNanos == other.tickNanos
        case _                => false
      }

    override def hashCode: Int = baseClock.hashCode ^ (tickNanos ^ (tickNanos >>> 32)).toInt

    override def toString: String = s"TickClock[$baseClock,${Duration.ofNanos(tickNanos)}]"
  }

}

/**
 * A clock providing access to the current instant, date and time using a time-zone.
 *
 * Instances of this class are used to find the current instant, which can be interpreted using the
 * stored time-zone to find the current date and time. As such, a clock can be used instead of
 * {@link System#currentTimeMillis()} and {@link TimeZone#getDefault()}.
 *
 * Use of a {@code Clock} is optional. All key date-time classes also have a {@code now()} factory
 * method that uses the system clock in the default time zone. The primary purpose of this
 * abstraction is to allow alternate clocks to be plugged in as and when required. Applications use
 * an object to obtain the current time rather than a static method. This can simplify testing.
 *
 * Best practice for applications is to pass a {@code Clock} into any method that requires the
 * current instant. A dependency injection framework is one way to achieve this: 
 public class
 * MyBean { private Clock clock; // dependency inject ... public void process(LocalDate eventDate) {
 * if (eventDate.isBefore(LocalDate.now(clock)) { ... } } } 
This approach allows an alternate * clock, such as {@link #fixed(Instant, ZoneId) fixed} or {@link #offset(Clock, Duration) offset} * to be used during testing. * * The {@code system} factory methods provide clocks based on the best available system clock This * may use {@link System#currentTimeMillis()}, or a higher resolution clock if one is available. * *

Specification for implementors

This abstract class must be implemented with care to * ensure other operate correctly. All implementations that can be instantiated must be final, * immutable and thread-safe. * * The principal methods are defined to allow the throwing of an exception. In normal use, no * exceptions will be thrown, however one possible implementation would be to obtain the time from a * central time server across the network. Obviously, in this case the lookup could fail, and so the * method is permitted to throw an exception. * * The returned instants from {@code Clock} work on a time-scale that ignores leap seconds. If the * implementation wraps a source that provides leap second information, then a mechanism should be * used to "smooth" the leap second, such as UTC-SLS. * * Implementations should implement {@code Serializable} wherever possible and must document whether * or not they do support serialization. */ abstract class Clock protected () { /** * Gets the time-zone being used to create dates and times. * * A clock will typically obtain the current instant and then convert that to a date or time using * a time-zone. This method returns the time-zone used. * * @return * the time-zone being used to interpret instants, not null */ def getZone: ZoneId /** * Returns a copy of this clock with a different time-zone. * * A clock will typically obtain the current instant and then convert that to a date or time using * a time-zone. This method returns a clock with similar properties but using a different * time-zone. * * @param zone * the time-zone to change to, not null * @return * a clock based on this clock with the specified time-zone, not null */ def withZone(zone: ZoneId): Clock /** * Gets the current millisecond instant of the clock. * * This returns the millisecond-based instant, measured from 1970-01-01T00:00 UTC. This is * equivalent to the definition of {@link System#currentTimeMillis()}. * * Most applications should avoid this method and use {@link Instant} to represent an instant on * the time-line rather than a raw millisecond value. This method is provided to allow the use of * the clock in high performance use cases where the creation of an object would be unacceptable. * The default implementation currently calls {@link #instant()}. * * @return * the current millisecond instant from this clock, measured from the Java epoch of * 1970-01-01T00:00 UTC, not null * @throws DateTimeException * if the instant cannot be obtained, not thrown by most implementations */ def millis: Long = instant.toEpochMilli /** * Gets the current instant of the clock. * * This returns an instant representing the current instant as defined by the clock. * * @return * the current instant from this clock, not null * @throws DateTimeException * if the instant cannot be obtained, not thrown by most implementations */ def instant: Instant /** * Checks if this clock is equal to another clock. * * Clocks must compare equal based on their state and behavior. * * @param obj * the object to check, null returns false * @return * true if this is equal to the other clock */ override def equals(obj: Any): Boolean = super.equals(obj) /** * A hash code for this clock. * * @return * a suitable hash code */ override def hashCode: Int = super.hashCode }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy