Java Code Examples for java.util.concurrent.TimeUnit#ordinal()

The following examples show how to use java.util.concurrent.TimeUnit#ordinal() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SQSScheduledExecutorService.java    From amazon-sqs-java-temporary-queues-client with Apache License 2.0 6 votes vote down vote up
public ScheduledSQSFutureTask(Callable<T> callable, MessageContent messageContent, boolean withResponse, long delay, long period, TimeUnit unit) {
    super(callable, messageContent, withResponse);

    if (unit.ordinal() < TimeUnit.SECONDS.ordinal()) {
        throw new IllegalArgumentException("Delays at this precision not supported: " + unit);
    }
    this.delay = unit.toNanos(delay);
    this.period = unit.toNanos(period);

    messageContent.setMessageAttributesEntry(DELAY_NANOS_ATTRIBUTE_NAME, 
            longMessageAttributeValue(this.delay));
    messageContent.setMessageAttributesEntry(PERIOD_NANOS_ATTRIBUTE_NAME, 
            longMessageAttributeValue(this.period));

    this.time = getTime(this.delay);
}
 
Example 2
Source File: RunningStatisticsPerTime.java    From myrrix-recommender with Apache License 2.0 6 votes vote down vote up
public RunningStatisticsPerTime(TimeUnit timeUnit) {
  int timeUnitOrdinal = timeUnit.ordinal();
  Preconditions.checkArgument(timeUnitOrdinal >= TimeUnit.MINUTES.ordinal(), "Unsupported time unit: %s", timeUnit);
  TimeUnit subTimeUnit = TimeUnit.values()[timeUnitOrdinal - 1];
  int numBuckets = (int) subTimeUnit.convert(1, timeUnit);

  mean = new IntWeightedMean();
  min = Double.NaN;
  max = Double.NaN;
  bucketTimeMS = TimeUnit.MILLISECONDS.convert(1, subTimeUnit);
  subBuckets = new LinkedList<RunningStatistics>();
  for (int i = 0; i < numBuckets; i++) {
    subBuckets.add(new RunningStatistics());
  }
  frontBucketValidUntil = System.currentTimeMillis() + bucketTimeMS;
}
 
Example 3
Source File: TimeUtil.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Calculate the duration between now and the given time
 *
 * Taken mostly from http://stackoverflow.com/a/5062810/207604 . Kudos to @dblevins
 *
 * @param start starting time (in milliseconds)
 * @return time in seconds
 *
 */
public static String formatDurationTill(long start) {
    long duration = System.currentTimeMillis() - start;
    StringBuilder res = new StringBuilder();

    TimeUnit current = HOURS;

    while (duration > 0) {
        long temp = current.convert(duration, MILLISECONDS);

        if (temp > 0) {
            duration -= current.toMillis(temp);
            res.append(temp).append(" ").append(current.name().toLowerCase());
            if (temp < 2) res.deleteCharAt(res.length() - 1);
            res.append(", ");
        }
        if (current == SECONDS) {
            break;
        }
        current = TimeUnit.values()[current.ordinal() - 1];
    }
    if (res.lastIndexOf(", ") < 0) {
        return duration + " " + MILLISECONDS.name().toLowerCase();
    }
    res.deleteCharAt(res.length() - 2);
    int i = res.lastIndexOf(", ");
    if (i > 0) {
        res.deleteCharAt(i);
        res.insert(i, " and");
    }

    return res.toString();
}
 
Example 4
Source File: EnvUtil.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Calculate the duration between now and the given time
 *
 * <p> Taken mostly from http://stackoverflow.com/a/5062810/207604 . Kudos to @dblevins
 *
 * @param start starting time (in milliseconds)
 * @return time in seconds
 */
public static String formatDurationTill(long start) {
    long duration = System.currentTimeMillis() - start;
    StringBuilder res = new StringBuilder();

    TimeUnit current = HOURS;

    while (duration > 0) {
        long temp = current.convert(duration, MILLISECONDS);

        if (temp > 0) {
            duration -= current.toMillis(temp);
            res.append(temp).append(" ").append(current.name().toLowerCase());
            if (temp < 2) res.deleteCharAt(res.length() - 1);
            res.append(", ");
        }
        if (current == SECONDS) {
            break;
        }
        current = TimeUnit.values()[current.ordinal() - 1];
    }
    if (res.lastIndexOf(", ") < 0) {
        return duration + " " + MILLISECONDS.name().toLowerCase();
    }
    res.deleteCharAt(res.length() - 2);
    int i = res.lastIndexOf(", ");
    if (i > 0) {
        res.deleteCharAt(i);
        res.insert(i, " and");
    }

    return res.toString();
}
 
