Search in sources :

Example 21 with ChronoUnit

use of java.time.temporal.ChronoUnit in project de-DiscordBot by DACH-Discord.

the class CommandUtils method parseDurationParameters.

public static DurationParameters parseDurationParameters(final String input) {
    if (input == null) {
        return null;
    }
    final Pattern pattern = Pattern.compile("(\\d+)\\s*([smhd])\\s*(.*)");
    final Matcher matcher = pattern.matcher(input);
    if (!matcher.matches()) {
        // No valid duration was specified
        return null;
    }
    final int muteDuration = Integer.parseInt(matcher.group(1));
    final ChronoUnit muteDurationUnit = parseChronoUnit(matcher.group(2));
    final String message = matcher.group(3);
    return new DurationParameters(muteDuration, muteDurationUnit, message);
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) ChronoUnit(java.time.temporal.ChronoUnit)

Example 22 with ChronoUnit

use of java.time.temporal.ChronoUnit in project hippo by NHS-digital-website.

the class CmsSteps method iHaveAPublishedPublicationWithNominalDateFallingBeforeWeeksFromNow.

@Given("^I have a published publication with nominal date falling before (-?\\d+) (days|weeks|years) from now$")
public void iHaveAPublishedPublicationWithNominalDateFallingBeforeWeeksFromNow(final int valueFromNow, final String unit) throws Throwable {
    ChronoUnit chronoUnit = ChronoUnit.valueOf(unit.toUpperCase());
    final Publication publicationWithNominalDateBeforeCutOff = TestDataFactory.createBareMinimumPublication().withNominalDate(LocalDateTime.now().plus(valueFromNow, chronoUnit).toInstant(ZoneOffset.UTC)).build();
    testDataRepo.setPublication(publicationWithNominalDateBeforeCutOff);
    createPublishedPublication(publicationWithNominalDateBeforeCutOff);
}
Also used : ChronoUnit(java.time.temporal.ChronoUnit) Given(cucumber.api.java.en.Given)

Example 23 with ChronoUnit

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

the class CircuitBreakerInterceptor method circuitBreak.

