Пример #1
0
 public static LocalDate nextWeekDay(LocalDate localDate) {
   localDate = localDate.plusDays(1);
   while (isWeekend(localDate)) {
     localDate = localDate.plusDays(1);
   }
   return localDate;
 }
Пример #2
0
  /**
   * 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.");
  }
Пример #3
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;
  }
  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);
  }
Пример #5
0
  /**
   * Make a set of standard CDS represented as a MultiCdsAnalytic instance. The maturities of the
   * CDS are measured from the next IMM date (after the trade date), and the tenors are the given
   * matIndices multiplied by the coupon interval (3 months).
   *
   * @param tradeDate the trade date
   * @param accStartDate the accrual start date
   * @param matIndices the CDS tenors are these multiplied by the coupon interval (3 months)
   * @return a set of CDS represented as a MultiCdsAnalytic
   */
  public MultiCdsAnalytic makeMultiImmCds(
      LocalDate tradeDate, LocalDate accStartDate, int[] matIndices) {
    if (!_couponInterval.equals(DEFAULT_COUPON_INT)) {
      throw new IllegalArgumentException(
          "coupon interval must be 3M for this method. However it is set to "
              + _couponInterval.toString());
    }
    ArgChecker.notNull(tradeDate, "tradeDate");
    ArgChecker.notEmpty(matIndices, "matIndicies");

    LocalDate nextIMM = ImmDateLogic.getNextIMMDate(tradeDate);
    LocalDate stepinDate = tradeDate.plusDays(_stepIn);
    LocalDate valueDate = addWorkDays(tradeDate, _cashSettle, _calendar);

    return new MultiCdsAnalytic(
        tradeDate,
        stepinDate,
        valueDate,
        accStartDate,
        nextIMM,
        matIndices,
        _payAccOnDefault,
        _couponIntervalTenor,
        _stubType,
        _protectStart,
        _recoveryRate,
        _businessdayAdjustmentConvention,
        DEFAULT_CALENDAR,
        _accrualDayCount,
        _curveDayCount);
  }
Пример #6
0
  public static Date add(Date awal, int i) {
    LocalDate localDate = awal.toLocalDate();

    LocalDate newDate = localDate.plusDays(i);

    return toDate(newDate);
  }
Пример #7
0
 @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;
 }
Пример #8
0
  @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";
  }
Пример #9
0
  public Map<LocalDate, BigDecimal> getPlannedIncomePerDay(
      LocalDate dateFrom, LocalDate dateTo, ObservableList<Category> categories) {
    Map<LocalDate, BigDecimal> income = new TreeMap<>(Collections.reverseOrder());
    List<PlannedTransaction> transactions = getPlannedTransactions(dateFrom, dateTo, categories);
    for (LocalDate iterDate = dateTo;
        iterDate.isAfter(dateFrom.minusDays(1));
        iterDate = iterDate.minusDays(1)) {
      List<PlannedTransaction> transactionList = new LinkedList<>();
      for (PlannedTransaction transaction : transactions) {
        if (transaction.getDate().isAfter(iterDate.minusDays(1))
            && transaction.getDate().isBefore(iterDate.plusDays(1))) {
          transactionList.add(transaction);
        }
      }
      BigDecimal value =
          transactionList
              .stream()
              .filter(a -> a.getValue().compareTo(BigDecimal.ZERO) == 1)
              .map(a -> a.getValue().abs())
              .reduce(BigDecimal.ZERO, BigDecimal::add);

      if (value.compareTo(BigDecimal.ZERO) > 0) income.put(iterDate, value);
    }

    return income;
  }
