java.time.LocalDate Java Examples

The following examples show how to use java.time.LocalDate. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestChronoLocalDate.java    From jdk8u-dev-jdk with GNU General Public License v2.0 7 votes vote down vote up
public void test_date_comparator_checkGenerics_LocalDate() {
    List<LocalDate> dates = new ArrayList<>();
    LocalDate date = LocalDate.of(2013, 1, 1);

    // Insert dates in order, no duplicates
    dates.add(date.minus(10, ChronoUnit.YEARS));
    dates.add(date.minus(1, ChronoUnit.YEARS));
    dates.add(date.minus(1, ChronoUnit.MONTHS));
    dates.add(date.minus(1, ChronoUnit.WEEKS));
    dates.add(date.minus(1, ChronoUnit.DAYS));
    dates.add(date);
    dates.add(date.plus(1, ChronoUnit.DAYS));
    dates.add(date.plus(1, ChronoUnit.WEEKS));
    dates.add(date.plus(1, ChronoUnit.MONTHS));
    dates.add(date.plus(1, ChronoUnit.YEARS));
    dates.add(date.plus(10, ChronoUnit.YEARS));

    List<LocalDate> copy = new ArrayList<>(dates);
    Collections.shuffle(copy);
    Collections.sort(copy, ChronoLocalDate.timeLineOrder());
    assertEquals(copy, dates);
    assertTrue(ChronoLocalDate.timeLineOrder().compare(copy.get(0), copy.get(1)) < 0);
}
 
Example #2
Source File: ResolvedCapitalIndexedBondTest.java    From Strata with Apache License 2.0 6 votes vote down vote up
@Test
public void test_builder() {
  ResolvedCapitalIndexedBond test = sut();
  assertThat(test.getCurrency()).isEqualTo(USD);
  assertThat(test.getDayCount()).isEqualTo(ACT_ACT_ISDA);
  assertThat(test.getStartDate()).isEqualTo(PERIODIC[0].getStartDate());
  assertThat(test.getEndDate()).isEqualTo(PERIODIC[3].getEndDate());
  assertThat(test.getUnadjustedStartDate()).isEqualTo(PERIODIC[0].getUnadjustedStartDate());
  assertThat(test.getUnadjustedEndDate()).isEqualTo(PERIODIC[3].getUnadjustedEndDate());
  assertThat(test.getLegalEntityId()).isEqualTo(LEGAL_ENTITY);
  assertThat(test.getNominalPayment()).isEqualTo(NOMINAL);
  assertThat(test.getNotional()).isEqualTo(NOTIONAL);
  assertThat(test.getPeriodicPayments().toArray()).isEqualTo(PERIODIC);
  assertThat(test.getSettlementDateOffset()).isEqualTo(SETTLE_OFFSET);
  assertThat(test.getYieldConvention()).isEqualTo(US_IL_REAL);
  assertThat(test.hasExCouponPeriod()).isFalse();
  assertThat(test.getFirstIndexValue()).isEqualTo(RATE_CALC.getFirstIndexValue().getAsDouble());
  assertThat(test.findPeriod(PERIODIC[0].getUnadjustedStartDate())).isEqualTo(Optional.of(test.getPeriodicPayments().get(0)));
  assertThat(test.findPeriod(LocalDate.MIN)).isEqualTo(Optional.empty());
  assertThat(test.findPeriodIndex(PERIODIC[0].getUnadjustedStartDate())).isEqualTo(OptionalInt.of(0));
  assertThat(test.findPeriodIndex(PERIODIC[1].getUnadjustedStartDate())).isEqualTo(OptionalInt.of(1));
  assertThat(test.findPeriodIndex(LocalDate.MIN)).isEqualTo(OptionalInt.empty());
  assertThat(test.calculateSettlementDateFromValuation(date(2015, 6, 30), REF_DATA))
      .isEqualTo(SETTLE_OFFSET.adjust(date(2015, 6, 30), REF_DATA));
}
 
