public Duration(double value, TimeUnit unit) { checkArgument(!Double.isInfinite(value), "value is infinite"); checkArgument(!Double.isNaN(value), "value is not a number"); checkArgument(value >= 0, "value is negative"); requireNonNull(unit, "unit is null"); this.value = value; this.unit = unit; }
static void checkArgument(boolean expression, String errorMessageTemplate, Object... errorMessageArgs) { if (!expression) { throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs)); } }
public long toBytes() { double bytes = getValue(Unit.BYTE); checkState(bytes <= Long.MAX_VALUE, "size is too large to be represented in bytes as a long"); return (long) bytes; }
public DataSize(double size, Unit unit) { checkArgument(!Double.isInfinite(size), "size is infinite"); checkArgument(!Double.isNaN(size), "size is not a number"); checkArgument(size >= 0, "size is negative"); requireNonNull(unit, "unit is null"); this.value = size; this.unit = unit; }
static void checkState(boolean expression, String errorMessageTemplate, Object... errorMessageArgs) { if (!expression) { throw new IllegalStateException(format(errorMessageTemplate, errorMessageArgs)); } }
public long roundTo(Unit unit) { double rounded = Math.floor(getValue(unit) + 0.5d); checkArgument(rounded <= Long.MAX_VALUE, "size is too large to be represented in requested unit as a long"); return (long) rounded; }
public long roundTo(TimeUnit timeUnit) { requireNonNull(timeUnit, "timeUnit is null"); double rounded = Math.floor(getValue(timeUnit) + 0.5d); checkArgument(rounded <= Long.MAX_VALUE, "size is too large to be represented in requested unit as a long"); return (long) rounded; }
@JsonCreator public static Duration valueOf(String duration) throws IllegalArgumentException { requireNonNull(duration, "duration is null"); checkArgument(!duration.isEmpty(), "duration is empty"); Matcher matcher = PATTERN.matcher(duration); if (!matcher.matches()) { throw new IllegalArgumentException("duration is not a valid data duration string: " + duration); } double value = Double.parseDouble(matcher.group(1)); String unitString = matcher.group(2); TimeUnit timeUnit = valueOfTimeUnit(unitString); return new Duration(value, timeUnit); }
@JsonCreator public static DataSize valueOf(String size) throws IllegalArgumentException { requireNonNull(size, "size is null"); checkArgument(!size.isEmpty(), "size is empty"); Matcher matcher = PATTERN.matcher(size); if (!matcher.matches()) { throw new IllegalArgumentException("size is not a valid data size string: " + size); } double value = Double.parseDouble(matcher.group(1)); String unitString = matcher.group(2); for (Unit unit : Unit.values()) { if (unit.getUnitString().equals(unitString)) { return new DataSize(value, unit); } } throw new IllegalArgumentException("Unknown unit: " + unitString); }