Search in sources :

Example 1 with ChronoUnit

use of java.time.temporal.ChronoUnit in project titan by thinkaurelius.

the class CommonConfigTest method testDateParsing.

@Test
public void testDateParsing() {
    BaseConfiguration base = new BaseConfiguration();
    CommonsConfiguration config = new CommonsConfiguration(base);
    for (ChronoUnit unit : Arrays.asList(ChronoUnit.NANOS, ChronoUnit.MICROS, ChronoUnit.MILLIS, ChronoUnit.SECONDS, ChronoUnit.MINUTES, ChronoUnit.HOURS, ChronoUnit.DAYS)) {
        base.setProperty("test", "100 " + unit.toString());
        Duration d = config.get("test", Duration.class);
        assertEquals(TimeUnit.NANOSECONDS.convert(100, Temporals.timeUnit(unit)), d.toNanos());
    }
    Map<ChronoUnit, String> mapping = ImmutableMap.of(ChronoUnit.MICROS, "us", ChronoUnit.DAYS, "d");
    for (Map.Entry<ChronoUnit, String> entry : mapping.entrySet()) {
        base.setProperty("test", "100 " + entry.getValue());
        Duration d = config.get("test", Duration.class);
        assertEquals(TimeUnit.NANOSECONDS.convert(100, Temporals.timeUnit(entry.getKey())), d.toNanos());
    }
}
Also used : BaseConfiguration(org.apache.commons.configuration.BaseConfiguration) CommonsConfiguration(com.thinkaurelius.titan.diskstorage.configuration.backend.CommonsConfiguration) Duration(java.time.Duration) ImmutableMap(com.google.common.collect.ImmutableMap) Map(java.util.Map) ChronoUnit(java.time.temporal.ChronoUnit) Test(org.junit.Test)

Example 2 with ChronoUnit

use of java.time.temporal.ChronoUnit in project jdk8u_jdk by JetBrains.

the class LocalDateTime method until.

/**
     * Calculates the amount of time until another date-time in terms of the specified unit.
     * <p>
     * This calculates the amount of time between two {@code LocalDateTime}
     * objects in terms of a single {@code TemporalUnit}.
     * The start and end points are {@code this} and the specified date-time.
     * The result will be negative if the end is before the start.
     * The {@code Temporal} passed to this method is converted to a
     * {@code LocalDateTime} using {@link #from(TemporalAccessor)}.
     * For example, the amount in days between two date-times can be calculated
     * using {@code startDateTime.until(endDateTime, DAYS)}.
     * <p>
     * The calculation returns a whole number, representing the number of
     * complete units between the two date-times.
     * For example, the amount in months between 2012-06-15T00:00 and 2012-08-14T23:59
     * will only be one month as it is one minute short of two months.
     * <p>
     * There are two equivalent ways of using this method.
     * The first is to invoke this method.
     * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:
     * <pre>
     *   // these two lines are equivalent
     *   amount = start.until(end, MONTHS);
     *   amount = MONTHS.between(start, end);
     * </pre>
     * The choice should be made based on which makes the code more readable.
     * <p>
     * The calculation is implemented in this method for {@link ChronoUnit}.
     * The units {@code NANOS}, {@code MICROS}, {@code MILLIS}, {@code SECONDS},
     * {@code MINUTES}, {@code HOURS} and {@code HALF_DAYS}, {@code DAYS},
     * {@code WEEKS}, {@code MONTHS}, {@code YEARS}, {@code DECADES},
     * {@code CENTURIES}, {@code MILLENNIA} and {@code ERAS} are supported.
     * Other {@code ChronoUnit} values will throw an exception.
     * <p>
     * If the unit is not a {@code ChronoUnit}, then the result of this method
     * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}
     * passing {@code this} as the first argument and the converted input temporal
     * as the second argument.
     * <p>
     * This instance is immutable and unaffected by this method call.
     *
     * @param endExclusive  the end date, exclusive, which is converted to a {@code LocalDateTime}, not null
     * @param unit  the unit to measure the amount in, not null
     * @return the amount of time between this date-time and the end date-time
     * @throws DateTimeException if the amount cannot be calculated, or the end
     *  temporal cannot be converted to a {@code LocalDateTime}
     * @throws UnsupportedTemporalTypeException if the unit is not supported
     * @throws ArithmeticException if numeric overflow occurs
     */