Пример #10
0
  public Map<LocalDate, BigDecimal> getIncomePerDay(
      LocalDate dateFrom, LocalDate dateTo, List<Account> accounts, List<Category> categories) {
    Map<LocalDate, BigDecimal> income = new TreeMap<>(Collections.reverseOrder());
    List<ExternalTransaction> transactions =
        getTransactions(dateFrom, dateTo, accounts, categories);
    for (LocalDate iterDate = dateTo;
        iterDate.isAfter(dateFrom.minusDays(1));
        iterDate = iterDate.minusDays(1)) {
      List<ExternalTransaction> transactionList = new LinkedList<>();
      for (ExternalTransaction transaction : transactions) {
        if ((compareDates(transaction.dateProperty().get(), iterDate.minusDays(1)) == 1)
            && (compareDates(transaction.dateProperty().get(), iterDate.plusDays(1)) == -1)) {
          transactionList.add(transaction);
        }
      }
      BigDecimal value =
          transactionList
              .stream()
              .filter(a -> a.deltaProperty().get().compareTo(BigDecimal.ZERO) == 1)
              .map(a -> a.deltaProperty().get().abs())
              .reduce(BigDecimal.ZERO, BigDecimal::add);

      if (value.compareTo(BigDecimal.ZERO) > 0) income.put(iterDate, value);
    }

    return income;
  }
  public static void main(String[] args) {
    LocalDate today = LocalDate.now(); // Today’s date
    System.out.println("TODAY: " + today);

    /*String strDate = today.plusWeeks(1).toString(); // 2015-09-01
    String day;
    if (strDate.substring(8, 9).matches("0")) {
        day = strDate.substring(9);
        System.out.println("DAY IS: " + day);
    } else {
        day = strDate.substring(8);
        System.out.println("DAY IS: " + day);
    }*/

    int dayOfMonth = today.plusDays(4).getDayOfMonth();
    System.out.println("DAY OF MONTH: " + dayOfMonth);

    LocalDate localDate = LocalDate.of(2015, Month.valueOf("OCTOBER"), 25);
    System.out.println("LOCAL DATE: " + localDate);

    long toDays = Duration.between(localDate.atTime(0, 0), today.atTime(0, 0)).toDays();
    System.out.println("TO DAYS: " + toDays);
    Duration toDays23 = Duration.between(localDate, today);
    System.out.println("TO DAYS: " + toDays23);

    Month month = today.getMonth();
    //        localDate.
    System.out.println("Month " + month.toString());
    String displayName = month.getDisplayName(TextStyle.FULL, Locale.CANADA);
    System.out.println("DISPLAY NAME: " + displayName);

    LocalDate alonzosBirthday = LocalDate.of(1903, 6, 14);
    alonzosBirthday = LocalDate.of(1903, Month.JUNE, 14);
    // Uses the Month enumeration
    System.out.println("alonzosBirthday: " + alonzosBirthday);

    LocalDate programmersDay = LocalDate.of(2015, 1, 1).plusDays(255);
    // September 13, but in a leap year it would be September 12
    System.out.println("programmersDay: " + programmersDay);

    LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);
    LocalDate christmas = LocalDate.of(2014, Month.DECEMBER, 25);

    System.out.println("Until christmas: " + independenceDay.until(christmas));
    System.out.println(
        "Until christmas (with crono): " + independenceDay.until(christmas, ChronoUnit.DAYS));

    System.out.println(LocalDate.of(2016, 1, 31).plusMonths(1));
    System.out.println(LocalDate.of(2016, 3, 31).minusMonths(1));

    DayOfWeek startOfLastMillennium = LocalDate.of(1900, 1, 1).getDayOfWeek();
    System.out.println("startOfLastMillennium: " + startOfLastMillennium);
    System.out.println(startOfLastMillennium.getValue());
    System.out.println(DayOfWeek.SATURDAY.plus(3));
  }
Пример #12
0
  @RequestMapping(value = "/api/suggestion", method = RequestMethod.GET)
  public Map<String, FlightSuggestion> getFlight(
      @RequestParam("user") String userID,
      @RequestParam("departureAirportCode") String departureAirportCode,
      @RequestParam("departureAirportCity") String departureAirportCity,
      @RequestParam("departureDate") String date) {

    // The imageService and cruiseSuggestionService calls should happen from withing the
    // flightSuggestionService, but for now are here
    LocalDate departureDate = LocalDate.parse(date, DATE_FORMAT);
    LocalDate returnDate = departureDate.plusDays(7);

    String[] strArray = {"suggested", "followingIfLiked", "followingIfDisliked"};

    Map<String, FlightSuggestion> flightSuggestions = new LinkedHashMap<>();

    String depDate = departureDate.format(DATE_FORMAT);
    String retDate = returnDate.format(DATE_FORMAT);
    String displayDepDate = departureDate.format(DISPLAY_DATE_FORMAT);
    String displayRetDate = returnDate.format(DISPLAY_DATE_FORMAT);

    Map<String, Suggestion> suggestions =
        destinationSuggestionService.getNextDestination(userID, departureAirportCity);

    for (String key : suggestions.keySet()) {
      Suggestion suggestion = suggestions.get(key);

      Flights flights =
          flightSearchService.getFlights(
              depDate, departureAirportCode, suggestion.getAirportCodes().get(0), retDate);

      DestinationDetails destinationDetails = new DestinationDetails();
      //
      // destinationDetails.setDestinationImages(imageService.getCityImages(suggestionCurrent.getCityName(), suggestionCurrent.getLabels(), 3));

      CruiseSuggestion cruiseSuggestion =
          cruiseSuggestionService.getCruiseSuggestion(
              suggestion.getAirportCodes().get(0), departureDate, returnDate);

      FlightSuggestion flightSuggestion =
          new FlightSuggestion(
              flights.getPrice(),
              flights.getDepartureDate(),
              flights.getReturnDate(),
              new Airport(departureAirportCode, departureAirportCity),
              new Airport(suggestion.getAirportCodes().get(0), suggestion.getCityName()),
              destinationDetails,
              cruiseSuggestion,
              displayDepDate,
              displayRetDate);
      flightSuggestions.put(key, flightSuggestion);
    }

    return flightSuggestions;
  }
