public static void main(String[] args) {

    Grados.usarJava8 = true;

    testConstructorNormal();
    testConstructorExcepcion();

    testSetEmailNormal();
    testSetEmailExcepcion();

    testMatriculaAsignatura();
    testMatriculaAsignaturaExcepcion();

    testEliminaAsignatura();
    testEliminaAsignaturaExcepcion();

    Alumno a1 =
        Grados.createAlumno(
            "12345678Z",
            "Juaan",
            "Nadie Nadie",
            LocalDate.of(1950, 3, 15),
            "*****@*****.**");
    Alumno a2 =
        Grados.createAlumno(
            "12345678Z", "Juan", "Nadie Nadie", LocalDate.of(1950, 3, 15), "*****@*****.**");
    System.out.println(a1.equals(a2));
    System.out.println(a1.compareTo(a2));
  }
  @Override
  public LocalDate deserialize(JsonParser parser, DeserializationContext context)
      throws IOException {
    switch (parser.getCurrentToken()) {
      case START_ARRAY:
        if (parser.nextToken() == JsonToken.END_ARRAY) {
          return null;
        }
        int year = parser.getIntValue();

        parser.nextToken();
        int month = parser.getIntValue();

        parser.nextToken();
        int day = parser.getIntValue();

        if (parser.nextToken() != JsonToken.END_ARRAY) {
          throw context.wrongTokenException(parser, JsonToken.END_ARRAY, "Expected array to end.");
        }
        return LocalDate.of(year, month, day);

      case VALUE_STRING:
        String string = parser.getText().trim();
        if (string.length() == 0) {
          return null;
        }
        return LocalDate.parse(string, ISO_DATE_OPTIONAL_TIME);
    }
    throw context.wrongTokenException(parser, JsonToken.START_ARRAY, "Expected array or string.");
  }
 @Override
 public boolean checkoutBook(String memberId, String isbn) throws LibrarySystemException {
   Book currentBook = searchBook(isbn);
   BookCopy[] book = currentBook.getCopies();
   for (BookCopy bc : book) {
     if (computeStatus(bc)) {
       DataAccessFacade dc = new DataAccessFacade();
       LocalDate currentDate = LocalDate.now();
       LocalDate dueDate = currentDate.plusDays(bc.getBook().getMaxCheckoutLength());
       CheckoutRecordEntry newCheckoutRecordEntry =
           new CheckoutRecordEntry(currentDate, dueDate, bc);
       LibraryMember member = search(memberId);
       CheckoutRecord rc = member.getCheckoutRecord();
       if (rc.getCheckoutRecordEntries() == null) {
         List<CheckoutRecordEntry> entries = new ArrayList<>();
         entries.add(newCheckoutRecordEntry);
         member.getCheckoutRecord().setCheckoutRecordEntries(entries);
       } else {
         member.getCheckoutRecord().getCheckoutRecordEntries().add(newCheckoutRecordEntry);
       }
       bc.changeAvailability();
       dc.updateMember(member);
       dc.saveNewBook(currentBook);
       return true;
     }
   }
   return false;
 }
  /**
   * Tests if birth date is valid. Validation separate from getter method to allow validation before
   * assigning ramq. Assumes birthdate cannot be equal to or over 100 years ago.
   *
   * @param date the date portion of the Ramq
   * @returns birthDate the birthdate in LocalDate form
   * @throws IllegalArgumentException
   */
  private LocalDate validateBirthdate(String date) throws IllegalArgumentException {
    LocalDate birthdate;

    int year = Integer.parseInt(date.substring(0, 2));
    int month = Integer.parseInt(date.substring(2, 4));
    int day = Integer.parseInt(date.substring(4));

    // If Ramq belongs to a female, removes 50 from birth month
    if (month > 50) {
      month = month - 50;
    }

    // Checks for which century birthdate belongs in
    // Difference of less than 2000 demonstrates that birth was in 1900s
    int currentYear = LocalDate.now().getYear();
    if ((currentYear - year) < 2000) {
      year = 1900 + year;
    } else {
      year = 2000 + year;
    }

    try {
      birthdate = LocalDate.of(year, month, day);
    } catch (DateTimeException dtpe) {
      throw new IllegalArgumentException(
          "Cannot identify date.  " + "Ramq is invalid.\n" + dtpe.getMessage());
    }

    return birthdate;
  }
  /** * Initialises the collection of entity information from the ICAT into the Dashboard. */
  private void initialiseEntityCollection() {

    LocalDate today = LocalDate.now();

    LOG.info("Data Collection initiated for " + today.toString());

    LocalDate earliestEntityImport = getNextImportDate("entity");
    LocalDate earliestInstrumentImport = getNextImportDate("instrument");
    LocalDate earliestInvestigationImport = getNextImportDate("investigation");

    // Import data into Dashboard even if the import script has never been run
    if (earliestEntityImport == null
        && earliestInstrumentImport == null
        && earliestInvestigationImport == null) {
      LocalDate past = LocalDate.now().minusWeeks(1);
      counter.performEntityCountCollection(past, today);
      counter.performInstrumentMetaCollection(past, today);
      counter.performInvestigationMetaCollection(past, today);
    }

    // An actual import has happened.
    if (earliestEntityImport != null) {
      counter.performEntityCountCollection(earliestEntityImport, today);
    }
    if (earliestInstrumentImport != null) {
      counter.performInstrumentMetaCollection(earliestInstrumentImport, today);
    }
    if (earliestInvestigationImport != null) {
      counter.performInvestigationMetaCollection(earliestInvestigationImport, today);
    }

    LOG.info("Data collection completed for " + today.toString());
  }
 public void test_toLeg_withSpread() {
   OvernightRateSwapLegConvention base =
       OvernightRateSwapLegConvention.builder().index(GBP_SONIA).accrualMethod(AVERAGED).build();
   LocalDate startDate = LocalDate.of(2015, 5, 5);
   LocalDate endDate = LocalDate.of(2020, 5, 5);
   RateCalculationSwapLeg test = base.toLeg(startDate, endDate, PAY, NOTIONAL_2M, 0.25d);
   RateCalculationSwapLeg expected =
       RateCalculationSwapLeg.builder()
           .payReceive(PAY)
           .accrualSchedule(
               PeriodicSchedule.builder()
                   .frequency(TERM)
                   .startDate(startDate)
                   .endDate(endDate)
                   .businessDayAdjustment(BDA_MOD_FOLLOW)
                   .build())
           .paymentSchedule(
               PaymentSchedule.builder()
                   .paymentFrequency(TERM)
                   .paymentDateOffset(DaysAdjustment.NONE)
                   .build())
           .notionalSchedule(NotionalSchedule.of(GBP, NOTIONAL_2M))
           .calculation(
               OvernightRateCalculation.builder()
                   .index(GBP_SONIA)
                   .accrualMethod(AVERAGED)
                   .spread(ValueSchedule.of(0.25d))
                   .build())
           .build();
   assertEquals(test, expected);
 }
  public void checkoutBook(String memberID, String bookCopyId) {

    // Get Library member's FULL object from file System
    LibraryMember lm = libraryMemberService.readLibraryMember(memberID);

    //
    CheckoutRecord checkoutRecord = lm.getRecord();

    // Get BookCopy which we are trying to checkout
    BookCopy bookCopy = BookCopy.getBookCopy(bookCopyId);

    // Get the Book Object
    Book book = Book.get(bookCopy.getISBN());

    // Current/ today's date
    LocalDate checkoutDate = LocalDate.now();

    // Duedate = current date PLUS no of days to lend
    LocalDate dueDate = checkoutDate.plusDays(book.getDaysOfLend());

    // Create a new checkout entry
    CheckoutEntry checkoutEntry = new CheckoutEntry(bookCopy, checkoutDate, dueDate, false);

    checkoutRecord.addEntry(checkoutEntry);
    lm.setRecord(checkoutRecord);

    lm.writeLibraryMember(lm);
  }
  @Test
  public void testThatTransferalsDoNotChangePerformance() {
    double[] delta = {0d, 0.023d, 0.043d, 0.02d, 0.05d, 0.08d, 0.1d, 0.04d, -0.05d};
    long[] transferals = {1000000, 0, 20000, -40000, 0, 0, 540000, -369704, 0};
    long[] transferals2 = {1000000, 0, 0, 0, 0, 0, 0, 0, 0};

    Client client = createClient(delta, transferals);

    ReportingPeriod.FromXtoY period =
        new ReportingPeriod.FromXtoY(
            LocalDate.of(2012, Month.JANUARY, 1), //
            LocalDate.of(2012, Month.JANUARY, 9));
    CurrencyConverter converter = new TestCurrencyConverter();
    ClientIndex index =
        PerformanceIndex.forClient(client, converter, period, new ArrayList<Exception>());

    double[] accumulated = index.getAccumulatedPercentage();
    for (int ii = 0; ii < accumulated.length; ii++)
      assertThat(accumulated[ii], IsCloseTo.closeTo(delta[ii], PRECISION));

    Client anotherClient = createClient(delta, transferals2);
    index =
        PerformanceIndex.forClient(anotherClient, converter, period, new ArrayList<Exception>());

    accumulated = index.getAccumulatedPercentage();
    for (int ii = 0; ii < accumulated.length; ii++)
      assertThat(accumulated[ii], IsCloseTo.closeTo(delta[ii], PRECISION));
  }
  @Test
  public void testThatInterstWithoutInvestmentDoesNotCorruptResultAndIsReported() {
    Client client = new Client();
    new AccountBuilder() //
        .interest("2012-01-02", 100) //
        .addTo(client);

    ReportingPeriod.FromXtoY period =
        new ReportingPeriod.FromXtoY(
            LocalDate.of(2012, Month.JANUARY, 1), //
            LocalDate.of(2012, Month.JANUARY, 9));

    List<Exception> errors = new ArrayList<Exception>();
    CurrencyConverter converter = new TestCurrencyConverter();
    ClientIndex index = PerformanceIndex.forClient(client, converter, period, errors);

    double[] accumulated = index.getAccumulatedPercentage();
    for (int ii = 0; ii < accumulated.length; ii++)
      assertThat(accumulated[ii], IsCloseTo.closeTo(0d, PRECISION));

    assertThat(errors.size(), is(1));
    assertThat(
        errors.get(0).getMessage(),
        startsWith(
            Messages.MsgDeltaWithoutAssets.substring(
                0, Messages.MsgDeltaWithoutAssets.indexOf('{'))));
  }
  @Test
  public void testMaybeOverride_countertest() {

    Cook p1 = createPerson("a", newHashSet(THURSDAY), newHashSet());
    Cook p2 = createPerson("b", newHashSet(FRIDAY), newHashSet());
    Cook p3 = createPerson("c", newHashSet(MONDAY), newHashSet());

    // FRIDAYs instead of THURSDAYS
    CookingDay c1 = new CookingDay(p1, LocalDate.of(2015, 7, 3));
    CookingDay c2 = new CookingDay(p1, LocalDate.of(2015, 7, 10));
    CookingDay c3 = new CookingDay(p1, LocalDate.of(2015, 7, 17));

    // THURSDAYs instead of FRIDAYS
    CookingDay c4 = new CookingDay(p2, LocalDate.of(2015, 7, 2));
    CookingDay c5 = new CookingDay(p2, LocalDate.of(2015, 7, 9));
    CookingDay c6 = new CookingDay(p2, LocalDate.of(2015, 7, 16));

    // THUESDAYs instead of Mondays
    CookingDay c7 = new CookingDay(p3, LocalDate.of(2015, 6, 30));
    CookingDay c8 = new CookingDay(p3, LocalDate.of(2015, 7, 7));
    CookingDay c9 = new CookingDay(p3, LocalDate.of(2015, 7, 14));

    kl =
        new CookingListImpl(
            Arrays.asList(p1, p2, p3), Arrays.asList(c1, c2, c3, c4, c5, c6, c7, c8, c9));

    // Monday
    CookingDay day = kl.determineCookFor(LocalDate.of(2015, 9, 10));

    assertThat(day.getCook(), is(p1));
  }