@Override
public long until(Temporal endExclusive, TemporalUnit unit) {
    LocalDateTime end = LocalDateTime.from(endExclusive);
    if (unit instanceof ChronoUnit) {
        if (unit.isTimeBased()) {
            long amount = date.daysUntil(end.date);
            if (amount == 0) {
                return time.until(end.time, unit);
            }
            long timePart = end.time.toNanoOfDay() - time.toNanoOfDay();
            if (amount > 0) {
                // safe
                amount--;
                // safe
                timePart += NANOS_PER_DAY;
            } else {
                // safe
                amount++;
                // safe
                timePart -= NANOS_PER_DAY;
            }
            switch((ChronoUnit) unit) {
                case NANOS:
                    amount = Math.multiplyExact(amount, NANOS_PER_DAY);
                    break;
                case MICROS:
                    amount = Math.multiplyExact(amount, MICROS_PER_DAY);
                    timePart = timePart / 1000;
                    break;
                case MILLIS:
                    amount = Math.multiplyExact(amount, MILLIS_PER_DAY);
                    timePart = timePart / 1_000_000;
                    break;
                case SECONDS:
                    amount = Math.multiplyExact(amount, SECONDS_PER_DAY);
                    timePart = timePart / NANOS_PER_SECOND;
                    break;
                case MINUTES:
                    amount = Math.multiplyExact(amount, MINUTES_PER_DAY);
                    timePart = timePart / NANOS_PER_MINUTE;
                    break;
                case HOURS:
                    amount = Math.multiplyExact(amount, HOURS_PER_DAY);
                    timePart = timePart / NANOS_PER_HOUR;
                    break;
                case HALF_DAYS:
                    amount = Math.multiplyExact(amount, 2);
                    timePart = timePart / (NANOS_PER_HOUR * 12);
                    break;
            }
            return Math.addExact(amount, timePart);
        }
        LocalDate endDate = end.date;
        if (endDate.isAfter(date) && end.time.isBefore(time)) {
            endDate = endDate.minusDays(1);
        } else if (endDate.isBefore(date) && end.time.isAfter(time)) {
            endDate = endDate.plusDays(1);
        }
        return date.until(endDate, unit);
    }
    return unit.between(this, end);
}
Also used : ChronoLocalDateTime(java.time.chrono.ChronoLocalDateTime) ChronoUnit(java.time.temporal.ChronoUnit)

Example 3 with ChronoUnit

use of java.time.temporal.ChronoUnit in project dhis2-core by dhis2.

the class DateUtils method getDuration.

/**
     * Parses the given string into a {@link java.time.Duration} object. The
     * string syntax is [amount][unit]. The supported units are:
     * <p>
     * <ul>
     * <li>"d": Days</li>
     * <li>"h": Hours</li>
     * <li>"m": Minutes</li>
     * <li>"s": Seconds</li>
     * </ul>
     *
     * @param duration the duration string, an example describing 12 days is "12d".
     * @return a Duration object, or null if the duration string is invalid.
     */
public static Duration getDuration(String duration) {
    Matcher matcher = DURATION_PATTERN.matcher(duration);
    if (!matcher.find()) {
        return null;
    }
    long amount = Long.valueOf(matcher.group(1));
    String unit = matcher.group(2);
    ChronoUnit chronoUnit = TEMPORAL_MAP.get(unit);
    if (chronoUnit == null) {
        return null;
    }
    return Duration.of(amount, chronoUnit);
}
Also used : Matcher(java.util.regex.Matcher) ChronoUnit(java.time.temporal.ChronoUnit)

Example 4 with ChronoUnit

use of java.time.temporal.ChronoUnit in project Payara by payara.

the class RetryInterceptor method retry.

/**
 * Proceeds the given invocation context with Retry semantics.
 * @param invocationContext The invocation context to proceed
 * @return The proceeded invocation context
 * @throws Exception If the invocation throws an exception that shouldn't be retried, or if all retry attempts are
 * expended
 */