Пример #13
0
  /**
   * Make a set of CDS represented as a MultiCdsAnalytic instance.
   *
   * @param tradeDate the trade date
   * @param accStartDate This is when the CDS nominally starts in terms of the accrual calculation
   *     for premium payments. For a standard CDS this is the previous IMM date, and for a `legacy'
   *     CDS it is T+1
   * @param maturityReferanceDate A reference date that maturities are measured from. For standard
   *     CDSSs, this is the next IMM date after the trade date, so the actually maturities will be
   *     some fixed periods after this.
   * @param maturityIndexes the maturities are fixed integer multiples of the payment interval, so
   *     for 6M, 1Y and 2Y tenors with a 3M payment interval, would require 2, 4, and 8 as the
   *     indices
   * @return Make a set of CDS represented as a MultiCdsAnalytic
   */
  public MultiCdsAnalytic makeMultiCds(
      LocalDate tradeDate,
      LocalDate accStartDate,
      LocalDate maturityReferanceDate,
      int[] maturityIndexes) {
    LocalDate stepinDate = tradeDate.plusDays(_stepIn);

    LocalDate valueDate = addWorkDays(tradeDate, _cashSettle, _calendar);
    return makeMultiCds(
        tradeDate, stepinDate, valueDate, accStartDate, maturityReferanceDate, maturityIndexes);
  }
Пример #14
0
  public static List<Descriptor> getDescriptors(
      @NotNull ReportPeriod reportPeriod,
      @NotNull LocalDate startDate,
      @NotNull LocalDate endDate) {

    final List<Descriptor> descriptors = new ArrayList<>();

    LocalDate start = startDate;
    LocalDate end = startDate;

    switch (reportPeriod) {
      case YEARLY:
        while (end.isBefore(endDate)) {
          end = end.with(TemporalAdjusters.lastDayOfYear());
          descriptors.add(new Descriptor(start, end, "    " + start.getYear()));
          start = end.plusDays(1);
        }
        break;
      case QUARTERLY:
        int i = DateUtils.getQuarterNumber(start) - 1;
        while (end.isBefore(endDate)) {
          end = DateUtils.getLastDayOfTheQuarter(start);
          descriptors.add(new Descriptor(start, end, " " + start.getYear() + "-Q" + (1 + i++ % 4)));
          start = end.plusDays(1);
        }
        break;
      case MONTHLY:
        while (end.isBefore(endDate)) {
          end = DateUtils.getLastDayOfTheMonth(start);
          final int month = start.getMonthValue();
          descriptors.add(
              new Descriptor(
                  start, end, " " + start.getYear() + (month < 10 ? "/0" + month : "/" + month)));
          start = end.plusDays(1);
        }
        break;
      default:
    }

    return descriptors;
  }
Пример #15
0
  /**
   * A forward starting CDS starts on some date after today (the trade date). The accrual start must
   * be specified (would normally use this for T+1 accrual atart). The stepin date and cash
   * settlement date are taken from the forward start date (1 day and 3 working days by default).
   *
   * @param tradeDate the trade date (i.e. today)
   * @param forwardStartDate the forward start date
   * @param accStartDate the accrual start date
   * @param maturity the maturity of the CDS
   * @return a CDS analytic description for a forward starting CDS
   */
  public CdsAnalytic makeForwardStartingCds(
      LocalDate tradeDate, LocalDate forwardStartDate, LocalDate accStartDate, LocalDate maturity) {

    ArgChecker.isFalse(
        forwardStartDate.isBefore(tradeDate),
        "forwardStartDate of {} is before trade date of {}",
        forwardStartDate,
        tradeDate);
    LocalDate stepinDate = forwardStartDate.plusDays(_stepIn);
    LocalDate valueDate = addWorkDays(forwardStartDate, _cashSettle, _calendar);
    return makeCds(tradeDate, stepinDate, valueDate, accStartDate, maturity);
  }
Пример #16
0
 /**
  * A forward starting CDS starts on some date after today (the trade date). The stepin date and
  * cash settlement date are taken from the forward start date (1 day and 3 working days by
  * default).
  *
  * @param tradeDate the trade date (i.e. today)
  * @param forwardStartDate the forward start date
  * @param maturity the maturity of the CDS
  * @return a CDS analytic description for a forward starting CDS
  */
 public CdsAnalytic makeForwardStartingCds(
     LocalDate tradeDate, LocalDate forwardStartDate, LocalDate maturity) {
   ArgChecker.isFalse(
       forwardStartDate.isBefore(tradeDate),
       "forwardStartDate of {} is before trade date of {}",
       forwardStartDate,
       tradeDate);
   LocalDate stepinDate = forwardStartDate.plusDays(_stepIn);
   LocalDate valueDate = addWorkDays(forwardStartDate, _cashSettle, _calendar);
   LocalDate accStartDate =
       _businessdayAdjustmentConvention.adjust(
           ImmDateLogic.getPrevIMMDate(forwardStartDate), _calendar);
   return makeCds(tradeDate, stepinDate, valueDate, accStartDate, maturity);
 }