Example 5
Source File: DurationPanel.java    From Explvs-AIO with MIT License 5 votes vote down vote up
public double toTimeUnit(double amount, TimeUnit to) {
    if (getTimeUnit().ordinal() < to.ordinal()) {
        return amount / getTimeUnit().convert(1, to);
    } else {
        return amount * to.convert(1, getTimeUnit());
    }
}
 
Example 6
Source File: TimeInterpreter.java    From L2jOrg with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Appends an user-friendly description of the given amount of time to the specified text builder.<BR>
 * <BR>
 * Please keep in mind, that this method is primarily designed to be used with heap text builders. Therefore, if the given text builder throws an {@link IOException}, this exception will be wrapped in a {@link RuntimeException} and returned to the caller as an unchecked exception.
 *
 * @param <T>
 * @param textBuilder          a character sequence builder
 * @param timeAmount           amount of time to be written
 * @param timeUnit             unit of the given amount
 * @param minConsolidationUnit smallest unit to be included within the description
 * @param maxConsolidationUnit largest unit to be included within the description
 * @param noTimeUsedIndicator  text to be written if the amount is not positive
 * @return {@code textBuilder}
 * @throws RuntimeException if {@code textBuilder} throws an {@link IOException}
 */
@SuppressWarnings("unchecked")
private static <T extends Appendable & CharSequence> T appendConsolidated(T textBuilder, long timeAmount, TimeUnit timeUnit, TimeUnit minConsolidationUnit, TimeUnit maxConsolidationUnit, String noTimeUsedIndicator) throws RuntimeException {
    try {
        if (timeAmount < 1) {
            return (T) textBuilder.append(noTimeUsedIndicator);
        }

        final int len = textBuilder.length();
        for (int i = maxConsolidationUnit.ordinal(); i >= minConsolidationUnit.ordinal(); --i) {
            final TimeUnit activeUnit = UNIT_CACHE[i];
            final long num = activeUnit.convert(timeAmount, timeUnit);
            if (num == 0) {
                continue;
            }

            if (textBuilder.length() > len) {
                textBuilder.append(", ");
            }
            textBuilder.append(String.valueOf(num)).append(' ');
            final String unit = activeUnit.name().toLowerCase(Locale.ENGLISH);
            textBuilder.append(unit, 0, num == 1 ? unit.length() - 1 : unit.length());

            timeAmount -= timeUnit.convert(num, activeUnit);
        }

        if (textBuilder.length() == len) {
            return (T) textBuilder.append(noTimeUsedIndicator).append(' ').append(minConsolidationUnit.name().toLowerCase(Locale.ENGLISH));
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return textBuilder;
}
 
Example 7
Source File: DurationPanel.java    From Explvs-AIO with MIT License 5 votes vote down vote up
public double toTimeUnit(double amount, TimeUnit to) {
    if (getTimeUnit().ordinal() < to.ordinal()) {
        return amount / getTimeUnit().convert(1, to);
    } else {
        return amount * to.convert(1, getTimeUnit());
    }
}
 
Example 8
Source File: FormatUtils.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the numerical multiplier to convert a value from {@code originalTimeUnit} to
 * {@code newTimeUnit} (i.e. for {@code TimeUnit.DAYS -> TimeUnit.MINUTES} would return
 * 24 * 60 = 1440). If the original and new units are the same, returns 1. If the new unit
 * is larger than the original (i.e. the result would be less than 1), throws an
 * {@link IllegalArgumentException}.
 *
 * @param originalTimeUnit the source time unit
 * @param newTimeUnit      the destination time unit
 * @return the numerical multiplier between the units
 */
protected static long calculateMultiplier(TimeUnit originalTimeUnit, TimeUnit newTimeUnit) {
    if (originalTimeUnit == newTimeUnit) {
        return 1;
    } else if (originalTimeUnit.ordinal() < newTimeUnit.ordinal()) {
        throw new IllegalArgumentException("The original time unit '" + originalTimeUnit + "' must be larger than the new time unit '" + newTimeUnit + "'");
    } else {
        int originalOrd = originalTimeUnit.ordinal();
        int newOrd = newTimeUnit.ordinal();

        List<Long> unitMultipliers = TIME_UNIT_MULTIPLIERS.subList(newOrd, originalOrd);
        return unitMultipliers.stream().reduce(1L, (a, b) -> (long) a * b);
    }
}
 
Example 9
Source File: RxUtil.java    From ocelli with Apache License 2.0 5 votes vote down vote up
public static <T> Operator<T, T> rate(final String label, final long interval, final TimeUnit units) {
    final String caption = getSourceLabel(label);
    return new Operator<T, T>() {
        @Override
        public Subscriber<? super T> call(final Subscriber<? super T> child) {
            final AtomicLong counter = new AtomicLong();
            final String sUnits = (interval == 1) ? TIME_UNIT[units.ordinal()] : String.format("({} {})", interval, TIME_UNIT[units.ordinal()]);
            child.add(
                Observable.interval(interval, units)
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long t1) {
                        LOG.info("{} {} / {}", caption, counter.getAndSet(0), sUnits);
                    }
                }));
            return new Subscriber<T>(child) {
                @Override
                public void onCompleted() {
                    if (!isUnsubscribed()) 
                        child.onCompleted();
                }

                @Override
                public void onError(Throwable e) {
                    if (!isUnsubscribed()) 
                        child.onError(e);
                }

                @Override
                public void onNext(T t) {
                    counter.incrementAndGet();
                    if (!isUnsubscribed()) 
                        child.onNext(t);
                }
            };
        }
    };            
}
 