Example #3
Source File: HtmlMappingTest.java    From doov with Apache License 2.0 6 votes vote down vote up
@Test
void mapping_to_date_field_with_converter() {
    ctx = map(LocalDate.of(2000, 1, 1)).using(converter(date -> date.toString(), "empty", "date to string"))
                    .to(stringField).executeOn(model, model);
    doc = documentOf(ctx);
    assertThat(doc).percentageValue_DIV().isEmpty();
    assertThat(doc).nary_OL().hasSize(0);
    assertThat(doc).binary_LI().hasSize(0);
    assertThat(doc).nary_LI().hasSize(0);
    assertThat(doc).leaf_LI().hasSize(0);
    assertThat(doc).when_UL().hasSize(0);
    assertThat(doc).binary_UL().hasSize(0);
    assertThat(doc).binaryChild_UL().hasSize(0);
    assertThat(doc).unary_UL().hasSize(0);
    assertThat(doc).tokenWhen_SPAN().hasSize(0);
    assertThat(doc).tokenThen_SPAN().hasSize(0);
    assertThat(doc).tokenElse_SPAN().hasSize(0);
    assertThat(doc).tokenSingleMapping_SPAN().hasSize(1);
    assertThat(doc).tokenOperator_SPAN().containsExactly("map", "using", "to");
    assertThat(doc).tokenValue_SPAN().containsExactly("2000-01-01", "'date to string'");
    assertThat(doc).tokenNary_SPAN().isEmpty();
}
 
Example #4
Source File: TokenSecuredResource.java    From quarkus-quickstarts with Apache License 2.0 6 votes vote down vote up
@GET
@Path("winners2")
@Produces(MediaType.TEXT_PLAIN)
@RolesAllowed("Subscriber")
public String winners2() {
    int remaining = 6;
    ArrayList<Integer> numbers = new ArrayList<>();

    // If the JWT contains a birthdate claim, use the day of the month as a pick
    if (birthdate.isPresent()) {
        String bdayString = birthdate.get().getString();
        LocalDate bday = LocalDate.parse(bdayString);
        numbers.add(bday.getDayOfMonth());
        remaining--;
    }
    // Fill remaining picks with random numbers
    while (remaining > 0) {
        int pick = (int) Math.rint(64 * Math.random() + 1);
        numbers.add(pick);
        remaining--;
    }
    return numbers.toString();
}
 
Example #5
Source File: TCKLocalDateTime.java    From j2objc with Apache License 2.0 6 votes vote down vote up
void test_comparisons_LocalDateTime(LocalDate... localDates) {
    test_comparisons_LocalDateTime(
        localDates,
        LocalTime.MIDNIGHT,
        LocalTime.of(0, 0, 0, 999999999),
        LocalTime.of(0, 0, 59, 0),
        LocalTime.of(0, 0, 59, 999999999),
        LocalTime.of(0, 59, 0, 0),
        LocalTime.of(0, 59, 59, 999999999),
        LocalTime.NOON,
        LocalTime.of(12, 0, 0, 999999999),
        LocalTime.of(12, 0, 59, 0),
        LocalTime.of(12, 0, 59, 999999999),
        LocalTime.of(12, 59, 0, 0),
        LocalTime.of(12, 59, 59, 999999999),
        LocalTime.of(23, 0, 0, 0),
        LocalTime.of(23, 0, 0, 999999999),
        LocalTime.of(23, 0, 59, 0),
        LocalTime.of(23, 0, 59, 999999999),
        LocalTime.of(23, 59, 0, 0),
        LocalTime.of(23, 59, 59, 999999999)
    );
}
 