Пример #17
0
  private Month create(final LocalDate year, final LocalDate localMonth) {

    log.debug("Entering with {}, {}", year, localMonth);

    Month month = new Month();

    month.setMonth(localMonth.getMonth());

    for (int i = 0; i < localMonth.getMonth().length(year.isLeapYear()); i++)
      month.getDays().add(create(localMonth.plusDays(i)));

    createWeeks(month);

    return month;
  }
Пример #18
0
  /**
   * Add a certain number of working days (defined by the holidayCalendar) to a date.
   *
   * @param startDate the start date
   * @param workingDaysToAdd working days to add
   * @param calendar the calendar of holidays
   * @return a working day
   */
  private static LocalDate addWorkDays(
      LocalDate startDate, int workingDaysToAdd, HolidayCalendar calendar) {
    ArgChecker.notNull(startDate, "startDate");
    ArgChecker.notNull(calendar, "calendar");

    int daysLeft = workingDaysToAdd;
    LocalDate temp = startDate;
    while (daysLeft > 0) {
      temp = temp.plusDays(1);
      if (calendar.isBusinessDay(temp)) {
        daysLeft--;
      }
    }
    return temp;
  }
  public static ZonedDateTime getNextSchedule() {
    ZonedDateTime next_schedule;

    // Determine type of schedule
    if (ConfigHandler.backupInterval > 0) // Interval
    {
      next_schedule =
          ZonedDateTime.ofInstant(
              Instant.ofEpochMilli(
                  System.currentTimeMillis() + (ConfigHandler.backupInterval * 60 * 1000)),
              ZoneId.systemDefault());
    } else // Schedule
    {
      if (ConfigHandler.backupSchedule.length == 0) {
        return null;
      }

      LocalTime now = LocalTime.now();
      LocalTime next_time = null;
      LocalDate day = LocalDate.now();
      TreeSet<LocalTime> times = new TreeSet<>();

      for (String s : ConfigHandler.backupSchedule) {
        times.add(LocalTime.parse(s, DateTimeFormatter.ofPattern("H:mm")));
      }

      for (LocalTime t : times) // try to find next scheduled time for today
      {
        if (t.compareTo(now) == 1) {
          next_time = t;
          break;
        }
      }

      if (next_time
          == null) // if we couldn't find one for today take the first schedule time for tomorrow
      {
        day = day.plusDays(1);
        next_time = times.first();
      }

      next_schedule = ZonedDateTime.of(day, next_time, ZoneId.systemDefault());
    }

    return next_schedule;
  }
Пример #20
0
 /**
  * Make a CDS by specifying key dates.
  *
  * @param tradeDate the trade date
  * @param accStartDate this is when the CDS nominally starts in terms of premium payments. For a
  *     standard CDS this is the previous IMM date, and for a `legacy' CDS it is T+1
  * @param maturity the maturity. For a standard CDS this is an IMM date
  * @return a CDS analytic description
  */
 public CdsAnalytic makeCds(LocalDate tradeDate, LocalDate accStartDate, LocalDate maturity) {
   LocalDate stepinDate = tradeDate.plusDays(_stepIn);
   LocalDate valueDate = addWorkDays(tradeDate, _cashSettle, _calendar);
   return new CdsAnalytic(
       tradeDate,
       stepinDate,
       valueDate,
       accStartDate,
       maturity,
       _payAccOnDefault,
       _couponInterval,
       _stubType,
       _protectStart,
       _recoveryRate,
       _businessdayAdjustmentConvention,
       _calendar,
       _accrualDayCount,
       _curveDayCount);
 }
Пример #21
0
  @Test
  public void testThatPerformanceOfAnInvestmentIntoAnIndexIsIdenticalToIndex() {
    LocalDate startDate = LocalDate.of(2012, 1, 1);
    LocalDate endDate = LocalDate.of(2012, 4, 29); // a weekend
    long startPrice = Values.Quote.factorize(100);

    Client client = new Client();

    Security security =
        new SecurityBuilder() //
            .generatePrices(startPrice, startDate, endDate) //
            .addTo(client);

    PortfolioBuilder portfolio = new PortfolioBuilder(new Account());

    // add some buy transactions
    LocalDate date = startDate;
    while (date.isBefore(endDate)) {
      long p = security.getSecurityPrice(date).getValue();
      portfolio.inbound_delivery(security, date, Values.Share.factorize(100), p);
      date = date.plusDays(20);
    }

    portfolio.addTo(client);

    ReportingPeriod.FromXtoY period = new ReportingPeriod.FromXtoY(startDate, endDate);

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

    double[] accumulated = index.getAccumulatedPercentage();
    long lastPrice = security.getSecurityPrice(endDate).getValue();

    assertThat(
        (double) (lastPrice - startPrice) / (double) startPrice,
        IsCloseTo.closeTo(accumulated[accumulated.length - 1], PRECISION));

    PerformanceIndex benchmark = PerformanceIndex.forSecurity(index, security);
    assertThat(
        benchmark.getFinalAccumulatedPercentage(), is(index.getFinalAccumulatedPercentage()));
  }
