下面列出了怎么用java.time.temporal.TemporalAmount的API类实例代码及写法,或者点击链接到github查看源代码。
@Test(dataProvider="calendars")
public void test_badMinusAdjusterChrono(Chronology chrono) {
LocalDate refDate = LocalDate.of(2013, 1, 1);
ChronoZonedDateTime<?> czdt = chrono.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC);
for (Chronology[] clist : data_of_calendars()) {
Chronology chrono2 = clist[0];
ChronoZonedDateTime<?> czdt2 = chrono2.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC);
TemporalAmount adjuster = new FixedAdjuster(czdt2);
if (chrono != chrono2) {
try {
czdt.minus(adjuster);
Assert.fail("WithAdjuster should have thrown a ClassCastException, "
+ "required: " + czdt + ", supplied: " + czdt2);
} catch (ClassCastException cce) {
// Expected exception; not an error
}
} else {
// Same chronology,
ChronoZonedDateTime<?> result = czdt.minus(adjuster);
assertEquals(result, czdt2, "WithAdjuster failed to replace date");
}
}
}
/**
* Test the times Duration ← relative
*/
@Test
public void getDuration() {
// "last min", "last hour", "last day", "last week"
Duration lastMin = TimeParser.parseDuration("1 min");
assertEquals("Failed to get Duration for last min", Duration.ofSeconds(60),
lastMin);
Duration lastHour = TimeParser.parseDuration("1 hour");
assertEquals("Failed to get Duration for last hour",
Duration.ofHours(1), lastHour);
// "last 5 mins", "last 5 hours", "last 5 days"
TemporalAmount last5Min = TimeParser.parseDuration(" 5 mins");
assertEquals("Failed to get Duration for last 5 mins",
Duration.ofMinutes(5), last5Min);
TemporalAmount last5Hour = TimeParser.parseDuration(" 5 hours");
assertEquals("Failed to get Duration for last 5 hours",
Duration.ofHours(5), last5Hour);
Duration last5Day = TimeParser.parseDuration(" 5 days");
assertEquals("Failed to get Duration for last 5 days",
60 * 60 * 24 * 5, last5Day.getSeconds());
}
@Test(dataProvider="calendars")
public void test_badPlusAdjusterChrono(Chronology chrono) {
LocalDate refDate = LocalDate.of(2013, 1, 1);
ChronoZonedDateTime<?> czdt = chrono.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC);
for (Chronology[] clist : data_of_calendars()) {
Chronology chrono2 = clist[0];
ChronoZonedDateTime<?> czdt2 = chrono2.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC);
TemporalAmount adjuster = new FixedAdjuster(czdt2);
if (chrono != chrono2) {
try {
czdt.plus(adjuster);
Assert.fail("WithAdjuster should have thrown a ClassCastException, "
+ "required: " + czdt + ", supplied: " + czdt2);
} catch (ClassCastException cce) {
// Expected exception; not an error
}
} else {
// Same chronology,
ChronoZonedDateTime<?> result = czdt.plus(adjuster);
assertEquals(result, czdt2, "WithAdjuster failed to replace date time");
}
}
}
/**
* Create a schedule to run a task exactly once at the given time.
* for a service with given name and relinquishing leadership
* at a given interval
*
* @param instant the task will run
* @param taskName name of the task in the global world
* @param number period to release leadership
* @param timeUnit time unit to release leadership
* @return schedule with the time in millis
*/
public static Schedule scheduleForRunningOnceAt(final Instant instant, final String taskName,
long number, TimeUnit timeUnit) {
return new Schedule() {
@Override
public TemporalAmount getPeriod() {
return null;
}
@Override
public Iterator<Instant> iterator() {
return Collections.singletonList(instant)
.iterator();
}
@Override
public String getTaskName() {
return taskName;
}
@Override
public Long getScheduledOwnershipReleaseInMillis() {
return timeUnit.toMillis(number);
}
};
}
@Test(dataProvider="calendars")
public void test_badPlusAdjusterChrono(Chronology chrono) {
LocalDate refDate = LocalDate.of(2013, 1, 1);
ChronoZonedDateTime<?> czdt = chrono.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC);
for (Chronology[] clist : data_of_calendars()) {
Chronology chrono2 = clist[0];
ChronoZonedDateTime<?> czdt2 = chrono2.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC);
TemporalAmount adjuster = new FixedAdjuster(czdt2);
if (chrono != chrono2) {
try {
czdt.plus(adjuster);
Assert.fail("WithAdjuster should have thrown a ClassCastException, "
+ "required: " + czdt + ", supplied: " + czdt2);
} catch (ClassCastException cce) {
// Expected exception; not an error
}
} else {
// Same chronology,
ChronoZonedDateTime<?> result = czdt.plus(adjuster);
assertEquals(result, czdt2, "WithAdjuster failed to replace date time");
}
}
}
@Test(dataProvider="calendars")
public void test_badMinusAdjusterChrono(Chronology chrono) {
LocalDate refDate = LocalDate.of(2013, 1, 1);
ChronoLocalDate date = chrono.date(refDate);
for (Chronology[] clist : data_of_calendars()) {
Chronology chrono2 = clist[0];
ChronoLocalDate date2 = chrono2.date(refDate);
TemporalAmount adjuster = new FixedAdjuster(date2);
if (chrono != chrono2) {
try {
date.minus(adjuster);
Assert.fail("WithAdjuster should have thrown a ClassCastException");
} catch (ClassCastException cce) {
// Expected exception; not an error
}
} else {
// Same chronology,
ChronoLocalDate result = date.minus(adjuster);
assertEquals(result, date2, "WithAdjuster failed to replace date");
}
}
}
@Test(dataProvider="calendars")
public void test_badPlusAdjusterChrono(Chronology chrono) {
LocalDate refDate = LocalDate.of(2013, 1, 1);
ChronoZonedDateTime<?> czdt = chrono.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC);
for (Chronology[] clist : data_of_calendars()) {
Chronology chrono2 = clist[0];
ChronoZonedDateTime<?> czdt2 = chrono2.date(refDate).atTime(LocalTime.NOON).atZone(ZoneOffset.UTC);
TemporalAmount adjuster = new FixedAdjuster(czdt2);
if (chrono != chrono2) {
try {
czdt.plus(adjuster);
Assert.fail("WithAdjuster should have thrown a ClassCastException, "
+ "required: " + czdt + ", supplied: " + czdt2);
} catch (ClassCastException cce) {
// Expected exception; not an error
}
} else {
// Same chronology,
ChronoZonedDateTime<?> result = czdt.plus(adjuster);
assertEquals(result, czdt2, "WithAdjuster failed to replace date time");
}
}
}
@Test(dataProvider="plus_TemporalAmount")
public void test_plus_TemporalAmount(YearMonth base, TemporalAmount temporalAmount, YearMonth expectedYearMonth, Class<?> expectedEx) {
if (expectedEx == null) {
assertEquals(base.plus(temporalAmount), expectedYearMonth);
} else {
try {
YearMonth result = base.plus(temporalAmount);
fail();
} catch (Exception ex) {
assertTrue(expectedEx.isInstance(ex));
}
}
}
@Override
public TemporalAmount duration(String from) {
try {
return this.durationLib.duration(from);
} catch (Exception e) {
String message = String.format("duration(%s)", from);
logError(message, e);
return null;
}
}
@Override
public ChronoPeriod plus(TemporalAmount amountToAdd) {
ChronoPeriodImpl amount = validateAmount(amountToAdd);
return new ChronoPeriodImpl(
chrono,
Math.addExact(years, amount.years),
Math.addExact(months, amount.months),
Math.addExact(days, amount.days));
}
public static void expect(TemporalAmount timeout, Callable<Boolean> condition, Duration interval)
throws Exception
{
Instant deadline = Instant.now().plus(timeout);
while (Instant.now().toEpochMilli() < deadline.toEpochMilli()) {
if (condition.call()) {
return;
}
Thread.sleep(interval.toMillis());
}
fail("Timeout after: " + timeout);
}
@Override
public ChronoPeriod minus(TemporalAmount amountToSubtract) {
ChronoPeriodImpl amount = validateAmount(amountToSubtract);
return new ChronoPeriodImpl(
chrono,
Math.subtractExact(years, amount.years),
Math.subtractExact(months, amount.months),
Math.subtractExact(days, amount.days));
}
@Override
public ChronoPeriod minus(TemporalAmount amountToSubtract) {
ChronoPeriodImpl amount = validateAmount(amountToSubtract);
return new ChronoPeriodImpl(
chrono,
Math.subtractExact(years, amount.years),
Math.subtractExact(months, amount.months),
Math.subtractExact(days, amount.days));
}
@Test
public void shouldLockTimeFromAnnotationWithDurationString() throws NoSuchMethodException {
noopResolver();
AnnotationData annotation = getAnnotation("annotatedMethodWithDurationString");
TemporalAmount lockAtMostFor = extractor.getLockAtMostFor(annotation);
assertThat(lockAtMostFor).isEqualTo(Duration.of(1, SECONDS));
}
static boolean isImmutable(Object value) {
if (value == null) {
return true;
} else if (isImmutableProxy(value)) {
return true;
} else if (value instanceof String) {
return true;
} else if (value instanceof Number) {
return true;
} else if (value instanceof Boolean) {
return true;
} else if (value instanceof Character) {
return true;
} else if (value instanceof Temporal) {
return true;
} else if (value instanceof TemporalAmount) {
return true;
} else if (value instanceof UUID) {
return true;
} else if (value instanceof File) {
return true;
} else if (value instanceof Path) {
return true;
} else if (value instanceof URI) {
return true;
} else if (isEnumValue(value)) {
return true;
} else {
return false;
}
}
/**
* Obtains an instance of {@code ChronoPeriodImpl} from a temporal amount.
*
* @param amount the temporal amount to convert, not null
* @return the period, not null
*/
private ChronoPeriodImpl validateAmount(TemporalAmount amount) {
Objects.requireNonNull(amount, "amount");
if (amount instanceof ChronoPeriodImpl == false) {
throw new DateTimeException("Unable to obtain ChronoPeriod from TemporalAmount: " + amount.getClass());
}
ChronoPeriodImpl period = (ChronoPeriodImpl) amount;
if (chrono.equals(period.getChronology()) == false) {
throw new ClassCastException("Chronology mismatch, expected: " + chrono.getId() + ", actual: " + period.getChronology().getId());
}
return period;
}
public void handleJobFailure(Job job, String error) {
log.debug("Job handler "+job.getJobHandler().getClass().getSimpleName()+" error occurred: "+error);
long errorCount = job.getErrorCount();
TemporalAmount retryDuration = job.getNextRetryDuration();
if (retryDuration!=null) {
Instant nextRetryTime = Time.now().plus(retryDuration);
job.setExecutionTime(nextRetryTime);
engine.getEventDispatcher().dispatch(new JobFailedEvent(job.getId(), error, nextRetryTime));
} else {
engine.getEventDispatcher().dispatch(new JobFailedEvent(job.getId(), error));
}
}
@Test(dataProvider="plus_TemporalAmount")
public void test_plus_TemporalAmount(YearMonth base, TemporalAmount temporalAmount, YearMonth expectedYearMonth, Class<?> expectedEx) {
if (expectedEx == null) {
assertEquals(base.plus(temporalAmount), expectedYearMonth);
} else {
try {
YearMonth result = base.plus(temporalAmount);
fail();
} catch (Exception ex) {
assertTrue(expectedEx.isInstance(ex));
}
}
}
public static LocalDateTime minus( @This LocalDateTime thiz, Time time )
{
if( time.getDisplayUnit().isDateBased() )
{
// Extract the Period from the date-based time and add that
Rational years = time.toBaseNumber() / TimeUnit.Year.getSeconds();
int wholeYears = years.wholePart().intValue();
Rational months = years.fractionPart() * TimeUnit.Year.getSeconds() / TimeUnit.Month.getSeconds();
int wholeMonths = months.wholePart().intValue();
Rational days = months.fractionPart() * TimeUnit.Month.getSeconds() / TimeUnit.Day.getSeconds();
int wholeDays = days.wholePart().intValue();
Period period = Period.of( wholeYears, wholeMonths, wholeDays );
LocalDateTime newDate = thiz - period;
// Now add the remaining fractional day part, if non-zero, as a Duration (added to the date-time's time component)
Rational seconds = days.fractionPart() * TimeUnit.Day.getSeconds();
if( seconds != Rational.ZERO )
{
long wholeSeconds = seconds.wholePart().longValue();
long nanos = (seconds.fractionPart() * 1e+9).longValue();
newDate = newDate - Duration.ofSeconds( wholeSeconds, nanos );
}
return newDate;
}
return thiz - (TemporalAmount)time;
}
/**
* Obtains an instance of {@code Period} from a temporal amount.
* <p>
* This obtains a period based on the specified amount.
* A {@code TemporalAmount} represents an amount of time, which may be
* date-based or time-based, which this factory extracts to a {@code Period}.
* <p>
* The conversion loops around the set of units from the amount and uses
* the {@link ChronoUnit#YEARS YEARS}, {@link ChronoUnit#MONTHS MONTHS}
* and {@link ChronoUnit#DAYS DAYS} units to create a period.
* If any other units are found then an exception is thrown.
* <p>
* If the amount is a {@code ChronoPeriod} then it must use the ISO chronology.
*
* @param amount the temporal amount to convert, not null
* @return the equivalent period, not null
* @throws DateTimeException if unable to convert to a {@code Period}
* @throws ArithmeticException if the amount of years, months or days exceeds an int
*/
public static Period from(TemporalAmount amount) {
if (amount instanceof Period) {
return (Period) amount;
}
if (amount instanceof ChronoPeriod) {
if (IsoChronology.INSTANCE.equals(((ChronoPeriod) amount).getChronology()) == false) {
throw new DateTimeException("Period requires ISO chronology: " + amount);
}
}
Objects.requireNonNull(amount, "amount");
int years = 0;
int months = 0;
int days = 0;
for (TemporalUnit unit : amount.getUnits()) {
long unitAmount = amount.get(unit);
if (unit == ChronoUnit.YEARS) {
years = Math.toIntExact(unitAmount);
} else if (unit == ChronoUnit.MONTHS) {
months = Math.toIntExact(unitAmount);
} else if (unit == ChronoUnit.DAYS) {
days = Math.toIntExact(unitAmount);
} else {
throw new DateTimeException("Unit must be Years, Months or Days, but was " + unit);
}
}
return create(years, months, days);
}
@Test(expectedExceptions=NullPointerException.class)
public void test_plus_PlusAdjuster_null() {
TEST_11_30_59_500_PONE.plus((TemporalAmount) null);
}
@Test(expectedExceptions=DateTimeException.class)
public void test_plus_TemporalAmount_dateNotAllowed() {
TemporalAmount period = MockSimplePeriod.of(7, ChronoUnit.MONTHS);
TEST_12_30_40_987654321.plus(period);
}
public Builder recurring(Runnable action, TemporalAmount period) {
recurrentActions.add(new RecurrentAction(action, period));
return this;
}
@Override
public TemporalAmount getPeriod() {
return amount;
}
@Test()
@UseDataProvider("data_minusValid")
public void test_minusValid(int year, TemporalAmount amount, int expected) {
assertEquals(Year.of(year).minus(amount), Year.of(expected));
}
@Test(expected=NullPointerException.class)
public void test_minus_MinusAdjuster_null() {
TEST_11_30_59_500_PONE.minus((TemporalAmount) null);
}
@Test(expectedExceptions=NullPointerException.class)
public void test_plus_PlusAdjuster_null() {
TEST_11_30_59_500_PONE.plus((TemporalAmount) null);
}
@Test
public void factory_from_TemporalAmount_Duration() {
TemporalAmount amount = Duration.ofHours(3);
assertEquals(Duration.from(amount), Duration.ofHours(3));
}
@Test
public void test_minus_TemporalAmount_wrap() {
TemporalAmount p = MockSimplePeriod.of(1, HOURS);
LocalTime t = LocalTime.of(0, 30).minus(p);
assertEquals(t, LocalTime.of(23, 30));
}
@Test
public void test_plus_TemporalAmount_zero() {
TemporalAmount period = Period.ZERO;
LocalTime t = TEST_12_30_40_987654321.plus(period);
assertEquals(t, TEST_12_30_40_987654321);
}