Example #6
Source File: AbstractForwardCurve.java    From finmath-lib with Apache License 2.0 6 votes vote down vote up
@Override
public double getPaymentOffset(final double fixingTime) {
	if(getPaymentOffsetCode() == null) {
		return paymentOffset;
	}

	if(paymentOffsets.containsKey(fixingTime)) {
		return paymentOffsets.get(fixingTime);
	}
	else {
		/*
		 * TODO In case paymentDate is relevant for the index modeling, it should be checked
		 * if the following derivation of paymentDate is accurate (e.g. wo we have a fixingOffset).
		 * In such a case, this method may be overridden.
		 */
		final LocalDate referenceDate = getReferenceDate();
		final LocalDate fixingDate = FloatingpointDate.getDateFromFloatingPointDate(referenceDate, fixingTime);
		final LocalDate paymentDate = getPaymentBusinessdayCalendar().getAdjustedDate(fixingDate, getPaymentOffsetCode(), getPaymentDateRollConvention());
		final double paymentTime = FloatingpointDate.getFloatingPointDateFromDate(referenceDate, paymentDate);
		paymentOffsets.put(fixingTime, paymentTime-fixingTime);
		return paymentTime-fixingTime;
	}
}
 
Example #7
Source File: CT_DocInfoTest.java    From ofdrw with Apache License 2.0 6 votes vote down vote up
public static CT_DocInfo docInfoCase(){
    CT_DocInfo docInfo = new CT_DocInfo();
    CustomDatas customDatas = new CustomDatas()
            .addCustomData("key1", "value1")
            .addCustomData("key2", "value2");

    docInfo.randomDocID()
            .setTile("Title")
            .setAuthor("Cliven")
            .setSubject("Subject")
            .setAbstract("This is abstract")
            .setCreationDate(LocalDate.now().minusDays(1L))
            .setModDate(LocalDate.now())
            .setDocUsage(DocUsage.Normal)
            .setCover(new ST_Loc("./Res/Cover.xml"))
            .addKeyword("111")
            .addKeyword("222")
            .setCreator("ofdrw")
            .setCreatorVersion("1.0.0-SNAPSHOT")
            .setCustomDatas(customDatas);
    return docInfo;
}
 
Example #8
Source File: TestLocalDate.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
void doTest_comparisons_LocalDate(LocalDate... localDates) {
    for (int i = 0; i < localDates.length; i++) {
        LocalDate a = localDates[i];
        for (int j = 0; j < localDates.length; j++) {
            LocalDate b = localDates[j];
            if (i < j) {
                assertTrue(a.compareTo(b) < 0, a + " <=> " + b);
                assertEquals(a.isBefore(b), true, a + " <=> " + b);
                assertEquals(a.isAfter(b), false, a + " <=> " + b);
                assertEquals(a.equals(b), false, a + " <=> " + b);
            } else if (i > j) {
                assertTrue(a.compareTo(b) > 0, a + " <=> " + b);
                assertEquals(a.isBefore(b), false, a + " <=> " + b);
                assertEquals(a.isAfter(b), true, a + " <=> " + b);
                assertEquals(a.equals(b), false, a + " <=> " + b);
            } else {
                assertEquals(a.compareTo(b), 0, a + " <=> " + b);
                assertEquals(a.isBefore(b), false, a + " <=> " + b);
                assertEquals(a.isAfter(b), false, a + " <=> " + b);
                assertEquals(a.equals(b), true, a + " <=> " + b);
            }
        }
    }
}
 
Example #9
Source File: TCKIsoChronology.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider = "resolve_ymaa")
public void test_resolve_ymaa_strict(int y, int m, int w, int d, LocalDate expected, boolean smart, boolean strict) {
    Map<TemporalField, Long> fieldValues = new HashMap<>();
    fieldValues.put(ChronoField.YEAR, (long) y);
    fieldValues.put(ChronoField.MONTH_OF_YEAR, (long) m);
    fieldValues.put(ChronoField.ALIGNED_WEEK_OF_MONTH, (long) w);
    fieldValues.put(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH, (long) d);
    if (strict) {
        LocalDate date = IsoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT);
        assertEquals(date, expected);
        assertEquals(fieldValues.size(), 0);
    } else {
        try {
            IsoChronology.INSTANCE.resolveDate(fieldValues, ResolverStyle.STRICT);
            fail("Should have failed");
        } catch (DateTimeException ex) {
            // expected
        }
    }
}
 