Пример #22
0
  /**
   * Finds out the earliest LocalDate that an import check has been inserted and then returns the
   * next day
   *
   * @return the date of when to perform the next import. If no check was found then
   * @param type The type of the import that we want to find (i.e entity, instrument or
   *     investigation) null is returned.
   */
  public LocalDate getNextImportDate(String type) {

    TypedQuery<Date> importCheckQuery =
        manager.createQuery(
            "SELECT ic.checkDate FROM ImportCheck ic WHERE ic.passed=1 AND ic.type='"
                + type
                + "' ORDER BY ic.checkDate desc",
            Date.class);

    importCheckQuery.setMaxResults(1);

    // Have to use getResultList as getSingleResult will fail if no collection has occured.
    List<Date> dates = importCheckQuery.getResultList();

    LocalDate earliestImport = null;

    if (!dates.isEmpty()) {
      earliestImport = convertToLocalDate(dates.get(0));
      earliestImport = earliestImport.plusDays(1);
    }

    return earliestImport;
  }
  @Test
  public void testPaymentDateSemiMonthly() {
    LocalDate scheduleStartDate = LocalDate.of(2015, Month.DECEMBER, 2);
    AmortizationAttributes amAttrs = generateAmortizationAttributesObjectTemplate();
    amAttrs.setAdjustmentDate(scheduleStartDate);
    amAttrs.setPaymentFrequency(TimePeriod.SemiMonthly.getPeriodsPerYear());
    int termInMonths = 24;
    amAttrs.setTermInMonths(termInMonths);

    int dayOfMonthPayment1 = scheduleStartDate.getDayOfMonth();
    int dayOfMonthPayment2 = scheduleStartDate.plusDays(14).getDayOfMonth();

    List<ScheduledPayment> schedule = AmortizationCalculator.generateSchedule(amAttrs);

    // First payment of month
    for (int i = 1; i <= 48; i += 2) {
      String msg = String.format("First date for semi-monthly payment %d", i);
      assertEquals(
          msg,
          scheduleStartDate.plusMonths(i / 2).plusDays(14),
          schedule.get(i - 1).getPaymentDate());
      assertEquals(
          "Semi-monthly common day of month",
          dayOfMonthPayment2,
          schedule.get(i - 1).getPaymentDate().getDayOfMonth());
    }

    // Second payment of month
    for (int i = 2; i <= 48; i += 2) {
      String msg = String.format("Second date for semi-monthly payment %d", i);
      assertEquals(msg, scheduleStartDate.plusMonths(i / 2), schedule.get(i - 1).getPaymentDate());
      assertEquals(
          "Semi-monthly common day of month",
          dayOfMonthPayment1,
          schedule.get(i - 1).getPaymentDate().getDayOfMonth());
    }
  }
  // Calculate How many time
  public List<TestingCenterTimeSlots> generateTimeSlots(Exam exam) {
    TestingCenterInfo tci = tcr.findByTerm(tcr.getCurrentTerm().getTermId());
    int gap = tci.getGap();
    int examDuration = exam.getDuration();
    int openMinutes = (int) ChronoUnit.MINUTES.between(tci.getOpen(), tci.getClose());

    // Ensure time chunk devides 30
    int timeChuck =
        (examDuration + gap) % 30 == 0 ? examDuration : 30 * ((examDuration + gap) / 30 + 1);

    LocalTime endTime = exam.getEndDateTime().toLocalTime();
    LocalTime beginTime = exam.getStartDateTime().toLocalTime();
    LocalTime openTime = tci.getOpen();
    LocalTime closeTime = tci.getClose();
    LocalDate beginDate = exam.getStartDateTime().toLocalDate();
    LocalDate endDate = exam.getEndDateTime().toLocalDate();

    beginTime = adjustTime(beginTime); // Exam Begin Time
    endTime = adjustTime(endTime); // Exam End Time

    // Calculate Duration According to different day.
    int startDayDuration = (int) ChronoUnit.MINUTES.between(beginTime, closeTime);
    int dayLast = (int) ChronoUnit.DAYS.between(beginDate, endDate) - 1;
    int endDayDuration = (int) ChronoUnit.MINUTES.between(openTime, endTime);

    int startDayChucks = startDayDuration / timeChuck;
    int endDayChucks = endDayDuration / timeChuck;
    int regularDayChuncks = dayLast >= 0 ? (dayLast * openMinutes) / timeChuck : 0;
    int dailyChuncks = openMinutes / timeChuck;

    LocalDate dateCursor = beginDate;
    LocalTime timeCursor = beginTime;
    List<TestingCenterTimeSlots> timeSlotses = new ArrayList<>();
    if (startDayChucks > 0) {
      for (int i = 0; i < startDayChucks; i++) {
        LocalDateTime slotsBegin = dateCursor.atTime(timeCursor);
        LocalDateTime slotsEnd = dateCursor.atTime(timeCursor.plusMinutes(examDuration));

        TestingCenterTimeSlots t =
            new TestingCenterTimeSlots(
                exam.getExamId(),
                slotsBegin,
                slotsEnd,
                tci.getNumSeats(),
                tci.getNumSetAsideSeats());
        timeSlotses.add(t);

        timeCursor = timeCursor.plusMinutes(timeChuck);
      }
    }
    if (regularDayChuncks > 0) {

      for (int i = 0; i < dayLast; i++) {
        dateCursor = dateCursor.plusDays(1);
        timeCursor = adjustTime(openTime);

        for (int j = 0; j < dailyChuncks; j++) {
          LocalDateTime slotsBegin = dateCursor.atTime(timeCursor);
          LocalDateTime slotsEnd = dateCursor.atTime(timeCursor.plusMinutes(examDuration));

          TestingCenterTimeSlots t =
              new TestingCenterTimeSlots(
                  exam.getExamId(),
                  slotsBegin,
                  slotsEnd,
                  tci.getNumSeats(),
                  tci.getNumSetAsideSeats());
          timeSlotses.add(t);

          timeCursor = timeCursor.plusMinutes(timeChuck);
        }
      }
    }
    if (endDayChucks > 0) {
      dateCursor = dateCursor.plusDays(1);
      timeCursor = adjustTime(openTime);

      for (int i = 0; i < endDayChucks; i++) {
        LocalDateTime slotsBegin = dateCursor.atTime(timeCursor);
        LocalDateTime slotsEnd = dateCursor.atTime(timeCursor.plusMinutes(examDuration));

        TestingCenterTimeSlots t =
            new TestingCenterTimeSlots(
                exam.getExamId(),
                slotsBegin,
                slotsEnd,
                tci.getNumSeats(),
                tci.getNumSetAsideSeats());
        timeSlotses.add(t);

        timeCursor = timeCursor.plusMinutes(timeChuck);
      }
    }
    return timeSlotses;
  }