Example 10
Source File: EnvUtil.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate the duration between now and the given time
 *
 * Taken mostly from http://stackoverflow.com/a/5062810/207604 . Kudos to @dblevins
 *
 * @param start starting time (in milliseconds)
 * @return time in seconds
 *
 */
public static String formatDurationTill(long start) {
    long duration = System.currentTimeMillis() - start;
    StringBuilder res = new StringBuilder();

    TimeUnit current = HOURS;

    while (duration > 0) {
        long temp = current.convert(duration, MILLISECONDS);

        if (temp > 0) {
            duration -= current.toMillis(temp);
            res.append(temp).append(" ").append(current.name().toLowerCase());
            if (temp < 2) res.deleteCharAt(res.length() - 1);
            res.append(", ");
        }
        if (current == SECONDS) {
            break;
        }
        current = TimeUnit.values()[current.ordinal() - 1];
    }
    if (res.lastIndexOf(", ") < 0) {
        return duration + " " + MILLISECONDS.name().toLowerCase();
    }
    res.deleteCharAt(res.length() - 2);
    int i = res.lastIndexOf(", ");
    if (i > 0) {
        res.deleteCharAt(i);
        res.insert(i, " and");
    }

    return res.toString();
}
 
Example 11
Source File: FormatUtils.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the numerical multiplier to convert a value from {@code originalTimeUnit} to
 * {@code newTimeUnit} (i.e. for {@code TimeUnit.DAYS -> TimeUnit.MINUTES} would return
 * 24 * 60 = 1440). If the original and new units are the same, returns 1. If the new unit
 * is larger than the original (i.e. the result would be less than 1), throws an
 * {@link IllegalArgumentException}.
 *
 * @param originalTimeUnit the source time unit
 * @param newTimeUnit      the destination time unit
 * @return the numerical multiplier between the units
 */
protected static long calculateMultiplier(TimeUnit originalTimeUnit, TimeUnit newTimeUnit) {
    if (originalTimeUnit == newTimeUnit) {
        return 1;
    } else if (originalTimeUnit.ordinal() < newTimeUnit.ordinal()) {
        throw new IllegalArgumentException("The original time unit '" + originalTimeUnit + "' must be larger than the new time unit '" + newTimeUnit + "'");
    } else {
        int originalOrd = originalTimeUnit.ordinal();
        int newOrd = newTimeUnit.ordinal();

        List<Long> unitMultipliers = TIME_UNIT_MULTIPLIERS.subList(newOrd, originalOrd);
        return unitMultipliers.stream().reduce(1L, (a, b) -> (long) a * b);
    }
}
 
Example 12
Source File: TimeDuration.java    From incubator-ratis with Apache License 2.0 4 votes vote down vote up
/** @return the next lower {@link TimeUnit}.  If the unit is already the lowest, return it. */
public static TimeUnit lowerUnit(TimeUnit unit) {
  final int ordinal = unit.ordinal();
  return ordinal == 0? unit: TimeUnit.values()[ordinal - 1];
}
 