Example #10
Source File: WeatherService.java    From ehcache3-samples with Apache License 2.0 5 votes vote down vote up
private WeatherReport getFakeWeatherReport(String location, LocalDate date) {
    Random rand = ThreadLocalRandom.current();
    Stopwatch stopwatch = Stopwatch.createStarted();
    try {
        Thread.sleep(500 + rand.nextInt(500));
        resourceCallService.addCall("Fake Webservice call", ResourceType.WEB_SERVICE, location, stopwatch.elapsed(TimeUnit.MILLISECONDS));
    } catch (InterruptedException e) {
        // ignore
    }
    int min = -30 + rand.nextInt(60);
    int max = min + rand.nextInt(15);
    String summary = WEATHERS[rand.nextInt(WEATHERS.length)];
    String icon = summary.toLowerCase(Locale.US);
    return new WeatherReport(date, location, summary, icon, min, max);
}
 
Example #11
Source File: DateAdapters.java    From sumk with Apache License 2.0 5 votes vote down vote up
@Override
public LocalDate read(JsonReader in) throws IOException {
	if (in.peek() == JsonToken.NULL) {
		in.nextNull();
		return null;
	}
	String v = in.nextString();
	return SumkDate.of(v, SumkDate.yyyy_MM_dd).toLocalDate();
}
 
Example #12
Source File: ApproxForwardOvernightAveragedRateComputationFn.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Override
public double explainRate(
    OvernightAveragedRateComputation computation,
    LocalDate startDate,
    LocalDate endDate,
    RatesProvider provider,
    ExplainMapBuilder builder) {

  double rate = rate(computation, startDate, endDate, provider);
  builder.put(ExplainKey.COMBINED_RATE, rate);
  return rate;
}
 
Example #13
Source File: TCKTemporalAdjusters.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_firstDayOfNextMonth_leap() {
    for (Month month : Month.values()) {
        for (int i = 1; i <= month.length(true); i++) {
            LocalDate date = date(2008, month, i);
            LocalDate test = (LocalDate) TemporalAdjusters.firstDayOfNextMonth().adjustInto(date);
            assertEquals(test.getYear(), month == DECEMBER ? 2009 : 2008);
            assertEquals(test.getMonth(), month.plus(1));
            assertEquals(test.getDayOfMonth(), 1);
        }
    }
}
 
Example #14
Source File: SelectDataTypesTest.java    From pgadba with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void selectDate() throws ExecutionException, InterruptedException, TimeoutException {
  try (Session session = ds.getSession()) {
    CompletionStage<LocalDate> idF = session.<LocalDate>rowOperation("select '2018-04-29 20:55:57.692132'::date as t")
        .collect(singleCollector(LocalDate.class))
        .submit()
        .getCompletionStage();

    assertEquals(LocalDate.of(2018, 4, 29), get10(idF));
  }
}
 
Example #15
Source File: YYYYMMDDAssigner.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Override
protected void doProcess(final JCas jCas) throws AnalysisEngineProcessException {
  final DocumentAnnotation da = getDocumentAnnotation(jCas);
  final String source = da.getSourceUri();

  final Matcher matcher = pattern.matcher(source);
  if (matcher.matches()) {
    try {
      final int y = Integer.parseInt(matcher.group("year"));
      final int m = Integer.parseInt(matcher.group("month"));
      final int d = Integer.parseInt(matcher.group("day"));

      if (m >= 1 && m <= 12 && d >= 1 && d <= 31) {
        // This will check if its' actually valid (31 Feb) it's actualy valid date...

        final LocalDate date = LocalDate.of(y, m, d);
        final long ts = date.atStartOfDay().atOffset(ZoneOffset.UTC).toInstant().toEpochMilli();

        da.setTimestamp(ts);
      }

    } catch (final Exception e) {
      // Do nothing.. not a valid source path...
      getMonitor().warn("Cant parse date from source uri {} ", source, e);
    }
  }
}
 
