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;
}
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));
}
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));
}
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));
}
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());
}
}
Aggregations