View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.lang3.time;
19  
20  import java.time.Duration;
21  import java.time.temporal.ChronoUnit;
22  import java.util.Objects;
23  import java.util.concurrent.TimeUnit;
24  
25  import org.apache.commons.lang3.ObjectUtils;
26  import org.apache.commons.lang3.Range;
27  import org.apache.commons.lang3.function.FailableBiConsumer;
28  import org.apache.commons.lang3.math.NumberUtils;
29  
30  /**
31   * Utilities for {@link Duration}.
32   *
33   * @since 3.12.0
34   */
35  public class DurationUtils {
36  
37      /**
38       * An Integer Range that accepts Longs.
39       */
40      static final Range<Long> LONG_TO_INT_RANGE = Range.between(NumberUtils.LONG_INT_MIN_VALUE,
41              NumberUtils.LONG_INT_MAX_VALUE);
42  
43      /**
44       * Accepts the function with the duration as a long milliseconds and int nanoseconds.
45       *
46       * @param <T> The function exception.
47       * @param consumer Accepting function.
48       * @param duration The duration to pick apart.
49       * @throws T See the function signature.
50       */
51      public static <T extends Throwable> void accept(final FailableBiConsumer<Long, Integer, T> consumer, final Duration duration)
52              throws T {
53          if (consumer != null && duration != null) {
54              consumer.accept(duration.toMillis(), getNanosOfMiili(duration));
55          }
56      }
57  
58      /**
59       * Gets the nanosecond part of a Duration converted to milliseconds.
60       * <p>
61       * Handy when calling an API that takes a long of milliseconds and an int of nanoseconds. For example,
62       * {@link Object#wait(long, int)} and {@link Thread#sleep(long, int)}.
63       * </p>
64       * <p>
65       * Note that is this different from {@link Duration#getNano()} because a duration are seconds and nanoseconds.
66       * </p>
67       *
68       * @param duration The duration to query.
69       * @return nanoseconds between 0 and 999,999.
70       */
71      public static int getNanosOfMiili(final Duration duration) {
72          return duration.getNano() % 1_000_000;
73      }
74  
75      /**
76       * Tests whether the given Duration is positive (&gt;0).
77       *
78       * @param duration the value to test
79       * @return whether the given Duration is positive (&gt;0).
80       */
81      public static boolean isPositive(final Duration duration) {
82          return !duration.isNegative() && !duration.isZero();
83      }
84  
85      /**
86       * Converts a {@link TimeUnit} to a {@link ChronoUnit}.
87       *
88       * @param timeUnit A non-null TimeUnit.
89       * @return The corresponding ChronoUnit.
90       */
91      static ChronoUnit toChronoUnit(final TimeUnit timeUnit) {
92          // TODO when using Java >= 9: Use TimeUnit.toChronoUnit().
93          switch (Objects.requireNonNull(timeUnit)) {
94          case NANOSECONDS:
95              return ChronoUnit.NANOS;
96          case MICROSECONDS:
97              return ChronoUnit.MICROS;
98          case MILLISECONDS:
99              return ChronoUnit.MILLIS;
100         case SECONDS:
101             return ChronoUnit.SECONDS;
102         case MINUTES:
103             return ChronoUnit.MINUTES;
104         case HOURS:
105             return ChronoUnit.HOURS;
106         case DAYS:
107             return ChronoUnit.DAYS;
108         default:
109             throw new IllegalArgumentException(timeUnit.toString());
110         }
111     }
112 
113     /**
114      * Converts an amount and TimeUnit into a Duration.
115      *
116      * @param amount   the amount of the duration, measured in terms of the unit, positive or negative
117      * @param timeUnit the unit that the duration is measured in, must have an exact duration, not null
118      * @return a Duration.
119      */
120     public static Duration toDuration(final long amount, final TimeUnit timeUnit) {
121         return Duration.of(amount, toChronoUnit(timeUnit));
122     }
123 
124     /**
125      * Converts a Duration to milliseconds bound to an int (instead of a long).
126      * <p>
127      * Handy for low-level APIs that take millisecond timeouts in ints rather than longs.
128      * </p>
129      * <ul>
130      * <li>If the duration milliseconds are greater than {@link Integer#MAX_VALUE}, then return
131      * {@link Integer#MAX_VALUE}.</li>
132      * <li>If the duration milliseconds are lesser than {@link Integer#MIN_VALUE}, then return
133      * {@link Integer#MIN_VALUE}.</li>
134      * </ul>
135      *
136      * @param duration The duration to convert, not null.
137      * @return int milliseconds.
138      */
139     public static int toMillisInt(final Duration duration) {
140         Objects.requireNonNull(duration, "duration");
141         // intValue() does not do a narrowing conversion here
142         return LONG_TO_INT_RANGE.fit(Long.valueOf(duration.toMillis())).intValue();
143     }
144 
145     /**
146      * Returns the given non-null value or {@link Duration#ZERO} if null.
147      *
148      * @param duration The duration to test.
149      * @return The given duration or {@link Duration#ZERO}.
150      */
151     public static Duration zeroIfNull(final Duration duration) {
152         return ObjectUtils.defaultIfNull(duration, Duration.ZERO);
153     }
154 
155 }