• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.Instant;
22 import java.time.temporal.ChronoUnit;
23 import java.time.temporal.Temporal;
24 import java.util.Objects;
25 import java.util.concurrent.TimeUnit;
26 
27 import org.apache.commons.lang3.LongRange;
28 import org.apache.commons.lang3.ObjectUtils;
29 import org.apache.commons.lang3.function.FailableBiConsumer;
30 import org.apache.commons.lang3.function.FailableConsumer;
31 import org.apache.commons.lang3.function.FailableRunnable;
32 import org.apache.commons.lang3.math.NumberUtils;
33 
34 /**
35  * Utilities for {@link Duration}.
36  *
37  * @since 3.12.0
38  */
39 public class DurationUtils {
40 
41     /**
42      * An Integer Range that accepts Longs.
43      */
44     static final LongRange LONG_TO_INT_RANGE = LongRange.of(NumberUtils.LONG_INT_MIN_VALUE, NumberUtils.LONG_INT_MAX_VALUE);
45 
46     /**
47      * Accepts the function with the duration as a long milliseconds and int nanoseconds.
48      *
49      * @param <T> The function exception.
50      * @param consumer Accepting function.
51      * @param duration The duration to pick apart.
52      * @throws T See the function signature.
53      */
54     @SuppressWarnings("boxing") // boxing unavoidable
accept(final FailableBiConsumer<Long, Integer, T> consumer, final Duration duration)55     public static <T extends Throwable> void accept(final FailableBiConsumer<Long, Integer, T> consumer, final Duration duration)
56             throws T {
57         if (consumer != null && duration != null) {
58             consumer.accept(duration.toMillis(), getNanosOfMilli(duration));
59         }
60     }
61 
62     /**
63      * Gets the nanosecond part of a Duration converted to milliseconds.
64      * <p>
65      * Handy when calling an API that takes a long of milliseconds and an int of nanoseconds. For example,
66      * {@link Object#wait(long, int)} and {@link Thread#sleep(long, int)}.
67      * </p>
68      * <p>
69      * Note that is this different from {@link Duration#getNano()} because a duration are seconds and nanoseconds.
70      * </p>
71      *
72      * @param duration The duration to query.
73      * @return nanoseconds between 0 and 999,999.
74      * @deprecated Use {@link #getNanosOfMilli(Duration)}.
75      */
76     @Deprecated
getNanosOfMiili(final Duration duration)77     public static int getNanosOfMiili(final Duration duration) {
78         return getNanosOfMilli(duration);
79     }
80 
81     /**
82      * Gets the nanosecond part of a Duration converted to milliseconds.
83      * <p>
84      * Handy when calling an API that takes a long of milliseconds and an int of nanoseconds. For example,
85      * {@link Object#wait(long, int)} and {@link Thread#sleep(long, int)}.
86      * </p>
87      * <p>
88      * Note that is this different from {@link Duration#getNano()} because a duration are seconds and nanoseconds.
89      * </p>
90      *
91      * @param duration The duration to query.
92      * @return nanoseconds between 0 and 999,999.
93      * @since 3.13.0
94      */
getNanosOfMilli(final Duration duration)95     public static int getNanosOfMilli(final Duration duration) {
96         return zeroIfNull(duration).getNano() % 1_000_000;
97     }
98 
99     /**
100      * Tests whether the given Duration is positive (&gt;0).
101      *
102      * @param duration the value to test
103      * @return whether the given Duration is positive (&gt;0).
104      */
isPositive(final Duration duration)105     public static boolean isPositive(final Duration duration) {
106         return !duration.isNegative() && !duration.isZero();
107     }
108 
109     /**
110      * Runs the lambda and returns the duration of its execution.
111      *
112      * @param <E> The type of exception throw by the lambda.
113      * @param consumer What to execute.
114      * @return The Duration of execution.
115      * @throws E thrown by the lambda.
116      * @since 3.13.0
117      */
of(final FailableConsumer<Instant, E> consumer)118     public static <E extends Throwable> Duration of(final FailableConsumer<Instant, E> consumer) throws E {
119         return since(now(consumer::accept));
120     }
121 
122     /**
123      * Runs the lambda and returns the duration of its execution.
124      *
125      * @param <E> The type of exception throw by the lambda.
126      * @param runnable What to execute.
127      * @return The Duration of execution.
128      * @throws E thrown by the lambda.
129      * @since 3.13.0
130      */
of(final FailableRunnable<E> runnable)131     public static <E extends Throwable> Duration of(final FailableRunnable<E> runnable) throws E {
132         return of(start -> runnable.run());
133     }
134 
now(final FailableConsumer<Instant, E> nowConsumer)135     private static <E extends Throwable> Instant now(final FailableConsumer<Instant, E> nowConsumer) throws E {
136         final Instant start = Instant.now();
137         nowConsumer.accept(start);
138         return start;
139     }
140 
141     /**
142      * Computes the Duration between a start instant and now.
143      *
144      * @param startInclusive the start instant, inclusive, not null.
145      * @return a {@link Duration}, not null.
146      * @since 3.13.0
147      */
since(final Temporal startInclusive)148     public static Duration since(final Temporal startInclusive) {
149         return Duration.between(startInclusive, Instant.now());
150     }
151 
152     /**
153      * Converts a {@link TimeUnit} to a {@link ChronoUnit}.
154      *
155      * @param timeUnit A non-null TimeUnit.
156      * @return The corresponding ChronoUnit.
157      */
toChronoUnit(final TimeUnit timeUnit)158     static ChronoUnit toChronoUnit(final TimeUnit timeUnit) {
159         // TODO when using Java >= 9: Use TimeUnit.toChronoUnit().
160         switch (Objects.requireNonNull(timeUnit)) {
161         case NANOSECONDS:
162             return ChronoUnit.NANOS;
163         case MICROSECONDS:
164             return ChronoUnit.MICROS;
165         case MILLISECONDS:
166             return ChronoUnit.MILLIS;
167         case SECONDS:
168             return ChronoUnit.SECONDS;
169         case MINUTES:
170             return ChronoUnit.MINUTES;
171         case HOURS:
172             return ChronoUnit.HOURS;
173         case DAYS:
174             return ChronoUnit.DAYS;
175         default:
176             throw new IllegalArgumentException(timeUnit.toString());
177         }
178     }
179 
180     /**
181      * Converts an amount and TimeUnit into a Duration.
182      *
183      * @param amount   the amount of the duration, measured in terms of the unit, positive or negative
184      * @param timeUnit the unit that the duration is measured in, must have an exact duration, not null
185      * @return a Duration.
186      */
toDuration(final long amount, final TimeUnit timeUnit)187     public static Duration toDuration(final long amount, final TimeUnit timeUnit) {
188         return Duration.of(amount, toChronoUnit(timeUnit));
189     }
190 
191     /**
192      * Converts a Duration to milliseconds bound to an int (instead of a long).
193      * <p>
194      * Handy for low-level APIs that take millisecond timeouts in ints rather than longs.
195      * </p>
196      * <ul>
197      * <li>If the duration milliseconds are greater than {@link Integer#MAX_VALUE}, then return
198      * {@link Integer#MAX_VALUE}.</li>
199      * <li>If the duration milliseconds are lesser than {@link Integer#MIN_VALUE}, then return
200      * {@link Integer#MIN_VALUE}.</li>
201      * </ul>
202      *
203      * @param duration The duration to convert, not null.
204      * @return int milliseconds.
205      */
toMillisInt(final Duration duration)206     public static int toMillisInt(final Duration duration) {
207         Objects.requireNonNull(duration, "duration");
208         // intValue() does not do a narrowing conversion here
209         return LONG_TO_INT_RANGE.fit(Long.valueOf(duration.toMillis())).intValue();
210     }
211 
212     /**
213      * Returns the given non-null value or {@link Duration#ZERO} if null.
214      *
215      * @param duration The duration to test.
216      * @return The given duration or {@link Duration#ZERO}.
217      */
zeroIfNull(final Duration duration)218     public static Duration zeroIfNull(final Duration duration) {
219         return ObjectUtils.defaultIfNull(duration, Duration.ZERO);
220     }
221 
222 }
223