Exemple #11
0
  private Client createClient(double[] delta, long[] transferals) {
    Client client = new Client();

    AccountBuilder account = new AccountBuilder();

    LocalDate time = LocalDate.parse("2012-01-01");

    long valuation = 0;
    double quote = 1;
    for (int ii = 0; ii < delta.length; ii++) {
      long v = (long) Math.round((double) valuation * (delta[ii] + 1) / quote);
      long d = v - valuation;

      if (transferals[ii] > 0) account.deposit_(time, transferals[ii]);
      else if (transferals[ii] < 0) account.withdraw(time, Math.abs(transferals[ii]));

      if (v > 0) account.interest(time, d);
      else if (v < 0) account.fees____(time, Math.abs(d));

      valuation = v + transferals[ii];

      quote = 1 + delta[ii];

      time = time.plusDays(1);
    }

    account.addTo(client);
    return client;
  }
  private void setDiscount(boolean discount, Data data) {
    double totalPrice = bill.getTotalPrice();
    LocalDate date = data.getDate();
    if ((date.equals(hollidayChristmas))
        || (date.equals(hollidayIndepenanceDay))
        || (date.equals(hollidayProgrammerDay))) {
      totalPrice *= 0.5;
      bill.setTotalPrice(totalPrice);
      discount = false;
      logger.info(resourceBundle.getString("economyHollidays") + bill.getTotalPrice());
      bill.setHollidays(
          resourceBundle.getString("economyHollidays")
              + String.format(" %.2f ", bill.getTotalPrice()));
    } else {
      logger.info(resourceBundle.getString("noEconomy"));
      bill.setHollidays(resourceBundle.getString("noEconomy"));
    }

    if (discount == true) {
      double discountPay = bill.getTotalPrice() * 0.1;
      totalPrice *= 0.9;
      bill.setTotalPrice(totalPrice);
      logger.info(resourceBundle.getString("yourDiscount") + discountPay);
      bill.setDiscount(
          resourceBundle.getString("yourDiscount") + " " + String.format(" %.2f ", discountPay));
    } else if (discount == false) {
      totalPrice *= 1;
      bill.setTotalPrice(totalPrice);
      logger.info(resourceBundle.getString("noDiscount"));
      bill.setDiscount(resourceBundle.getString("noDiscount"));
    }
  }
  public static Date substract(Date awal, int i) {
    LocalDate localDate = awal.toLocalDate();

    LocalDate newDate = localDate.minusDays(i);

    return toDate(newDate);
  }
  public static Date add(Date awal, int i) {
    LocalDate localDate = awal.toLocalDate();

    LocalDate newDate = localDate.plusDays(i);

    return toDate(newDate);
  }
  private List<ReportEntry> fillForEmptyPeriods(
      List<ReportEntry> inputEntries, Pair<LocalDate, LocalDate> interval) {
    Optional<String> aRosterTypeCode =
        inputEntries.stream().map(ReportEntry::getRosterTypeCode).findAny();

    if (!aRosterTypeCode.isPresent()) {
      return inputEntries;
    }
    List<ReportEntry> result = inputEntries.stream().collect(Collectors.toList());

    for (LocalDate period = interval.getLeft();
        period.isBefore(interval.getRight());
        period = period.plusMonths(1)) {
      result.add(
          new ReportEntry(
              beneficiary,
              aRosterTypeCode.get(),
              AmountType.PAYMENT,
              YearMonth.from(period),
              BigDecimal.ZERO));
      result.add(
          new ReportEntry(
              beneficiary, "UNKNOWN", AmountType.REFUND, YearMonth.from(period), BigDecimal.ZERO));
    }
    return result;
  }
