下面列出了java.time.Duration#dividedBy ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
void calculateLapsPerHour()
{
Instant now = Instant.now();
if (lastLapCompleted != null)
{
Duration timeSinceLastLap = Duration.between(lastLapCompleted, now);
if (!timeSinceLastLap.isNegative())
{
lastLapTimes.add(timeSinceLastLap);
Duration sum = Duration.ZERO;
for (Duration lapTime : lastLapTimes)
{
sum = sum.plus(lapTime);
}
Duration averageLapTime = sum.dividedBy(lastLapTimes.size());
lapsPerHour = (int) (Duration.ofHours(1).toMillis() / averageLapTime.toMillis());
}
}
lastLapCompleted = now;
}
@Test(dataProvider="DividedBy")
public void dividedBy(long seconds, int nanos, int divisor, long expectedSeconds, int expectedNanos) {
Duration t = Duration.ofSeconds(seconds, nanos);
t = t.dividedBy(divisor);
assertEquals(t.getSeconds(), expectedSeconds);
assertEquals(t.getNano(), expectedNanos);
}
@Test()
@UseDataProvider("provider_dividedBy")
public void dividedBy(long seconds, int nanos, int divisor, long expectedSeconds, int expectedNanos) {
Duration t = Duration.ofSeconds(seconds, nanos);
t = t.dividedBy(divisor);
assertEquals(t.getSeconds(), expectedSeconds);
assertEquals(t.getNano(), expectedNanos);
}
@Test(dataProvider="DividedBy")
public void dividedBy(long seconds, int nanos, int divisor, long expectedSeconds, int expectedNanos) {
Duration t = Duration.ofSeconds(seconds, nanos);
t = t.dividedBy(divisor);
assertEquals(t.getSeconds(), expectedSeconds);
assertEquals(t.getNano(), expectedNanos);
}
@Test(dataProvider="DividedBy")
public void dividedBy(long seconds, int nanos, int divisor, long expectedSeconds, int expectedNanos) {
Duration t = Duration.ofSeconds(seconds, nanos);
t = t.dividedBy(divisor);
assertEquals(t.getSeconds(), expectedSeconds);
assertEquals(t.getNano(), expectedNanos);
}
@Test(dataProvider="DividedBy")
public void dividedBy(long seconds, int nanos, int divisor, long expectedSeconds, int expectedNanos) {
Duration t = Duration.ofSeconds(seconds, nanos);
t = t.dividedBy(divisor);
assertEquals(t.getSeconds(), expectedSeconds);
assertEquals(t.getNano(), expectedNanos);
}
@Test(dataProvider="DividedBy")
public void dividedBy(long seconds, int nanos, int divisor, long expectedSeconds, int expectedNanos) {
Duration t = Duration.ofSeconds(seconds, nanos);
t = t.dividedBy(divisor);
assertEquals(t.getSeconds(), expectedSeconds);
assertEquals(t.getNano(), expectedNanos);
}
@Test(dataProvider="DividedBy")
public void dividedBy(long seconds, int nanos, int divisor, long expectedSeconds, int expectedNanos) {
Duration t = Duration.ofSeconds(seconds, nanos);
t = t.dividedBy(divisor);
assertEquals(t.getSeconds(), expectedSeconds);
assertEquals(t.getNano(), expectedNanos);
}
@Test(expected=ArithmeticException.class)
@UseDataProvider("provider_dividedBy")
public void dividedByZero(long seconds, int nanos, int divisor, long expectedSeconds, int expectedNanos) {
Duration t = Duration.ofSeconds(seconds, nanos);
t.dividedBy(0);
fail(t + " divided by zero did not throw ArithmeticException");
}
@Test(dataProvider="DividedBy", expectedExceptions=ArithmeticException.class)
public void dividedByZero(long seconds, int nanos, int divisor, long expectedSeconds, int expectedNanos) {
Duration t = Duration.ofSeconds(seconds, nanos);
t.dividedBy(0);
fail(t + " divided by zero did not throw ArithmeticException");
}
@Test(dataProvider="DividedBy", expectedExceptions=ArithmeticException.class)
public void dividedByZero(long seconds, int nanos, int divisor, long expectedSeconds, int expectedNanos) {
Duration t = Duration.ofSeconds(seconds, nanos);
t.dividedBy(0);
fail(t + " divided by zero did not throw ArithmeticException");
}
@Test(dataProvider="DividedBy", expectedExceptions=ArithmeticException.class)
public void dividedByZero(long seconds, int nanos, int divisor, long expectedSeconds, int expectedNanos) {
Duration t = Duration.ofSeconds(seconds, nanos);
t.dividedBy(0);
fail(t + " divided by zero did not throw ArithmeticException");
}
/** {@inheritDoc} */
@Override
public void compute(final Instant low, final Instant high, final Graphics2D gc, final int screen_width)
{
final Duration range = Duration.between(low, high);
if (range.isNegative())
throw new Error("Tick range is not ordered, " + low + " > " + high);
// Estimate number of labels that fits on screen
final int label_width = gc.getFontMetrics().stringWidth("yyyy-MM-dd");
final int num_that_fits = Math.max(1, screen_width/label_width*FILL_PERCENTAGE/100);
final Duration distance = range.dividedBy(num_that_fits);
// Which of the available formats suits the visible time range?
for (int i=0; i<tick_configs.length; ++i)
{
final TickConfig option = tick_configs[i];
if (distance.compareTo(option.threshold) >= 0)
{
config = option;
detailed_config = i < tick_configs.length-1 ? tick_configs[i+1] : tick_configs[i];
break;
}
}
start = low.with(config.rounding);
logger.log(Level.FINE, "Compute time ticks for {0}, {1} pixels: Tick distance {2}",
new Object[] { range, screen_width, config.distance });
final List<MajorTick<Instant>> major_ticks = new ArrayList<>();
final List<MinorTick<Instant>> minor_ticks = new ArrayList<>();
long prev_ms = getPrevious(start).toEpochMilli();
final Instant end = getNext(high);
for (Instant value = start; value.isBefore(end); value = getNext(value))
{
if (value.compareTo(low) >= 0 && value.compareTo(high) <= 0)
major_ticks.add(new MajorTick<>(value, format(value)));
final long ms = value.toEpochMilli();
for (int i=1; i<config.minor_ticks; ++i)
{
final long min_ms = prev_ms + ((ms - prev_ms)*i)/config.minor_ticks;
final Instant min_val = Instant.ofEpochMilli(min_ms);
if (min_val.isAfter(low) && min_val.isBefore(high))
minor_ticks.add(new MinorTick<>(min_val));
}
prev_ms = ms;
}
if (major_ticks.size() < 2)
{ // If the best-laid plans of mice and men fail
// and we end up with just one or no tick,
// add the low and high markers.
// Use full format for the low marker.
final ZonedDateTime local = ZonedDateTime.ofInstant(low, ZoneId.systemDefault());
major_ticks.add(0, new MajorTick<>(low, config.start_formatter.format(local)));
major_ticks.add(new MajorTick<>(high, format(high)));
}
this.major_ticks = major_ticks;
this.minor_ticks = minor_ticks;
}
@Test
public void upgrade_by_retiring() {
var versions = new OsVersions(tester.nodeRepository(), new RetiringUpgrader(tester.nodeRepository()));
var clock = (ManualClock) tester.nodeRepository().clock();
int hostCount = 10;
// Provision hosts and children
List<Node> hosts = provisionInfraApplication(hostCount);
NodeResources resources = new NodeResources(2, 4, 8, 1);
for (var host : hosts) {
tester.makeReadyVirtualDockerNodes(2, resources, host.hostname());
}
Supplier<NodeList> hostNodes = () -> tester.nodeRepository().list()
.nodeType(NodeType.host)
.not().state(Node.State.deprovisioned);
// Target is set and upgrade started
var version1 = Version.fromString("7.1");
Duration totalBudget = Duration.ofHours(12);
Duration nodeBudget = totalBudget.dividedBy(hostCount);
versions.setTarget(NodeType.host, version1, Optional.of(totalBudget),false);
versions.resumeUpgradeOf(NodeType.host, true);
// One host is deprovisioning
assertEquals(1, hostNodes.get().deprovisioning().size());
// Nothing happens on next resume as first host has not spent its budget
versions.resumeUpgradeOf(NodeType.host, true);
NodeList nodesDeprovisioning = hostNodes.get().deprovisioning();
assertEquals(1, nodesDeprovisioning.size());
assertEquals(2, retiringChildrenOf(nodesDeprovisioning.asList().get(0)).size());
// Budget has been spent and another host is retired
clock.advance(nodeBudget);
versions.resumeUpgradeOf(NodeType.host, true);
assertEquals(2, hostNodes.get().deprovisioning().size());
// Two nodes complete their upgrade by being reprovisioned
completeUpgradeOf(hostNodes.get().deprovisioning().asList());
assertEquals(2, hostNodes.get().onOsVersion(version1).size());
// The remaining hosts complete their upgrade
for (int i = 0; i < hostCount - 2; i++) {
clock.advance(nodeBudget);
versions.resumeUpgradeOf(NodeType.host, true);
nodesDeprovisioning = hostNodes.get().deprovisioning();
assertEquals(1, nodesDeprovisioning.size());
assertEquals(2, retiringChildrenOf(nodesDeprovisioning.asList().get(0)).size());
completeUpgradeOf(nodesDeprovisioning.asList());
}
// All hosts upgraded and none are deprovisioning
assertEquals(hostCount, hostNodes.get().onOsVersion(version1).not().deprovisioning().size());
assertEquals(hostCount, tester.nodeRepository().list().state(Node.State.deprovisioned).size());
var lastRetiredAt = clock.instant().truncatedTo(ChronoUnit.MILLIS);
// Resuming after everything has upgraded does nothing
versions.resumeUpgradeOf(NodeType.host, true);
assertEquals(0, hostNodes.get().deprovisioning().size());
// Another upgrade is triggered. Last retirement time is preserved
clock.advance(Duration.ofDays(1));
var version2 = Version.fromString("7.2");
versions.setTarget(NodeType.host, version2, Optional.of(totalBudget), false);
assertEquals(lastRetiredAt, versions.readChange().targets().get(NodeType.host).lastRetiredAt().get());
}
@Test(expectedExceptions=NullPointerException.class)
public void test_dividedByDur_null() {
Duration t = Duration.ofSeconds(1, 0);
t.dividedBy(null);
}
@Test(expectedExceptions=ArithmeticException.class)
public void test_dividedByDur_overflow() {
Duration dur1 = Duration.ofSeconds(Long.MAX_VALUE, 0);
Duration dur2 = Duration.ofNanos(1);
dur1.dividedBy(dur2);
}
@Test(dataProvider="DividedBy", expectedExceptions=ArithmeticException.class)
public void dividedByZero(long seconds, int nanos, int divisor, long expectedSeconds, int expectedNanos) {
Duration t = Duration.ofSeconds(seconds, nanos);
t.dividedBy(0);
fail(t + " divided by zero did not throw ArithmeticException");
}
@Test(dataProvider="DividedBy", expectedExceptions=ArithmeticException.class)
public void dividedByZero(long seconds, int nanos, int divisor, long expectedSeconds, int expectedNanos) {
Duration t = Duration.ofSeconds(seconds, nanos);
t.dividedBy(0);
fail(t + " divided by zero did not throw ArithmeticException");
}
/**
* Supports the division operator; equivalent to calling the {@link Duration#dividedBy(long)} method.
*
* @param self a Duration
* @param scalar the value to divide by
* @return a Duration
* @since 2.5.0
*/
public static Duration div(final Duration self, long scalar) {
return self.dividedBy(scalar);
}
/**
* Returns a time interval that lasts this duration and is centered
* around the given instant reference.
*
* @param duration the duration
* @param reference a instant
* @return a new time interval
*/
public static TimeInterval around(Duration duration, Instant reference) {
Duration half = duration.dividedBy(2);
return TimeInterval.between(reference.minus(half), reference.plus(half));
}