Search in sources :

Example 31 with ChronoUnit

use of java.time.temporal.ChronoUnit in project error-prone by google.

the class CanonicalDuration method matchMethodInvocation.

@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
    Api api;
    if (JAVA_TIME_MATCHER.matches(tree, state)) {
        api = Api.JAVA;
    } else if (JODA_MATCHER.matches(tree, state)) {
        api = Api.JODA;
    } else {
        return NO_MATCH;
    }
    if (tree.getArguments().size() != 1) {
        // TODO(cushon): ofSeconds w/ nano adjustment?
        return NO_MATCH;
    }
    Tree arg = getOnlyElement(tree.getArguments());
    if (!(arg instanceof LiteralTree)) {
        // don't inline constants
        return NO_MATCH;
    }
    Number value = constValue(arg, Number.class);
    if (value == null) {
        return NO_MATCH;
    }
    if (value.intValue() == 0) {
        switch(api) {
            case JODA:
                ExpressionTree receiver = getReceiver(tree);
                SuggestedFix fix;
                if (receiver == null) {
                    // static import of the method
                    fix = SuggestedFix.builder().addImport(api.getDurationFullyQualifiedName()).replace(tree, "Duration.ZERO").build();
                } else {
                    fix = SuggestedFix.replace(state.getEndPosition(getReceiver(tree)), state.getEndPosition(tree), ".ZERO");
                }
                return buildDescription(tree).setMessage("Duration can be expressed more clearly without units, as Duration.ZERO").addFix(fix).build();
            case JAVA:
                // don't rewrite e.g. `ofMillis(0)` to `ofDays(0)`
                return NO_MATCH;
        }
        throw new AssertionError(api);
    }
    MethodSymbol sym = getSymbol(tree);
    if (!METHOD_NAME_TO_UNIT.containsKey(sym.getSimpleName().toString())) {
        return NO_MATCH;
    }
    TemporalUnit unit = METHOD_NAME_TO_UNIT.get(sym.getSimpleName().toString());
    if (Objects.equals(BLACKLIST.get(unit), value.longValue())) {
        return NO_MATCH;
    }
    Duration duration = Duration.of(value.longValue(), unit);
    // largest unit that can be used to exactly express the duration.
    for (Map.Entry<ChronoUnit, Converter<Duration, Long>> entry : CONVERTERS.entrySet()) {
        ChronoUnit nextUnit = entry.getKey();
        if (unit.equals(nextUnit)) {
            // We reached the original unit, no simplification is possible.
            break;
        }
        Converter<Duration, Long> converter = entry.getValue();
        long nextValue = converter.convert(duration);
        if (converter.reverse().convert(nextValue).equals(duration)) {
            // We reached a larger than original unit that precisely expresses the duration, rewrite to
            // use it instead.
            String name = FACTORIES.get(api, nextUnit);
            String replacement = String.format("%s(%d%s)", name, nextValue, nextValue == ((int) nextValue) ? "" : "L");
            ExpressionTree receiver = getReceiver(tree);
            if (receiver == null) {
                // static import of the method
                SuggestedFix fix = SuggestedFix.builder().addStaticImport(api.getDurationFullyQualifiedName() + "." + name).replace(tree, replacement).build();
                return describeMatch(tree, fix);
            } else {
                return describeMatch(tree, SuggestedFix.replace(state.getEndPosition(receiver), state.getEndPosition(tree), "." + replacement));
            }
        }
    }
    return NO_MATCH;
}
Also used : TemporalUnit(java.time.temporal.TemporalUnit) Duration(java.time.Duration) LiteralTree(com.sun.source.tree.LiteralTree) SuggestedFix(com.google.errorprone.fixes.SuggestedFix) MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) LiteralTree(com.sun.source.tree.LiteralTree) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) Tree(com.sun.source.tree.Tree) ExpressionTree(com.sun.source.tree.ExpressionTree) ExpressionTree(com.sun.source.tree.ExpressionTree) Converter(com.google.common.base.Converter) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) ChronoUnit(java.time.temporal.ChronoUnit)

Example 32 with ChronoUnit

use of java.time.temporal.ChronoUnit in project Aeron by real-logic.

the class ClusterEventEncoderTest method testEncodeElectionStateChange.