Exemple #16
0
  @Test
  public void testExcelSampleAggregatedWeekly() {
    // first day of week is locale dependent
    Locale locale = Locale.getDefault();
    Locale.setDefault(Locale.GERMAN);

    try {
      Client client = createClient();

      ReportingPeriod.FromXtoY reportInterval =
          new ReportingPeriod.FromXtoY( //
              LocalDate.of(2011, Month.DECEMBER, 31), LocalDate.of(2012, Month.JANUARY, 8));
      CurrencyConverter converter = new TestCurrencyConverter();
      PerformanceIndex index =
          PerformanceIndex.forClient(client, converter, reportInterval, new ArrayList<Exception>());

      index = Aggregation.aggregate(index, Aggregation.Period.WEEKLY);

      assertNotNull(index);

      double[] delta = index.getDeltaPercentage();
      assertThat(delta.length, is(2));
      assertThat(delta[0], IsCloseTo.closeTo(0.023d, PRECISION));
      assertThat(delta[1], IsCloseTo.closeTo(-0.0713587d, PRECISION));

      double[] accumulated = index.getAccumulatedPercentage();
      assertThat(accumulated[0], IsCloseTo.closeTo(0.023d, PRECISION));
      assertThat(accumulated[1], IsCloseTo.closeTo(-0.05d, PRECISION));
    } finally {
      Locale.setDefault(locale);
    }
  }
 // -----------------------------------------------------------------------
 // isSupportedBy(TemporalAccessor temporal) and getFrom(TemporalAccessor temporal)
 // -----------------------------------------------------------------------
 @DataProvider(name = "fieldAndAccessor")
 Object[][] data_fieldAndAccessor() {
   return new Object[][] {
     {YEAR, LocalDate.of(2000, 2, 29), true, 2000},
     {YEAR, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 2000},
     {MONTH_OF_YEAR, LocalDate.of(2000, 2, 29), true, 2},
     {MONTH_OF_YEAR, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 2},
     {DAY_OF_MONTH, LocalDate.of(2000, 2, 29), true, 29},
     {DAY_OF_MONTH, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 29},
     {DAY_OF_YEAR, LocalDate.of(2000, 2, 29), true, 60},
     {DAY_OF_YEAR, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 60},
     {HOUR_OF_DAY, LocalTime.of(5, 4, 3, 200), true, 5},
     {HOUR_OF_DAY, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 5},
     {MINUTE_OF_DAY, LocalTime.of(5, 4, 3, 200), true, 5 * 60 + 4},
     {MINUTE_OF_DAY, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 5 * 60 + 4},
     {MINUTE_OF_HOUR, LocalTime.of(5, 4, 3, 200), true, 4},
     {MINUTE_OF_HOUR, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 4},
     {SECOND_OF_DAY, LocalTime.of(5, 4, 3, 200), true, 5 * 3600 + 4 * 60 + 3},
     {SECOND_OF_DAY, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 5 * 3600 + 4 * 60 + 3},
     {SECOND_OF_MINUTE, LocalTime.of(5, 4, 3, 200), true, 3},
     {SECOND_OF_MINUTE, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 3},
     {NANO_OF_SECOND, LocalTime.of(5, 4, 3, 200), true, 200},
     {NANO_OF_SECOND, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 200},
     {YEAR, LocalTime.of(5, 4, 3, 200), false, -1},
     {MONTH_OF_YEAR, LocalTime.of(5, 4, 3, 200), false, -1},
     {DAY_OF_MONTH, LocalTime.of(5, 4, 3, 200), false, -1},
     {DAY_OF_YEAR, LocalTime.of(5, 4, 3, 200), false, -1},
     {HOUR_OF_DAY, LocalDate.of(2000, 2, 29), false, -1},
     {MINUTE_OF_DAY, LocalDate.of(2000, 2, 29), false, -1},
     {MINUTE_OF_HOUR, LocalDate.of(2000, 2, 29), false, -1},
     {SECOND_OF_DAY, LocalDate.of(2000, 2, 29), false, -1},
     {SECOND_OF_MINUTE, LocalDate.of(2000, 2, 29), false, -1},
     {NANO_OF_SECOND, LocalDate.of(2000, 2, 29), false, -1},
   };
 }
  @Test
  public void test() {
    Cliente c1 = new Cliente();

    c1.setStatus(1);
    c1.setTipopessoa(2);
    c1.setSexo(1);
    c1.setDatanascimento(LocalDate.now());
    c1.setNomerazao("");
    c1.setCpfcnpj("");
    c1.setRgie("");
    c1.setEndereco("");
    c1.setNumero("54");
    c1.setComplemento("10");
    c1.setBairro("");
    c1.setEstado(3);
    c1.setCidade(3);
    c1.setCep("3678000");
    c1.setTel("");
    c1.setCel("");
    c1.setEmail("*****@*****.**");
    c1.setSite("teste");
    c1.setClientedesde(LocalDate.now());
    c1.setObs("teste");

    ClienteDao dao = new ClienteDao();
    Boolean b = true;
    try {
      assertEquals(b, dao.inserir(c1));
    } catch (Exception e) {
      // Todo Auto-generated catch block
      e.printStackTrace();
    }
  }
  void saveNewJobsByDate(String folderPath, String printerName)
      throws ClientProtocolException, IOException, ParseJobException {

    List<JobDetail> toSave = new ArrayList<JobDetail>();
    int getJobsFrom;

    String latestLog = LogFiles.getMostRecentLogFileName(folderPath, printerName);

    if (latestLog != null) {
      JobDetailCSV l2csv = new JobDetailCSV(latestLog);

      // We'll be resaving the latest csv as it may have new jobs
      toSave = l2csv.readCSV();

      getJobsFrom = LogFiles.getLastSavedJob(folderPath, printerName).getJobNumber();
    } else {
      getJobsFrom = 0;
    }

    List<JobDetail> newJobs = printer.getJobsSinceJobNumber(getJobsFrom);

    toSave.addAll(newJobs);

    LogFiles.sortJobsByNumber(toSave);

    TreeMap<LocalDate, List<JobDetail>> sorted = LogFiles.splitJobsByDate(toSave);

    for (LocalDate day : sorted.keySet()) {

      JobDetailCSV jd =
          new JobDetailCSV(csvFolder + "/" + printer.getPrinterName() + day.toString());
      jd.write(sorted.get(day));
    }
  }