Пример #25
0
  @FilterWith(XSRFFilter.class)
  public Result dryRun(
      Context context, @Param("startDate") String start, @Param("endDate") String end) {
    long _start = System.currentTimeMillis();
    FlashScope flash = context.getFlashScope();

    LocalDate startDate = null;
    LocalDate endDate = null;

    try {
      startDate = LocalDate.parse(start);
      endDate = LocalDate.parse(end);
    } catch (Exception ex) {
    }

    if (startDate == null || endDate == null || startDate.isAfter(endDate)) {
      flash.error("error.invalidDate");
      return Results.redirect(router.getReverseRoute(DebugController.class, "debug"));
    }

    Run lastRun = baseDB.run.findLast(Module.GOOGLE, null, null);
    if (lastRun != null && lastRun.getDay().isAfter(startDate)) {
      flash.error("error.invalidDate");
      return Results.redirect(router.getReverseRoute(DebugController.class, "debug"));
    }

    LocalDate date = LocalDate.from(startDate);

    GoogleSettings ggOptions = googleDB.options.get();

    int minPauseBetweenPageSec = ggOptions.getMinPauseBetweenPageSec();
    int maxPauseBetweenPageSec = ggOptions.getMaxPauseBetweenPageSec();
    ggOptions.setMinPauseBetweenPageSec(0);
    ggOptions.setMaxPauseBetweenPageSec(0);
    googleDB.options.update(ggOptions);

    try {
      while (date.isBefore(endDate)) {
        LOG.debug("dry run {}", date);
        if (!taskManager.startGoogleTask(
            new Run(Run.Mode.MANUAL, Module.GOOGLE, date.atTime(13, 37, 00)))) {
          LOG.error("can't startGoogleTask");
          flash.error("can't startGoogleTask");
          return Results.redirect(router.getReverseRoute(DebugController.class, "debug"));
        }
        taskManager.joinGoogleTask();
        date = date.plusDays(1);
      }
    } catch (Exception ex) {
      LOG.error("an error occured", ex);
      flash.error("an error occured");
      return Results.redirect(router.getReverseRoute(DebugController.class, "debug"));
    } finally {
      ggOptions.setMinPauseBetweenPageSec(minPauseBetweenPageSec);
      ggOptions.setMaxPauseBetweenPageSec(maxPauseBetweenPageSec);
      googleDB.options.update(ggOptions);
    }

    LOG.debug(
        "dry run timing : {}",
        DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - _start));
    flash.success("ok");
    return Results.redirect(router.getReverseRoute(DebugController.class, "debug"));
  }