Example #16
Source File: InvoiceService.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean hasStornoBeforeDate(IInvoice invoice, LocalDate date){
	List<IPayment> zahlungen = invoice.getPayments();
	for (IPayment zahlung : zahlungen) {
		if (zahlung.getRemark().equals("Storno")) {
			if (zahlung.getDate().isBefore(date) || zahlung.getDate().equals(date)) {
				return true;
			}
		}
	}
	return false;
}
 
Example #17
Source File: TCKWeekFields.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
@UseDataProvider("data_weekFields")
public void test_fieldRanges(DayOfWeek firstDayOfWeek, int minDays) {
    WeekFields weekDef = WeekFields.of(firstDayOfWeek, minDays);
    TemporalField womField = weekDef.weekOfMonth();
    TemporalField woyField = weekDef.weekOfYear();

    LocalDate day = LocalDate.of(2012, 11, 30);
    LocalDate endDay = LocalDate.of(2013, 1, 2);
    while (day.isBefore(endDay)) {
        LocalDate last = day.with(DAY_OF_MONTH, day.lengthOfMonth());
        int lastWOM = last.get(womField);
        LocalDate first = day.with(DAY_OF_MONTH, 1);
        int firstWOM = first.get(womField);
        ValueRange rangeWOM = day.range(womField);
        assertEquals("Range min should be same as WeekOfMonth for first day of month: "
                + first + ", " + weekDef, rangeWOM.getMinimum(), firstWOM);
        assertEquals("Range max should be same as WeekOfMonth for last day of month: "
                + last + ", " + weekDef, rangeWOM.getMaximum(), lastWOM);

        last = day.with(DAY_OF_YEAR, day.lengthOfYear());
        int lastWOY = last.get(woyField);
        first = day.with(DAY_OF_YEAR, 1);
        int firstWOY = first.get(woyField);
        ValueRange rangeWOY = day.range(woyField);
        assertEquals("Range min should be same as WeekOfYear for first day of Year: "
                + day + ", " + weekDef, rangeWOY.getMinimum(), firstWOY);
        assertEquals("Range max should be same as WeekOfYear for last day of Year: "
                + day + ", " + weekDef, rangeWOY.getMaximum(), lastWOY);

        day = day.plusDays(1);
    }
}
 
Example #18
Source File: EventManagerIntegrationTest.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testNewBoundedCategoryWithExistingBoundedAndPendingTicket() {
    List<TicketCategoryModification> categories = Collections.singletonList(
        new TicketCategoryModification(null, "default", AVAILABLE_SEATS,
            new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()),
            DESCRIPTION, BigDecimal.TEN, false, "", false, null, null, null, null, null, 0, null, null, AlfioMetadata.empty()));
    Pair<Event, String> pair = initEvent(categories, organizationRepository, userManager, eventManager, eventRepository);
    Event event = pair.getLeft();
    String username = pair.getRight();
    assertEquals(Integer.valueOf(AVAILABLE_SEATS), ticketRepository.countFreeTicketsForUnbounded(event.getId()));
    TicketReservationModification trm = new TicketReservationModification();
    trm.setAmount(1);
    trm.setTicketCategoryId(ticketCategoryRepository.findAllTicketCategories(event.getId()).get(0).getId());
    TicketReservationWithOptionalCodeModification reservation = new TicketReservationWithOptionalCodeModification(trm, Optional.empty());
    ticketReservationManager.createTicketReservation(event, Collections.singletonList(reservation), Collections.emptyList(),
        DateUtils.addDays(new Date(), 1), Optional.empty(), Locale.ENGLISH, false);
    TicketCategoryModification tcm = new TicketCategoryModification(null, "new", 1,
        DateTimeModification.fromZonedDateTime(ZonedDateTime.now()),
        DateTimeModification.fromZonedDateTime(ZonedDateTime.now().plusDays(1)),
        Collections.emptyMap(), BigDecimal.TEN, false, "", true, null, null, null, null, null, 0, null, null, AlfioMetadata.empty());
    Result<Integer> insertResult = eventManager.insertCategory(event, tcm, username);
    assertTrue(insertResult.isSuccess());
    Integer categoryID = insertResult.getData();
    tcm = new TicketCategoryModification(categoryID, tcm.getName(), AVAILABLE_SEATS,
        tcm.getInception(), tcm.getExpiration(), tcm.getDescription(), tcm.getPrice(), false, "", true, null, null, null, null, null, 0, null, null, AlfioMetadata.empty());
    Result<TicketCategory> result = eventManager.updateCategory(categoryID, event, tcm, username);
    assertFalse(result.isSuccess());
}
 
