View Javadoc
1   package pk.lucidxpo.ynami.utils;
2   
3   import org.joda.time.DateTime;
4   import org.joda.time.LocalDateTime;
5   
6   import java.util.Date;
7   import java.util.List;
8   import java.util.Random;
9   
10  import static com.google.common.collect.Lists.newArrayList;
11  import static java.util.Arrays.asList;
12  import static org.joda.time.DateTimeZone.UTC;
13  
14  public final class Randomly {
15      public static final Random RANDOM = new Random(new Date().getTime());
16  
17      private Randomly() {
18      }
19  
20      @SafeVarargs
21      public static <T> T chooseOneOf(final T... values) {
22          return chooseOneOf(asList(values));
23      }
24  
25      public static <T> T chooseOneOf(final Iterable<T> values) {
26          return chooseOneOf(list(values));
27      }
28  
29      private static <T> T chooseOneOf(final List<T> list) {
30          if (list.isEmpty()) {
31              throw new IllegalArgumentException("List was empty");
32          }
33          return list.get((int) chooseNumberBetween(0L, list.size() - 1L));
34      }
35  
36      private static <T> List<T> list(final Iterable<T> values) {
37          return newArrayList(values);
38      }
39  
40      public static long chooseNumberBetween(final long from, final long to) {
41          final long range = to - from + 1;
42          final long fraction = (long) (range * RANDOM.nextDouble());
43          return from + fraction;
44      }
45  
46      public static LocalDateTime chooseLocalDateBetween(final LocalDateTime from, final LocalDateTime to) {
47          return chooseDateBetween(
48                  from.toDateTime(UTC),
49                  to.toDateTime(UTC)).
50                  toLocalDateTime();
51      }
52  
53      public static DateTime chooseDateBetween(final DateTime from, final DateTime to) {
54          final long difference = to.getMillis() - from.getMillis();
55          return new DateTime(from.getMillis() + chooseNumberBetween(0, difference));
56      }
57  }