Example 13
Source File: TimeDuration.java    From incubator-ratis with Apache License 2.0 4 votes vote down vote up
/** @return the next higher {@link TimeUnit}.  If the unit is already the highest, return it. */
public static TimeUnit higherUnit(TimeUnit unit) {
  final int ordinal = unit.ordinal();
  final TimeUnit[] timeUnits = TimeUnit.values();
  return ordinal == timeUnits.length - 1? unit: timeUnits[ordinal + 1];
}
 
Example 14
Source File: PrettyTime.java    From Time4A with Apache License 2.0 4 votes vote down vote up
private String printRelativeTime(
    Moment ref,
    Moment moment,
    Timezone tz,
    TimeUnit precision,
    CalendarUnit maxRelativeUnit,
    TemporalFormatter<Moment> formatter
) {

    PlainTimestamp start =
        PlainTimestamp.from(
            ref,
            tz.getOffset(ref));
    PlainTimestamp end =
        PlainTimestamp.from(
            moment,
            tz.getOffset(moment));

    IsoUnit[] units = (this.weekToDays ? TSP_UNITS : STD_UNITS);
    Duration<IsoUnit> duration = Duration.in(tz, units).between(start, end);

    if (duration.isEmpty()) {
        return this.getEmptyRelativeString(precision);
    }

    TimeSpan.Item<IsoUnit> item = duration.getTotalLength().get(0);
    long amount = item.getAmount();
    IsoUnit unit = item.getUnit();

    if (unit instanceof ClockUnit) {
        if (5 - ((ClockUnit) unit).ordinal() < precision.ordinal()) {
            return this.getEmptyRelativeString(precision);
        }
    } else if (
        (maxRelativeUnit != null)
        && (Double.compare(unit.getLength(), maxRelativeUnit.getLength()) > 0)
    ) {
        return formatter.format(moment);
    } else if (unit.equals(CalendarUnit.DAYS)) {
        String replacement = this.getRelativeReplacement(end.toDate(), duration.isNegative(), amount);

        if (!replacement.isEmpty()) {
            return replacement;
        }
    }

    String pattern;

    if (duration.isNegative()) {
        if (unit.isCalendrical()) {
            pattern = this.getPastPattern(amount, (CalendarUnit) unit);
        } else {
            pattern = this.getPastPattern(amount, (ClockUnit) unit);
        }
    } else {
        if (unit.isCalendrical()) {
            pattern = this.getFuturePattern(amount, (CalendarUnit) unit);
        } else {
            pattern = this.getFuturePattern(amount, (ClockUnit) unit);
        }
    }

    return this.format(pattern, amount);

}
 
Example 15
Source File: FormatUtils.java    From nifi-registry with Apache License 2.0 3 votes vote down vote up
/**
 * Returns the next smallest {@link TimeUnit} (i.e. {@code TimeUnit.DAYS -> TimeUnit.HOURS}).
 * If the parameter is {@code null} or {@code TimeUnit.NANOSECONDS}, an
 * {@link IllegalArgumentException} is thrown because there is no valid smaller TimeUnit.
 *
 * @param originalUnit the TimeUnit
 * @return the next smaller TimeUnit
 */
protected static TimeUnit getSmallerTimeUnit(TimeUnit originalUnit) {
    if (originalUnit == null || TimeUnit.NANOSECONDS == originalUnit) {
        throw new IllegalArgumentException("Cannot determine a smaller time unit than '" + originalUnit + "'");
    } else {
        return TimeUnit.values()[originalUnit.ordinal() - 1];
    }
}
 
Example 16
Source File: FormatUtils.java    From nifi with Apache License 2.0 3 votes vote down vote up
/**
 * Returns the next smallest {@link TimeUnit} (i.e. {@code TimeUnit.DAYS -> TimeUnit.HOURS}).
 * If the parameter is {@code null} or {@code TimeUnit.NANOSECONDS}, an
 * {@link IllegalArgumentException} is thrown because there is no valid smaller TimeUnit.
 *
 * @param originalUnit the TimeUnit
 * @return the next smaller TimeUnit
 */
protected static TimeUnit getSmallerTimeUnit(TimeUnit originalUnit) {
    if (originalUnit == null || TimeUnit.NANOSECONDS == originalUnit) {
        throw new IllegalArgumentException("Cannot determine a smaller time unit than '" + originalUnit + "'");
    } else {
        return TimeUnit.values()[originalUnit.ordinal() - 1];
    }
}