Example #19
Source File: TCKOffsetDateTime.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test(expected=NullPointerException.class)
public void constructor_nullOffset() throws Throwable  {
    Constructor<OffsetDateTime> con = OffsetDateTime.class.getDeclaredConstructor(LocalDateTime.class, ZoneOffset.class);
    con.setAccessible(true);
    try {
        con.newInstance(LocalDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30)), null);
    } catch (InvocationTargetException ex) {
        throw ex.getCause();
    }
}
 
Example #20
Source File: TestLocalDate.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="sampleMinusDaysSymmetry")
public void test_minusDays_symmetry(LocalDate reference) {
    for (int days = 0; days < 365 * 8; days++) {
        LocalDate t = reference.minusDays(days).minusDays(-days);
        assertEquals(t, reference);

        t = reference.minusDays(-days).minusDays(days);
        assertEquals(t, reference);
    }
}
 
Example #21
Source File: FxSwapCurveNode.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Override
public DatedParameterMetadata metadata(LocalDate valuationDate, ReferenceData refData) {
  LocalDate nodeDate = date(valuationDate, refData);
  if (date.isFixed()) {
    return LabelDateParameterMetadata.of(nodeDate, label);
  }
  Tenor tenor = Tenor.of(template.getPeriodToFar());
  return TenorDateParameterMetadata.of(nodeDate, tenor, label);
}
 
Example #22
Source File: TestLocalDate.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@DataProvider(name="sampleMinusDaysSymmetry")
Object[][] provider_sampleMinusDaysSymmetry() {
    return new Object[][] {
        {LocalDate.of(-1, 1, 1)},
        {LocalDate.of(-1, 2, 28)},
        {LocalDate.of(-1, 3, 1)},
        {LocalDate.of(-1, 12, 31)},
        {LocalDate.of(0, 1, 1)},
        {LocalDate.of(0, 2, 28)},
        {LocalDate.of(0, 2, 29)},
        {LocalDate.of(0, 3, 1)},
        {LocalDate.of(0, 12, 31)},
        {LocalDate.of(2007, 1, 1)},
        {LocalDate.of(2007, 2, 28)},
        {LocalDate.of(2007, 3, 1)},
        {LocalDate.of(2007, 12, 31)},
        {LocalDate.of(2008, 1, 1)},
        {LocalDate.of(2008, 2, 28)},
        {LocalDate.of(2008, 2, 29)},
        {LocalDate.of(2008, 3, 1)},
        {LocalDate.of(2008, 12, 31)},
        {LocalDate.of(2099, 1, 1)},
        {LocalDate.of(2099, 2, 28)},
        {LocalDate.of(2099, 3, 1)},
        {LocalDate.of(2099, 12, 31)},
        {LocalDate.of(2100, 1, 1)},
        {LocalDate.of(2100, 2, 28)},
        {LocalDate.of(2100, 3, 1)},
        {LocalDate.of(2100, 12, 31)},
    };
}
 
Example #23
Source File: BindParameterTypesTest.java    From pgadba with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void bindFutureDate() throws ExecutionException, InterruptedException, TimeoutException {
  LocalDate d = LocalDate.of(2018, 3, 12);
  CompletableFuture<LocalDate> f = CompletableFuture.supplyAsync(() -> d);

  try (Session session = ds.getSession()) {
    CompletionStage<LocalDate> idF = session.<LocalDate>rowOperation("select $1::date as t")
        .set("$1", f, PgAdbaType.DATE)
        .collect(singleCollector(LocalDate.class))
        .submit()
        .getCompletionStage();

    assertEquals(d, get10(idF));
  }
}
 