@Test
void testEncodeElectionStateChange() {
    final int offset = 8;
    final ChronoUnit to = ChronoUnit.MILLENNIA;
    final int memberId = 278;
    final int leaderId = -100;
    final long candidateTermId = 777L;
    final long leadershipTermId = 42L;
    final long logPosition = 128L;
    final long logLeadershipTermId = 1L;
    final long appendPosition = 998L;
    final long catchupPosition = 200L;
    final int captureLength = captureLength(electionStateChangeLength(null, to));
    final int length = encodedLength(captureLength);
    final int encodedLength = encodeElectionStateChange(buffer, offset, captureLength, length, null, to, memberId, leaderId, candidateTermId, leadershipTermId, logPosition, logLeadershipTermId, appendPosition, catchupPosition);
    assertEquals(length, encodedLength);
    int index = offset;
    assertEquals(captureLength, buffer.getInt(index, LITTLE_ENDIAN));
    index += SIZE_OF_INT;
    assertEquals(length, buffer.getInt(index, LITTLE_ENDIAN));
    index += SIZE_OF_INT;
    assertNotEquals(0, buffer.getLong(index, LITTLE_ENDIAN));
    index += SIZE_OF_LONG;
    assertEquals(memberId, buffer.getInt(index, LITTLE_ENDIAN));
    index += SIZE_OF_INT;
    assertEquals(leaderId, buffer.getInt(index, LITTLE_ENDIAN));
    index += SIZE_OF_INT;
    assertEquals(candidateTermId, buffer.getLong(index, LITTLE_ENDIAN));
    index += SIZE_OF_LONG;
    assertEquals(leadershipTermId, buffer.getLong(index, LITTLE_ENDIAN));
    index += SIZE_OF_LONG;
    assertEquals(logPosition, buffer.getLong(index, LITTLE_ENDIAN));
    index += SIZE_OF_LONG;
    assertEquals(logLeadershipTermId, buffer.getLong(index, LITTLE_ENDIAN));
    index += SIZE_OF_LONG;
    assertEquals(appendPosition, buffer.getLong(index, LITTLE_ENDIAN));
    index += SIZE_OF_LONG;
    assertEquals(catchupPosition, buffer.getLong(index, LITTLE_ENDIAN));
    index += SIZE_OF_LONG;
    assertEquals("null" + STATE_SEPARATOR + to.name(), buffer.getStringAscii(index));
}
Also used : ChronoUnit(java.time.temporal.ChronoUnit) Test(org.junit.jupiter.api.Test)

Example 33 with ChronoUnit

use of java.time.temporal.ChronoUnit in project Aeron by real-logic.

the class ClusterEventEncoderTest method testStateChangeLength.

@Test
void testStateChangeLength() {
    final ChronoUnit from = ChronoUnit.CENTURIES;
    final ChronoUnit to = ChronoUnit.HALF_DAYS;
    final String payload = from.name() + STATE_SEPARATOR + to.name();
    assertEquals(payload.length() + (SIZE_OF_INT * 2), stateChangeLength(from, to));
}
Also used : ChronoUnit(java.time.temporal.ChronoUnit) Test(org.junit.jupiter.api.Test)

Example 34 with ChronoUnit

use of java.time.temporal.ChronoUnit in project Aeron by real-logic.

the class ArchiveEventEncoderTest method testSessionStateChangeLength.

@Test
void testSessionStateChangeLength() {
    final ChronoUnit from = ChronoUnit.ERAS;
    final ChronoUnit to = ChronoUnit.MILLENNIA;
    final String payload = from.name() + STATE_SEPARATOR + to.name();
    assertEquals(payload.length() + SIZE_OF_LONG + SIZE_OF_INT, sessionStateChangeLength(from, to));
}
Also used : ChronoUnit(java.time.temporal.ChronoUnit) Test(org.junit.jupiter.api.Test)

Example 35 with ChronoUnit

use of java.time.temporal.ChronoUnit in project flink by apache.

the class TimeUtils method parseDuration.

/**
 * Parse the given string to a java {@link Duration}. The string is in format "{length
 * value}{time unit label}", e.g. "123ms", "321 s". If no time unit label is specified, it will
 * be considered as milliseconds.
 *
 * <p>Supported time unit labels are:
 *
 * <ul>
 *   <li>DAYS: "d", "day"
 *   <li>HOURS: "h", "hour"
 *   <li>MINUTES: "m", "min", "minute"
 *   <li>SECONDS: "s", "sec", "second"
 *   <li>MILLISECONDS: "ms", "milli", "millisecond"
 *   <li>MICROSECONDS: "µs", "micro", "microsecond"
 *   <li>NANOSECONDS: "ns", "nano", "nanosecond"
 * </ul>
 *
 * @param text string to parse.
 */
public static Duration parseDuration(String text) {
    checkNotNull(text);
    final String trimmed = text.trim();
    checkArgument(!trimmed.isEmpty(), "argument is an empty- or whitespace-only string");
    final int len = trimmed.length();
    int pos = 0;
    char current;
    while (pos < len && (current = trimmed.charAt(pos)) >= '0' && current <= '9') {
        pos++;
    }
    final String number = trimmed.substring(0, pos);
    final String unitLabel = trimmed.substring(pos).trim().toLowerCase(Locale.US);
    if (number.isEmpty()) {
        throw new NumberFormatException("text does not start with a number");
    }
    final long value;
    try {
        // this throws a NumberFormatException on overflow
        value = Long.parseLong(number);
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException("The value '" + number + "' cannot be re represented as 64bit number (numeric overflow).");
    }
    if (unitLabel.isEmpty()) {
        return Duration.of(value, ChronoUnit.MILLIS);
    }
    ChronoUnit unit = LABEL_TO_UNIT_MAP.get(unitLabel);
    if (unit != null) {
        return Duration.of(value, unit);
    } else {
        throw new IllegalArgumentException("Time interval unit label '" + unitLabel + "' does not match any of the recognized units: " + TimeUnit.getAllUnits());
    }
}
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