Exemple #20
0
  @Test
  public void testBasic() {
    System.out.println(Year.now());
    System.out.println(Year.of(2015));
    System.out.println(Year.isLeap(2016));

    Locale locale = Locale.getDefault();
    System.out.println(Month.DECEMBER.getDisplayName(TextStyle.FULL, locale));
    System.out.println(Month.DECEMBER.getDisplayName(TextStyle.SHORT, locale));
    System.out.println(Month.DECEMBER.getDisplayName(TextStyle.NARROW, locale));
    System.out.println(Month.DECEMBER.getDisplayName(TextStyle.FULL_STANDALONE, locale));
    System.out.println(Month.of(8).ordinal());
    System.out.println(Month.AUGUST.minus(2));

    System.out.println(YearMonth.now());
    System.out.println(MonthDay.now());

    System.out.println(DayOfWeek.FRIDAY.plus(2));
    System.out.println(DayOfWeek.of(1));
    System.out.println(
        DayOfWeek.from(LocalDateTime.ofInstant(Instant.now(), ZoneId.systemDefault())));

    System.out.println(Period.between(Year.now().atDay(1), LocalDate.now()));
    System.out.println(ChronoUnit.DAYS.between(Year.now().atDay(1), LocalDate.now()));
  }
  @Test
  public void testGenerateScheduleInterestOnlyMonthly() {
    AmortizationAttributes amAttrs = generateAmortizationAttributesObjectTemplate();
    amAttrs.setLoanAmount(ofUSD(10000));
    amAttrs.setInterestRateAsPercent(10.);
    amAttrs.setInterestOnly(true);
    amAttrs.setPaymentFrequency(TimePeriod.Monthly.getPeriodsPerYear());
    int termInMonths = 12;
    amAttrs.setTermInMonths(termInMonths);
    amAttrs.setAdjustmentDate(LocalDate.of(2016, Month.JANUARY, 1));
    amAttrs.setRegularPayment(ofUSD(0));

    List<ScheduledPayment> schedule = AmortizationCalculator.generateSchedule(amAttrs);
    assertEquals("Interest only schedule term in months", termInMonths, schedule.size());

    MonetaryAmount expectedInterest = ofUSD(83.34);
    MonetaryAmount expectedPrincipal = ofUSD(0);
    LocalDate expectedDate = amAttrs.getAdjustmentDate();
    int index = 0;

    for (ScheduledPayment payment : schedule) {
      expectedDate = expectedDate.plusMonths(1L);
      assertEquals("Interest only schedule payment number", ++index, payment.getPaymentNumber());
      assertEquals("Interest only schedule payment date", expectedDate, payment.getPaymentDate());
      assertEquals(
          "Interest only schedule payment interest", expectedInterest, payment.getInterest());
      assertEquals(
          "Interest only schedule payment principal", expectedPrincipal, payment.getPrincipal());
      assertEquals(
          "Interest only schedule payment total payment", expectedInterest, payment.getPayment());
      assertEquals(
          "Interest only schedule payment loan principal", ofUSD(10000), payment.getBalance());
    }
  }