Example #24
Source File: TCKTemporalAdjusters.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_firstDayOfNextYear_leap() {
    for (Month month : Month.values()) {
        for (int i = 1; i <= month.length(true); i++) {
            LocalDate date = date(2008, month, i);
            LocalDate test = (LocalDate) TemporalAdjusters.firstDayOfNextYear().adjustInto(date);
            assertEquals(test.getYear(), 2009);
            assertEquals(test.getMonth(), JANUARY);
            assertEquals(test.getDayOfMonth(), 1);
        }
    }
}
 
Example #25
Source File: TCKWeekFields.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider="WeekBasedYearData")
public void test_weekBasedYears(WeekFields weekDef, int weekBasedYear,
        int weekOfWeekBasedYear, int dayOfWeek, LocalDate date) {
    TemporalField dowField = weekDef.dayOfWeek();
    TemporalField wowbyField = weekDef.weekOfWeekBasedYear();
    TemporalField yowbyField = weekDef.weekBasedYear();
    assertEquals(date.get(dowField), dayOfWeek, "DayOfWeek mismatch");
    assertEquals(date.get(wowbyField), weekOfWeekBasedYear, "Week of WeekBasedYear mismatch");
    assertEquals(date.get(yowbyField), weekBasedYear, "Year of WeekBasedYear mismatch");
}
 
Example #26
Source File: TestIsoChronology.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_date_withEra() {
    int year = 5;
    int month = 5;
    int dayOfMonth = 5;
    LocalDate test = IsoChronology.INSTANCE.date(IsoEra.BCE, year, month, dayOfMonth);
    assertEquals(test.getEra(), IsoEra.BCE);
    assertEquals(test.get(ChronoField.YEAR_OF_ERA), year);
    assertEquals(test.get(ChronoField.MONTH_OF_YEAR), month);
    assertEquals(test.get(ChronoField.DAY_OF_MONTH), dayOfMonth);

    assertEquals(test.get(YEAR), 1 + (-1 * year));
    assertEquals(test.get(ERA), 0);
    assertEquals(test.get(YEAR_OF_ERA), year);
}
 
Example #27
Source File: TCKTemporalAdjusters.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_lastDayOfYear_leap() {
    for (Month month : Month.values()) {
        for (int i = 1; i <= month.length(true); i++) {
            LocalDate date = date(2008, month, i);
            LocalDate test = (LocalDate) TemporalAdjusters.lastDayOfYear().adjustInto(date);
            assertEquals(test.getYear(), 2008);
            assertEquals(test.getMonth(), Month.DECEMBER);
            assertEquals(test.getDayOfMonth(), 31);
        }
    }
}
 
Example #28
Source File: JapaneseDate.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a {@code LocalGregorianCalendar.Date} converted from the given {@code isoDate}.
 *
 * @param isoDate  the local date, not null
 * @return a {@code LocalGregorianCalendar.Date}, not null
 */
private static LocalGregorianCalendar.Date toPrivateJapaneseDate(LocalDate isoDate) {
    LocalGregorianCalendar.Date jdate = JapaneseChronology.JCAL.newCalendarDate(null);
    sun.util.calendar.Era sunEra = JapaneseEra.privateEraFrom(isoDate);
    int year = isoDate.getYear();
    if (sunEra != null) {
        year -= sunEra.getSinceDate().getYear() - 1;
    }
    jdate.setEra(sunEra).setYear(year).setMonth(isoDate.getMonthValue()).setDayOfMonth(isoDate.getDayOfMonth());
    JapaneseChronology.JCAL.normalize(jdate);
    return jdate;
}
 