private Object retry(InvocationContext invocationContext) throws Exception {
    Object proceededInvocationContext = null;
    Retry retry = FaultToleranceCdiUtils.getAnnotation(beanManager, Retry.class, invocationContext);
    FaultToleranceService faultToleranceService = Globals.getDefaultBaseServiceLocator().getService(FaultToleranceService.class);
    InvocationManager invocationManager = Globals.getDefaultBaseServiceLocator().getService(InvocationManager.class);
    try {
        proceededInvocationContext = invocationContext.proceed();
    } catch (Exception ex) {
        Config config = null;
        try {
            config = ConfigProvider.getConfig();
        } catch (IllegalArgumentException iae) {
            logger.log(Level.INFO, "No config could be found", ex);
        }
        Class<? extends Throwable>[] retryOn = retry.retryOn();
        try {
            String retryOnString = ((String) FaultToleranceCdiUtils.getOverrideValue(config, Retry.class, "retryOn", invocationContext, String.class).get());
            List<Class> classList = new ArrayList<>();
            // Remove any curly or square brackets from the string, as well as any spaces and ".class"es
            for (String className : retryOnString.replaceAll("[\\{\\[ \\]\\}]", "").replaceAll("\\.class", "").split(",")) {
                classList.add(Class.forName(className));
            }
            retryOn = classList.toArray(retryOn);
        } catch (NoSuchElementException nsee) {
            logger.log(Level.FINER, "Could not find element in config", nsee);
        } catch (ClassNotFoundException cnfe) {
            logger.log(Level.INFO, "Could not find class from retryOn config, defaulting to annotation. " + "Make sure you give the full canonical class name.", cnfe);
        }
        Class<? extends Throwable>[] abortOn = retry.abortOn();
        try {
            String abortOnString = (String) FaultToleranceCdiUtils.getOverrideValue(config, Retry.class, "abortOn", invocationContext, String.class).get();
            List<Class> classList = new ArrayList<>();
            // Remove any curly or square brackets from the string, as well as any spaces and ".class"es
            for (String className : abortOnString.replaceAll("[\\{\\[ \\]\\}]", "").replaceAll("\\.class", "").split(",")) {
                classList.add(Class.forName(className));
            }
            abortOn = classList.toArray(abortOn);
        } catch (NoSuchElementException nsee) {
            logger.log(Level.FINER, "Could not find element in config", nsee);
        } catch (ClassNotFoundException cnfe) {
            logger.log(Level.INFO, "Could not find class from abortOn config, defaulting to annotation. " + "Make sure you give the full canonical class name.", cnfe);
        }
        if (!shouldRetry(retryOn, abortOn, ex)) {
            logger.log(Level.FINE, "Exception is contained in retryOn or abortOn, not retrying.", ex);
            throw ex;
        }
        int maxRetries = (Integer) FaultToleranceCdiUtils.getOverrideValue(config, Retry.class, "maxRetries", invocationContext, Integer.class).orElse(retry.maxRetries());
        long delay = (Long) FaultToleranceCdiUtils.getOverrideValue(config, Retry.class, "delay", invocationContext, Long.class).orElse(retry.delay());
        ChronoUnit delayUnit = (ChronoUnit) FaultToleranceCdiUtils.getOverrideValue(config, Retry.class, "delayUnit", invocationContext, ChronoUnit.class).orElse(retry.delayUnit());
        long maxDuration = (Long) FaultToleranceCdiUtils.getOverrideValue(config, Retry.class, "maxDuration", invocationContext, Long.class).orElse(retry.maxDuration());
        ChronoUnit durationUnit = (ChronoUnit) FaultToleranceCdiUtils.getOverrideValue(config, Retry.class, "durationUnit", invocationContext, ChronoUnit.class).orElse(retry.durationUnit());
        long jitter = (Long) FaultToleranceCdiUtils.getOverrideValue(config, Retry.class, "jitter", invocationContext, Long.class).orElse(retry.jitter());
        ChronoUnit jitterDelayUnit = (ChronoUnit) FaultToleranceCdiUtils.getOverrideValue(config, Retry.class, "jitterDelayUnit", invocationContext, ChronoUnit.class).orElse(retry.jitterDelayUnit());
        long delayMillis = Duration.of(delay, delayUnit).toMillis();
        long jitterMillis = Duration.of(jitter, jitterDelayUnit).toMillis();
        long timeoutTime = System.currentTimeMillis() + Duration.of(maxDuration, durationUnit).toMillis();
        Exception retryException = ex;
        faultToleranceService.startFaultToleranceSpan(new RequestTraceSpan("retryMethod"), invocationManager, invocationContext);
        try {
            if (maxRetries == -1 && maxDuration > 0) {
                logger.log(Level.FINER, "Retrying until maxDuration is breached.");
                while (System.currentTimeMillis() < timeoutTime) {
                    try {
                        proceededInvocationContext = invocationContext.proceed();
                        break;
                    } catch (Exception caughtException) {
                        retryException = caughtException;
                        if (!shouldRetry(retryOn, abortOn, caughtException)) {
                            break;
                        }
                        if (delayMillis > 0 || jitterMillis > 0) {
                            faultToleranceService.startFaultToleranceSpan(new RequestTraceSpan("delayRetry"), invocationManager, invocationContext);
                            try {
                                Thread.sleep(delayMillis + ThreadLocalRandom.current().nextLong(0, jitterMillis));
                            } finally {
                                faultToleranceService.endFaultToleranceSpan();
                            }
                        }
                    }
                }
            } else if (maxRetries == -1 && maxDuration == 0) {
                logger.log(Level.INFO, "Retrying potentially forever!");
                while (true) {
                    try {
                        proceededInvocationContext = invocationContext.proceed();
                        break;
                    } catch (Exception caughtException) {
                        retryException = caughtException;
                        if (!shouldRetry(retryOn, abortOn, caughtException)) {
                            break;
                        }
                        if (delayMillis > 0 || jitterMillis > 0) {
                            faultToleranceService.startFaultToleranceSpan(new RequestTraceSpan("delayRetry"), invocationManager, invocationContext);
                            try {
                                Thread.sleep(delayMillis + ThreadLocalRandom.current().nextLong(0, jitterMillis));
                            } finally {
                                faultToleranceService.endFaultToleranceSpan();
                            }
                        }
                    }
                }
            } else if (maxRetries != -1 && maxDuration > 0) {
                logger.log(Level.INFO, "Retrying as long as maxDuration ({0}ms) isn''t breached, and no more than {1} times", new Object[] { Duration.of(maxDuration, durationUnit).toMillis(), maxRetries });
                while (maxRetries > 0 && System.currentTimeMillis() < timeoutTime) {
                    try {
                        proceededInvocationContext = invocationContext.proceed();
                        break;
                    } catch (Exception caughtException) {
                        retryException = caughtException;
                        if (!shouldRetry(retryOn, abortOn, caughtException)) {
                            break;
                        }
                        if (delayMillis > 0 || jitterMillis > 0) {
                            faultToleranceService.startFaultToleranceSpan(new RequestTraceSpan("delayRetry"), invocationManager, invocationContext);
                            try {
                                Thread.sleep(delayMillis + ThreadLocalRandom.current().nextLong(0, jitterMillis));
                            } finally {
                                faultToleranceService.endFaultToleranceSpan();
                            }
                        }
                        maxRetries--;
                    }
                }
            } else {
                logger.log(Level.INFO, "Retrying no more than {0} times", maxRetries);
                while (maxRetries > 0) {
                    try {
                        proceededInvocationContext = invocationContext.proceed();
                        break;
                    } catch (Exception caughtException) {
                        retryException = caughtException;
                        if (!shouldRetry(retryOn, abortOn, caughtException)) {
                            break;
                        }
                        if (delayMillis > 0 || jitterMillis > 0) {
                            faultToleranceService.startFaultToleranceSpan(new RequestTraceSpan("delayRetry"), invocationManager, invocationContext);
                            try {
                                Thread.sleep(delayMillis + ThreadLocalRandom.current().nextLong(0, jitterMillis));
                            } finally {
                                faultToleranceService.endFaultToleranceSpan();
                            }
                        }
                        maxRetries--;
                    }
                }
            }
        } finally {
            faultToleranceService.endFaultToleranceSpan();
        }
        if (proceededInvocationContext == null) {
            throw retryException;
        }
    }
    return proceededInvocationContext;
}
Also used : Config(org.eclipse.microprofile.config.Config) InvocationManager(org.glassfish.api.invocation.InvocationManager) RequestTraceSpan(fish.payara.notification.requesttracing.RequestTraceSpan) FaultToleranceService(fish.payara.microprofile.faulttolerance.FaultToleranceService) NoSuchElementException(java.util.NoSuchElementException) ArrayList(java.util.ArrayList) List(java.util.List) Retry(org.eclipse.microprofile.faulttolerance.Retry) NoSuchElementException(java.util.NoSuchElementException) ChronoUnit(java.time.temporal.ChronoUnit)