Exemple #22
0
 @Test
 public void testLocalDate() {
   System.out.println(LocalDate.now());
   System.out.println(LocalDate.ofYearDay(2015, 300));
   System.out.println(LocalDate.now().atStartOfDay());
   System.out.println(LocalDate.now().atTime(12, 20));
 }
  /**
   * Checks to see if there have been any failed imports. If any are found then they are sent to be
   * re-done.
   */
  public void checkForFailedImports() {
    LOG.info("Check for missed data collections.");
    TypedQuery<ImportCheck> failedImportQuery =
        manager.createQuery("SELECT ic FROM ImportCheck ic WHERE ic.passed = 0", ImportCheck.class);

    List<ImportCheck> failedImports = failedImportQuery.getResultList();

    if (!failedImports.isEmpty()) {

      for (ImportCheck ic : failedImports) {

        String type = ic.getType();
        LocalDate failedDate = convertToLocalDate(ic.getCheckDate());

        LOG.info("Found a failed import for " + type + " on the " + failedDate.toString());

        if ("instrument".equals(type)) {
          counter.performInstrumentMetaCollection(failedDate, failedDate.plusDays(1));
        } else if ("investigation".equals(type)) {
          counter.performInvestigationMetaCollection(failedDate, failedDate.plusDays(1));

        } else if ("entity".equals(type)) {
          counter.performEntityCountCollection(failedDate, failedDate.plusDays(1));
        }
      }
    }
    LOG.info("Finished checking for missed data collections.");
  }
 @Test
 public void testGetFullAge4LocalDate() {
   int currentYear = LocalDate.now().getYear();
   int birthYear = 2010;
   LocalDate birthDate = LocalDate.of(birthYear, 1, 1);
   Assert.assertEquals(currentYear - birthYear, AgeUtils.getFullAge(birthDate));
 }
  /**
   * Map a ComputerDTo to a Computer.
   *
   * @param dto the ComputerDTO to map
   * @return the dto as a computer
   */
  public Computer toComputer(ComputerDto dto) {

    DateTimeFormatter formatter =
        DateTimeFormatter.ofPattern(
            messageSource.getMessage("app.formatDate", null, Locale.getDefault()));
    LocalDate introduced = null;
    LocalDate discontinued = null;

    if (null != dto.getIntroduced() && !dto.getIntroduced().isEmpty()) {
      introduced = LocalDate.parse(dto.getIntroduced(), formatter);
    }
    if (null != dto.getDiscontinued() && !dto.getDiscontinued().isEmpty()) {
      discontinued = LocalDate.parse(dto.getDiscontinued(), formatter);
    }
    Company company = null;
    if (dto.getCompanyId() != 0) {
      company = new Company(dto.getCompanyId(), dto.getCompanyName());
    }

    return new Computer.ComputerBuilder(dto.getName())
        .id(dto.getId())
        .company(company)
        .introduced(introduced)
        .discontinued(discontinued)
        .build();
  }
  public Order(
      User user,
      LocalDate createdAtDate,
      LocalTime createdAtTime,
      LocalDate serveAtDate,
      LocalTime serveAtTime,
      String orderNumber,
      String desc)
      throws NullPointerException {
    this.createdDate = createdAtDate;
    this.createdTime = createdAtTime;
    this.user = user;
    createdTime = LocalTime.now();
    this.serveAtDate = serveAtDate;
    this.serveAtTime = serveAtTime;
    this.description = desc;
    orderedMeals = new ArrayList<>();
    number = orderNumber;

    sspCreatedDate = new SimpleStringProperty(createdDate.toString());
    sspCreatedTime = new SimpleStringProperty(createdTime.toString());
    sspOrderedMeals = new SimpleStringProperty();
    sspUserName = new SimpleStringProperty(this.user.getUserName().get());
    sspNumber = new SimpleStringProperty(number.toString());
    sspServeAtDate = new SimpleStringProperty(serveAtDate.toString());
    sspServeAtTime = new SimpleStringProperty(serveAtTime.toString());
    sspPrice = new SimpleStringProperty();
    sspDescription = new SimpleStringProperty(description);

    sspCreatedAtCompact =
        new SimpleStringProperty(createdDate.toString() + " " + createdTime.toString());
    sspServeAtCompact =
        new SimpleStringProperty(serveAtDate.toString() + " " + serveAtTime.toString());
  }