private Object circuitBreak(InvocationContext invocationContext) throws Exception {
    Object proceededInvocationContext = null;
    FaultToleranceService faultToleranceService = Globals.getDefaultBaseServiceLocator().getService(FaultToleranceService.class);
    CircuitBreaker circuitBreaker = FaultToleranceCdiUtils.getAnnotation(beanManager, CircuitBreaker.class, invocationContext);
    Config config = null;
    try {
        config = ConfigProvider.getConfig();
    } catch (IllegalArgumentException ex) {
        logger.log(Level.INFO, "No config could be found", ex);
    }
    Class<? extends Throwable>[] failOn = circuitBreaker.failOn();
    try {
        String failOnString = ((String) FaultToleranceCdiUtils.getOverrideValue(config, Retry.class, "failOn", 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 and loop
        for (String className : failOnString.replaceAll("[\\{\\[ \\]\\}]", "").replaceAll("\\.class", "").split(",")) {
            // Get a class object
            classList.add(Class.forName(className));
        }
        failOn = classList.toArray(failOn);
    } 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 failOn config, defaulting to annotation. " + "Make sure you give the full canonical class name.", cnfe);
    }
    long delay = (Long) FaultToleranceCdiUtils.getOverrideValue(config, CircuitBreaker.class, "value", invocationContext, Long.class).orElse(circuitBreaker.delay());
    ChronoUnit delayUnit = (ChronoUnit) FaultToleranceCdiUtils.getOverrideValue(config, CircuitBreaker.class, "delayUnit", invocationContext, ChronoUnit.class).orElse(circuitBreaker.delayUnit());
    int requestVolumeThreshold = (Integer) FaultToleranceCdiUtils.getOverrideValue(config, CircuitBreaker.class, "requestVolumeThreshold", invocationContext, Integer.class).orElse(circuitBreaker.requestVolumeThreshold());
    double failureRatio = (Double) FaultToleranceCdiUtils.getOverrideValue(config, CircuitBreaker.class, "failureRatio", invocationContext, Double.class).orElse(circuitBreaker.failureRatio());
    int successThreshold = (Integer) FaultToleranceCdiUtils.getOverrideValue(config, CircuitBreaker.class, "successThreshold", invocationContext, Integer.class).orElse(circuitBreaker.successThreshold());
    long delayMillis = Duration.of(delay, delayUnit).toMillis();
    InvocationManager invocationManager = Globals.getDefaultBaseServiceLocator().getService(InvocationManager.class);
    CircuitBreakerState circuitBreakerState = faultToleranceService.getCircuitBreakerState(faultToleranceService.getApplicationName(invocationManager, invocationContext), invocationContext.getMethod(), circuitBreaker);
    switch(circuitBreakerState.getCircuitState()) {
        case OPEN:
            logger.log(Level.FINER, "CircuitBreaker is Open, throwing exception");
            // If open, immediately throw an error
            throw new CircuitBreakerOpenException("CircuitBreaker for method " + invocationContext.getMethod().getName() + "is in state OPEN.");
        case CLOSED:
            // If closed, attempt to proceed the invocation context
            try {
                logger.log(Level.FINER, "Proceeding CircuitBreaker context");
                proceededInvocationContext = invocationContext.proceed();
            } catch (Exception ex) {
                logger.log(Level.FINE, "Exception executing CircuitBreaker context");
                // Check if the exception is something that should record a failure
                if (shouldFail(failOn, ex)) {
                    logger.log(Level.FINE, "Caught exception is included in CircuitBreaker failOn, " + "recording failure against CircuitBreaker");
                    // Add a failure result to the queue
                    circuitBreakerState.recordClosedResult(Boolean.FALSE);
                    // Calculate the failure threshold
                    long failureThreshold = Math.round(requestVolumeThreshold * failureRatio);
                    // If we're over the failure threshold, open the circuit
                    if (circuitBreakerState.isOverFailureThreshold(failureThreshold)) {
                        logger.log(Level.FINE, "CircuitBreaker is over failure threshold {0}, opening circuit", failureThreshold);
                        circuitBreakerState.setCircuitState(CircuitBreakerState.CircuitState.OPEN);
                        // Kick off a thread that will half-open the circuit after the specified delay
                        scheduleHalfOpen(delayMillis, circuitBreakerState);
                    }
                }
                // Finally, propagate the error upwards
                throw ex;
            }
            // If everything is bon, just add a success value
            circuitBreakerState.recordClosedResult(Boolean.TRUE);
            break;
        case HALF_OPEN:
            // If half-open, attempt to proceed the invocation context
            try {
                logger.log(Level.FINER, "Proceeding half open CircuitBreaker context");
                proceededInvocationContext = invocationContext.proceed();
            } catch (Exception ex) {
                logger.log(Level.FINE, "Exception executing CircuitBreaker context");
                // Check if the exception is something that should record a failure
                if (shouldFail(failOn, ex)) {
                    logger.log(Level.FINE, "Caught exception is included in CircuitBreaker failOn, " + "reopening half open circuit");
                    // Open the circuit again, and reset the half-open result counter
                    circuitBreakerState.setCircuitState(CircuitBreakerState.CircuitState.OPEN);
                    circuitBreakerState.resetHalfOpenSuccessfulResultCounter();
                    scheduleHalfOpen(delayMillis, circuitBreakerState);
                }
                throw ex;
            }
            // If the invocation context hasn't thrown an error, record a success
            circuitBreakerState.incrementHalfOpenSuccessfulResultCounter();
            logger.log(Level.FINER, "Number of consecutive successful circuitbreaker executions = {0}", circuitBreakerState.getHalfOpenSuccessFulResultCounter());
            // If we've hit the success threshold, close the circuit
            if (circuitBreakerState.getHalfOpenSuccessFulResultCounter() == successThreshold) {
                logger.log(Level.FINE, "Number of consecutive successful CircuitBreaker executions is above " + "threshold {0}, closing circuit", successThreshold);
                circuitBreakerState.setCircuitState(CircuitBreakerState.CircuitState.CLOSED);
                // Reset the counter for when we next need to use it
                circuitBreakerState.resetHalfOpenSuccessfulResultCounter();
                // Reset the rolling results window
                circuitBreakerState.resetResults();
            }
            break;
    }
    return proceededInvocationContext;
}
Also used : CircuitBreaker(org.eclipse.microprofile.faulttolerance.CircuitBreaker) Config(org.eclipse.microprofile.config.Config) CircuitBreakerState(fish.payara.microprofile.faulttolerance.state.CircuitBreakerState) ArrayList(java.util.ArrayList) InvocationManager(org.glassfish.api.invocation.InvocationManager) CircuitBreakerOpenException(org.eclipse.microprofile.faulttolerance.exceptions.CircuitBreakerOpenException) FaultToleranceService(fish.payara.microprofile.faulttolerance.FaultToleranceService) NamingException(javax.naming.NamingException) NoSuchElementException(java.util.NoSuchElementException) CircuitBreakerOpenException(org.eclipse.microprofile.faulttolerance.exceptions.CircuitBreakerOpenException) Retry(org.eclipse.microprofile.faulttolerance.Retry) NoSuchElementException(java.util.NoSuchElementException) ChronoUnit(java.time.temporal.ChronoUnit)

Example 24 with ChronoUnit

use of java.time.temporal.ChronoUnit in project org.csstudio.display.builder by kasemir.

the class TemporalRoundingTest method testRandomRoundingWithInstant.

@Test
public void testRandomRoundingWithInstant() {
    final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss (z, 'UTC' Z)");
    final ZoneId zone = ZoneId.systemDefault();
    final Instant start = Instant.now();
    for (ChronoUnit unit : SUPPORTED_UNITS) {
        final int amount = (int) (Math.random() * 60);
        final Instant rd = start.with(instanceRoundedToNextOrSame(unit, amount));
        System.out.println(formatter.format(ZonedDateTime.ofInstant(start, zone)) + " rounded by " + amount + " " + unit + " -> " + formatter.format(ZonedDateTime.ofInstant(rd, zone)));
    }
}
Also used : ZoneId(java.time.ZoneId) Instant(java.time.Instant) DateTimeFormatter(java.time.format.DateTimeFormatter) ChronoUnit(java.time.temporal.ChronoUnit) Test(org.junit.Test)

Example 25 with ChronoUnit

use of java.time.temporal.ChronoUnit in project data-prep by Talend.

the class DurationConverter method compile.

@Override
public void compile(ActionContext actionContext) {
    super.compile(actionContext);
    if (ActionsUtils.doesCreateNewColumn(actionContext.getParameters(), CREATE_NEW_COLUMN_DEFAULT)) {
        ActionsUtils.createNewColumn(actionContext, getAdditionalColumns(actionContext));
    }
    if (actionContext.getActionStatus() == OK) {
        ChronoUnit fromUnit = valueOf(actionContext.getParameters().get(FROM_UNIT_PARAMETER));
        ChronoUnit toUnit = valueOf(actionContext.getParameters().get(TO_UNIT_PARAMETER));
        actionContext.get(CONVERTER_HELPER, p -> new org.talend.dataquality.converters.DurationConverter(fromUnit, toUnit));
    }
}
Also used : ChronoUnit(java.time.temporal.ChronoUnit)

Aggregations

ChronoUnit (java.time.temporal.ChronoUnit)42 Test (org.junit.jupiter.api.Test)11 Test (org.junit.Test)6 LocalDateTime (java.time.LocalDateTime)5 Matcher (java.util.regex.Matcher)5 Duration (java.time.Duration)4 Map (java.util.Map)4 ImmutableMap (com.google.common.collect.ImmutableMap)3 ChronoLocalDateTime (java.time.chrono.ChronoLocalDateTime)3 ArrayList (java.util.ArrayList)3 Pattern (java.util.regex.Pattern)3 Given (cucumber.api.java.en.Given)2 CommandSubscriber (de.nikos410.discordBot.util.modular.annotations.CommandSubscriber)2 CommandSubscriber (de.nikos410.discordbot.framework.annotations.CommandSubscriber)2 CommandUtils (de.nikos410.discordbot.util.CommandUtils)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