Example 5 with ChronoUnit

use of java.time.temporal.ChronoUnit in project Payara by payara.

the class TimeoutInterceptor method timeout.

/**
 * Proceeds the given invocation context with Timeout semantics.
 * @param invocationContext The invocation context to proceed.
 * @return The result of the invocation context.
 * @throws Exception If the invocation context execution throws an exception
 */
private Object timeout(InvocationContext invocationContext) throws Exception {
    Object proceededInvocationContext = null;
    Timeout timeout = FaultToleranceCdiUtils.getAnnotation(beanManager, Timeout.class, invocationContext);
    Config config = null;
    try {
        config = ConfigProvider.getConfig();
    } catch (IllegalArgumentException ex) {
        logger.log(Level.INFO, "No config could be found", ex);
    }
    long value = (Long) FaultToleranceCdiUtils.getOverrideValue(config, Timeout.class, "value", invocationContext, Long.class).orElse(timeout.value());
    ChronoUnit unit = (ChronoUnit) FaultToleranceCdiUtils.getOverrideValue(config, Timeout.class, "unit", invocationContext, ChronoUnit.class).orElse(timeout.unit());
    Future timeoutFuture = null;
    ThreadLocal<Boolean> timedOut = new ThreadLocal<>();
    timedOut.set(false);
    long timeoutMillis = Duration.of(value, unit).toMillis();
    long timeoutTime = System.currentTimeMillis() + timeoutMillis;
    try {
        timeoutFuture = startTimeout(timeoutMillis, timedOut);
        proceededInvocationContext = invocationContext.proceed();
        stopTimeout(timeoutFuture);
        if (System.currentTimeMillis() > timeoutTime || timedOut.get()) {
            logger.log(Level.FINE, "Execution timed out");
            throw new TimeoutException();
        }
    } catch (Exception ex) {
        stopTimeout(timeoutFuture);
        throw ex;
    }
    return proceededInvocationContext;
}
Also used : Timeout(org.eclipse.microprofile.faulttolerance.Timeout) Config(org.eclipse.microprofile.config.Config) NamingException(javax.naming.NamingException) TimeoutException(org.eclipse.microprofile.faulttolerance.exceptions.TimeoutException) Future(java.util.concurrent.Future) ChronoUnit(java.time.temporal.ChronoUnit) TimeoutException(org.eclipse.microprofile.faulttolerance.exceptions.TimeoutException)

Aggregations

ChronoUnit (java.time.temporal.ChronoUnit)34 Test (org.junit.Test)6 Test (org.junit.jupiter.api.Test)6 LocalDateTime (java.time.LocalDateTime)5 Duration (java.time.Duration)4 Map (java.util.Map)4 Matcher (java.util.regex.Matcher)4 ImmutableMap (com.google.common.collect.ImmutableMap)3 ChronoLocalDateTime (java.time.chrono.ChronoLocalDateTime)3 ArrayList (java.util.ArrayList)3 Given (cucumber.api.java.en.Given)2 CommandSubscriber (de.nikos410.discordBot.util.modular.annotations.CommandSubscriber)2 FaultToleranceService (fish.payara.microprofile.faulttolerance.FaultToleranceService)2 Instant (java.time.Instant)2 ZonedDateTime (java.time.ZonedDateTime)2 DateTimeFormatter (java.time.format.DateTimeFormatter)2 ScheduledFuture (java.util.concurrent.ScheduledFuture)2 Pattern (java.util.regex.Pattern)2 Config (org.eclipse.microprofile.config.Config)2 Converter (com.google.common.base.Converter)1