public class DateComparisonUsingLocalDate {

  LocalDate now = LocalDate.now();
  String beginningOfMonth =
      now.withDayOfMonth(1).format(DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US));
  String today = now.format(DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US));
  String yesterday = now.minusDays(1).format(DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US));
  SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");

  void checkIfSameDay() throws Exception {
    String startDateStr = "03/03/2011";
    String endDateStr = "03/03/2011";
    Date endDate = formatter.parse(endDateStr);

    boolean isSameDay;
    isSameDay =
        DateUtils.isSameDay(formatter.parse(beginningOfMonth), formatter.parse(startDateStr));
    System.out.println("==1==" + isSameDay);
    isSameDay = DateUtils.isSameDay(formatter.parse(yesterday), endDate);
    System.out.println("==2==" + isSameDay);

    isSameDay = DateUtils.isSameDay(formatter.parse(yesterday), formatter.parse(startDateStr));
    System.out.println("==3==" + isSameDay);
    isSameDay = DateUtils.isSameDay(formatter.parse(yesterday), endDate);
    System.out.println("==4==" + isSameDay);
  }
}
  @SuppressWarnings("unchecked")
  @Override
  public void readExternal(ObjectInput arg0) throws IOException, ClassNotFoundException {
    createdDate = (LocalDate) arg0.readObject();
    createdTime = (LocalTime) arg0.readObject();
    user = (User) arg0.readObject();
    serveAtDate = (LocalDate) arg0.readObject();
    serveAtTime = (LocalTime) arg0.readObject();
    active = (boolean) arg0.readObject();
    number = (String) arg0.readObject();
    orderedMeals = (ArrayList<MealAndQuantity>) arg0.readObject();

    sspCreatedDate = new SimpleStringProperty(createdDate.toString());
    sspCreatedTime = new SimpleStringProperty(createdTime.toString());
    sspOrderedMeals = new SimpleStringProperty();
    sspUserName = new SimpleStringProperty(user.getUserName().get());
    sspNumber = new SimpleStringProperty(number.toString());
    sspServeAtDate = new SimpleStringProperty(serveAtDate.toString());
    sspServeAtTime = new SimpleStringProperty(serveAtTime.toString());
    sspPrice = new SimpleStringProperty();

    sspCreatedAtCompact =
        new SimpleStringProperty(createdDate.toString() + " " + createdTime.toString());
    sspServeAtCompact =
        new SimpleStringProperty(serveAtDate.toString() + " " + serveAtTime.toString());
  }
  @RequestMapping(value = "/api/cacheFlightSearch", method = RequestMethod.GET)
  public String cacheFlightSearch(
      @RequestParam("departureDate") String departureDate,
      @RequestParam("departureAirport") String departureAirport) {

    DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ISO_DATE;

    LocalDate depDate = LocalDate.parse(departureDate, DATE_FORMAT);
    LocalDate returnDate = depDate.plusDays(7);

    String retDate = returnDate.format(DATE_FORMAT);

    List<Destination> destinations = new Destinations().getDestinations();

    for (Destination destination : destinations) {

      String arrivalAirportCode = destination.getAirportCodes().get(0);

      System.out.println(
          "Getting best flight price for destination: "
              + arrivalAirportCode
              + ","
              + destination.getCity());

      flightSearchService.getFlights(departureDate, departureAirport, arrivalAirportCode, retDate);

      System.out.println(
          "Finished processing best flight price for destination: "
              + arrivalAirportCode
              + ","
              + destination.getCity());
    }

    return "success";
  }
 @Test
 public void test1() {
   final LocalDate startDate = LocalDate.of(2000, 1, 1);
   final LocalDate endDate = LocalDate.of(2002, 2, 9);
   final int months = 25;
   final LocalDate[] forward = CALCULATOR.getSchedule(startDate, endDate, false, true);
   assertEquals(forward.length, months);
   final LocalDate firstDate = LocalDate.of(2000, 1, 31);
   assertEquals(forward[0], firstDate);
   final LocalDate lastDate = LocalDate.of(2002, 1, 31);
   assertEquals(forward[months - 1], lastDate);
   LocalDate d1;
   for (int i = 1; i < months; i++) {
     d1 = forward[i];
     if (d1.getYear() == forward[i - 1].getYear()) {
       assertEquals(d1.getMonthValue() - forward[i - 1].getMonthValue(), 1);
     } else {
       assertEquals(d1.getMonthValue() - forward[i - 1].getMonthValue(), -11);
     }
     assertEquals(d1.getDayOfMonth(), d1.lengthOfMonth());
   }
   assertArrayEquals(CALCULATOR.getSchedule(startDate, endDate, true, false), forward);
   assertArrayEquals(CALCULATOR.getSchedule(startDate, endDate, true, true), forward);
   assertArrayEquals(CALCULATOR.getSchedule(startDate, endDate, false, false), forward);
   assertArrayEquals(CALCULATOR.getSchedule(startDate, endDate, false, true), forward);
   assertArrayEquals(CALCULATOR.getSchedule(startDate, endDate), forward);
 }