Пример #26
0
  BudgetPeriodDescriptor(
      final LocalDate budgetDate, final int budgetYear, final BudgetPeriod budgetPeriod) {
    Objects.requireNonNull(budgetPeriod);
    Objects.requireNonNull(budgetDate);

    this.budgetYear = budgetYear;
    this.budgetPeriod = budgetPeriod;
    this.startPeriod = budgetDate.getDayOfYear() - 1; // zero based index vs. 1 based day of year

    /* Calendar day 1 is 1.  Need to add 1 to get correct dates */
    startDate = LocalDate.ofYearDay(budgetYear, startPeriod + 1);

    switch (budgetPeriod) {
      case DAILY:
        endDate = startDate;
        endPeriod = startPeriod;

        periodDescription =
            ResourceUtils.getString("Pattern.NumericDate", DateUtils.asDate(startDate));
        break;
      case WEEKLY:
        // Check to see if we are working with the start of a 53 week year.  The first week will be
        // truncated
        if (DateUtils.getNumberOfWeeksInYear(budgetYear) == DateUtils.LEAP_WEEK
            && budgetDate.getYear() < budgetYear) {
          startPeriod = 0;
          startDate = budgetDate;

          endPeriod =
              (int) ChronoUnit.DAYS.between(startDate, LocalDate.of(budgetYear, Month.JANUARY, 1));
          endDate = startDate.plusDays(ONE_WEEK_INCREMENT);
        } else {
          endDate = startDate.plusDays(ONE_WEEK_INCREMENT);
          endPeriod =
              Math.min(
                  startPeriod + ONE_WEEK_INCREMENT,
                  BudgetGoal.PERIODS - 1); // need to cap for 53 week years
        }

        periodDescription =
            ResourceUtils.getString(
                "Pattern.WeekOfYear", DateUtils.getWeekOfTheYear(startDate), budgetYear);
        break;
      case BI_WEEKLY:
        if (DateUtils.getWeekOfTheYear(startDate) != DateUtils.LEAP_WEEK) {
          endDate = startDate.plusDays(TWO_WEEK_INCREMENT);
          endPeriod = startPeriod + TWO_WEEK_INCREMENT;
        } else {
          endDate = startDate.plusDays(ONE_WEEK_INCREMENT);
          endPeriod = startPeriod + ONE_WEEK_INCREMENT;
        }
        periodDescription =
            ResourceUtils.getString(
                "Pattern.DateRangeShort", DateUtils.asDate(startDate), DateUtils.asDate(endDate));
        break;
      case MONTHLY:
        final int days = startDate.lengthOfMonth();
        endDate = DateUtils.getLastDayOfTheMonth(startDate);
        endPeriod = startPeriod + days - 1;

        periodDescription =
            ResourceUtils.getString("Pattern.MonthOfYear", DateUtils.asDate(startDate));
        break;
      case QUARTERLY:
        endDate = DateUtils.getLastDayOfTheQuarter(startDate);
        endPeriod = startPeriod + (int) ChronoUnit.DAYS.between(startDate, endDate);

        periodDescription =
            ResourceUtils.getString(
                "Pattern.QuarterOfYear", DateUtils.getQuarterNumber(startDate), budgetYear);
        break;
      case YEARLY:
        endDate = DateUtils.getLastDayOfTheYear(startDate);
        endPeriod = startPeriod + (int) ChronoUnit.DAYS.between(startDate, endDate);

        periodDescription = Integer.toString(budgetYear);
        break;
      default:
        endPeriod = startPeriod;
        endDate = LocalDate.now();
        periodDescription = "";
    }

    // Periods especially bi-weekly can get weird, correct ending period if needed.
    if (endPeriod > BudgetGoal.PERIODS) {
      endPeriod = BudgetGoal.PERIODS - 1;
      endDate = DateUtils.getLastDayOfTheYear(startDate);
    }
  }
Пример #27
0
 private static LocalDate nextDay(LocalDate d) {
   return d.plusDays(1);
 }
 private long monateZwischen(LocalDate erstesDatum, LocalDate zweitesDatumInklusive) {
   return Period.between(erstesDatum, zweitesDatumInklusive.plusDays(1)).toTotalMonths();
 }