Example #29
Source File: SABRVolatilityCubeSharedParametersTest.java    From finmath-lib with Apache License 2.0 5 votes vote down vote up
@Test
public void a_cubeATM() {

	final ArrayList<Integer> maturities			= new ArrayList<>();
	final ArrayList<Integer> terminations			= new ArrayList<>();
	final ArrayList<Double> volatilitiesModel		= new ArrayList<>();
	final ArrayList<Double> volatilitiesMarket	= new ArrayList<>();

	for(final int maturity : physicalVolatilities.getMaturities(0)) {
		for(final int termination : physicalVolatilities.getTenors(0, maturity)) {

			final LocalDate maturityDate = referenceDate.plusMonths(maturity);
			final LocalDate terminationDate = maturityDate.plusMonths(termination);

			final Schedule floatSchedule = floatMetaSchedule.generateSchedule(referenceDate, maturityDate, terminationDate);
			final Schedule fixSchedule = fixMetaSchedule.generateSchedule(referenceDate, maturityDate, terminationDate);
			final double swapRate = Swap.getForwardSwapRate(fixSchedule, floatSchedule, model.getForwardCurve(forwardCurveName), model);

			try {
				final double volatility = cube.getValue(model, fixSchedule.getPayment(fixSchedule.getNumberOfPeriods()-1), fixSchedule.getFixing(0), swapRate,
						QuotingConvention.VOLATILITYNORMAL);
				maturities.add(maturity);
				terminations.add(termination);
				volatilitiesModel.add(volatility);
				volatilitiesMarket.add(physicalVolatilities.getValue(maturity, termination, 0));
			} catch (final Exception e) {
				maturities.add(maturity);
				terminations.add(termination);
				volatilitiesModel.add(0.0);
				volatilitiesMarket.add(physicalVolatilities.getValue(maturity, termination, 0));
			}
		}
	}

	final DataTableLight modelTable	= new DataTableLight("Volatilites-Model", TableConvention.MONTHS, maturities, terminations, volatilitiesModel);
	final DataTableLight marketTable	= new DataTableLight("Volatilites-Market", TableConvention.MONTHS, maturities, terminations, volatilitiesMarket);
	output.append(marketTable.toString()+"\n");
	output.append("\n"+modelTable.toString()+"\n\n\n\n");

}
 
Example #30
Source File: PatientValidator.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
@VisibleForTesting
static List<ValidationFinding> validateTreatments(@NotNull String patientIdentifier, @NotNull List<BiopsyTreatmentData> treatments) {
    List<ValidationFinding> findings = Lists.newArrayList();
    List<BiopsyTreatmentData> matchedTreatments =
            treatments.stream().filter(treatment -> treatment.biopsyId() != null).collect(Collectors.toList());
    matchedTreatments.forEach(treatment -> findings.addAll(validateTreatmentData(patientIdentifier, treatment)));
    Collections.sort(matchedTreatments);

    if (matchedTreatments.size() > 1) {
        for (int index = 1; index < matchedTreatments.size(); index++) {
            BiopsyTreatmentData currentTreatment = matchedTreatments.get(index);
            LocalDate startDate = currentTreatment.startDate();
            LocalDate previousTreatmentEnd = matchedTreatments.get(index - 1).endDate();
            if (startDate != null && (previousTreatmentEnd == null || startDate.isBefore(previousTreatmentEnd))) {
                findings.add(ValidationFinding.of(ECRF_LEVEL,
                        patientIdentifier,
                        "Subsequent treatment starts before the end of previous treatment",
                        currentTreatment.formStatus()));
            }
        }
        List<BiopsyTreatmentData> nonFinishedTreatments = matchedTreatments.stream()
                .filter(treatment -> treatment.startDate() != null)
                .filter(treatment -> treatment.endDate() == null)
                .collect(Collectors.toList());
        if (nonFinishedTreatments.size() > 1) {
            nonFinishedTreatments.forEach(treatment -> findings.add(ValidationFinding.of(ECRF_LEVEL,
                    patientIdentifier,
                    "End of at least 1 non-final treatment is missing",
                    treatment.formStatus())));
        }
    }
    return findings;
}