Пример #29
0
 /**
  * Make a set of CDS by specifying key dates.
  *
  * @param tradeDate the trade date
  * @param accStartDate this is when the CDS nominally starts in terms of premium payments. For a
  *     standard CDS this is the previous IMM date, and for a `legacy' CDS it is T+1
  * @param maturities The maturities of the CDSs. For a standard CDS these are IMM dates
  * @return an array of CDS analytic descriptions
  */
 public CdsAnalytic[] makeCds(
     LocalDate tradeDate, LocalDate accStartDate, LocalDate[] maturities) {
   LocalDate stepinDate = tradeDate.plusDays(_stepIn);
   LocalDate valueDate = addWorkDays(tradeDate, _cashSettle, _calendar);
   return makeCds(tradeDate, stepinDate, valueDate, accStartDate, maturities);
 }
  @Test
  public void buildDateCurveTest() {
    final LocalDate baseDate = LocalDate.of(2012, 8, 8);
    final LocalDate[] dates =
        new LocalDate[] {
          LocalDate.of(2012, 12, 3),
          LocalDate.of(2013, 4, 29),
          LocalDate.of(2013, 11, 12),
          LocalDate.of(2014, 5, 18)
        };
    final double[] rates = new double[] {0.11, 0.22, 0.15, 0.09};
    final DayCount dcc = DayCounts.ACT_365F;
    final int num = dates.length;

    final ISDACompliantDateCreditCurve baseCurve =
        new ISDACompliantDateCreditCurve(baseDate, dates, rates);
    final LocalDate[] clonedDates = baseCurve.getCurveDates();
    assertNotSame(dates, clonedDates);
    final int modPosition = 2;
    final ISDACompliantDateCreditCurve curveWithRate =
        baseCurve.withRate(rates[modPosition] * 1.5, modPosition);
    final ISDACompliantDateCreditCurve clonedCurve = baseCurve.clone();
    assertNotSame(baseCurve, clonedCurve);

    final double[] t = new double[num];
    final double[] rt = new double[num];
    for (int i = 0; i < num; ++i) {
      assertEquals(dates[i], baseCurve.getCurveDate(i));
      assertEquals(dates[i], curveWithRate.getCurveDate(i));
      assertEquals(dates[i], clonedDates[i]);
      assertEquals(clonedCurve.getCurveDate(i), baseCurve.getCurveDate(i));
      if (i == modPosition) {
        assertEquals(rates[i] * 1.5, curveWithRate.getZeroRateAtIndex(i));
      }
      t[i] = dcc.yearFraction(baseDate, dates[i]);
      rt[i] = t[i] * rates[i];
    }

    final LocalDate[] sampleDates =
        new LocalDate[] {baseDate.plusDays(2), LocalDate.of(2013, 7, 5), dates[2]};
    final int nSampleDates = sampleDates.length;
    final double[] sampleRates = new double[nSampleDates];
    final double[] fracs = new double[nSampleDates];
    for (int i = 0; i < nSampleDates; ++i) {
      fracs[i] = dcc.yearFraction(baseDate, sampleDates[i]);
      sampleRates[i] = baseCurve.getZeroRate(sampleDates[i]);
    }
    assertEquals(rates[0], sampleRates[0]);
    assertEquals(
        (rt[2] * (fracs[1] - t[1]) + rt[1] * (t[2] - fracs[1])) / (t[2] - t[1]) / fracs[1],
        sampleRates[1]);
    assertEquals(rates[2], sampleRates[2]);

    assertEquals(baseDate, baseCurve.getBaseDate());

    /*
     * Test meta
     */
    final Property<LocalDate> propBaseDate = baseCurve.baseDate();
    final Property<LocalDate[]> propDates = baseCurve.dates();
    final Property<DayCount> propDcc = baseCurve.dayCount();

    final Meta meta = baseCurve.metaBean();
    final BeanBuilder<?> builder = meta.builder();
    builder.set(propBaseDate.name(), baseDate);
    builder.set(propDates.name(), dates);
    builder.set(propDcc.name(), dcc);
    builder.set(meta.metaPropertyGet("name"), "");
    builder.set(meta.metaPropertyGet("t"), t);
    builder.set(meta.metaPropertyGet("rt"), rt);
    ISDACompliantDateCreditCurve builtCurve = (ISDACompliantDateCreditCurve) builder.build();
    assertEquals(baseCurve, builtCurve);

    final Meta meta1 = ISDACompliantDateCreditCurve.meta();
    assertEquals(meta1, meta);

    /*
     * hash and equals
     */
    assertTrue(!(baseCurve.equals(null)));
    assertTrue(!(baseCurve.equals(new ISDACompliantDateCurve(baseDate, dates, rates))));
    assertTrue(
        !(baseCurve.equals(new ISDACompliantDateCreditCurve(baseDate.minusDays(1), dates, rates))));
    assertTrue(
        !(baseCurve.equals(
            new ISDACompliantDateCreditCurve(
                baseDate,
                new LocalDate[] {
                  LocalDate.of(2012, 12, 3),
                  LocalDate.of(2013, 4, 29),
                  LocalDate.of(2013, 11, 12),
                  LocalDate.of(2014, 5, 19)
                },
                rates))));
    assertTrue(
        !(baseCurve.equals(
            new ISDACompliantDateCreditCurve(baseDate, dates, rates, DayCounts.ACT_365_25))));

    assertTrue(baseCurve.equals(baseCurve));

    assertTrue(baseCurve.hashCode() != curveWithRate.hashCode());
    assertTrue(!(baseCurve.equals(curveWithRate)));

    /*
     * String
     */
    assertEquals(baseCurve.toString(), clonedCurve.toString());
  }