Example usage for org.joda.time LocalDate plus

List of usage examples for org.joda.time LocalDate plus

Introduction

In this page you can find the example usage for org.joda.time LocalDate plus.

Prototype

public LocalDate plus(ReadablePeriod period) 

Source Link

Document

Returns a copy of this date with the specified period added.

Usage

From source file:com.mbc.jfin.daycount.impl.calculator.AFBActualActualDaycountCalculator.java

License:Open Source License

public double calculateDaycountFraction(SchedulePeriod period) {
    int daysBetween = DateUtils.daysBetween(period.getStart(), period.getEnd());

    if (daysBetween == 0)
        return 0;

    LocalDate newD2 = period.getEnd();
    LocalDate temp = period.getEnd();

    double sum = 0.0;
    while (temp.isAfter(period.getStart())) {
        temp = newD2;//w  w w .j  ava 2s .com
        temp = temp.minus(Years.ONE);
        if (temp.getDayOfMonth() == 28 && temp.getMonthOfYear() == 2 && DateUtils.isLeapYear(temp)) {
            temp = temp.plus(Days.ONE);
        }
        if (temp.isAfter(period.getStart()) || temp.equals(period.getStart())) {
            sum += 1.0;
            newD2 = temp;
        }
    }

    double den = 365.0;

    if (DateUtils.isLeapYear(newD2)) {
        temp = newD2;

        temp = new LocalDate(temp.getYear(), 2, 29);

        if (newD2.isAfter(temp) && (period.getStart().isBefore(temp) || period.getStart().equals(temp)))
            den += 1.0;
    } else if (DateUtils.isLeapYear(period.getStart())) {

        temp = new LocalDate(period.getStart().getYear(), 2, 29);

        if (newD2.isAfter(temp) && (period.getStart().isBefore(temp) || period.getStart().equals(temp)))
            den += 1.0;
    }

    return sum + DateUtils.daysBetween(period.getStart(), newD2) / den;

}

From source file:com.mbc.jfin.daycount.impl.calculator.ISMAActualActualDaycountCalculator.java

License:Open Source License

public double calculateDaycountFraction(SchedulePeriod schedulePeriod) {

    if (schedulePeriod.getStart().equals(schedulePeriod.getEnd()))
        return 0;

    // when the reference period is not specified, try taking
    // it equal to (d1,d2)
    LocalDate refPeriodStart = (schedulePeriod.getReferenceStart() != null ? schedulePeriod.getReferenceStart()
            : schedulePeriod.getStart());
    LocalDate refPeriodEnd = (schedulePeriod.getReferenceEnd() != null ? schedulePeriod.getReferenceEnd()
            : schedulePeriod.getEnd());//w w w  .  j av a  2s .  c o  m

    LocalDate startCalendar = schedulePeriod.getStart();
    LocalDate endCalendar = schedulePeriod.getEnd();

    if (!(refPeriodEnd.isAfter(refPeriodStart) && refPeriodEnd.isAfter(startCalendar))) {
        throw new InvalidReferencePeriodException(schedulePeriod);
    }

    // estimate roughly the length in months of a period
    // Integer months =
    // Integer(0.5+12*Real(refPeriodEnd-refPeriodStart)/365);

    double monthsEstimate = DateUtils.daysBetween(refPeriodStart, refPeriodEnd) * (12.0d / 365.0d);
    int months = (int) Math.round(monthsEstimate);

    if (months == 0) {
        refPeriodStart = startCalendar;
        refPeriodEnd = startCalendar.plus(Years.ONE);
        months = 12;
    }

    double period = (double) months / 12.0;

    if (endCalendar.isBefore(refPeriodEnd) || endCalendar.equals(refPeriodEnd)) {
        if (startCalendar.isAfter(refPeriodStart) || startCalendar.equals(refPeriodStart)) {
            long numerator = DateUtils.daysBetween(startCalendar, endCalendar);
            long denominator = DateUtils.daysBetween(refPeriodStart, refPeriodEnd);

            return period * (double) numerator / (double) denominator;
        } else {

            LocalDate previousRef = startCalendar;

            //previousRef.add(Calendar.MONTH, months * -1);
            if (endCalendar.isAfter(refPeriodStart))
                return calculateDaycountFraction(
                        new SchedulePeriod(startCalendar, refPeriodStart, previousRef, refPeriodStart))
                        + calculateDaycountFraction(
                                new SchedulePeriod(refPeriodStart, endCalendar, refPeriodStart, refPeriodEnd));
            else
                return calculateDaycountFraction(
                        new SchedulePeriod(startCalendar, endCalendar, previousRef, refPeriodStart));
        }
    } else {
        if (!(refPeriodStart.isBefore(startCalendar) || refPeriodStart.equals(startCalendar))) {
            throw new InvalidReferencePeriodException(schedulePeriod);
        }

        // the part from d1 to refPeriodEnd
        double sum = calculateDaycountFraction(
                new SchedulePeriod(startCalendar, refPeriodEnd, refPeriodStart, refPeriodEnd));

        // the part from refPeriodEnd to d2
        // count how many regular periods are in [refPeriodEnd, d2],
        // then add the remaining time
        int i = 0;
        LocalDate newRefStart, newRefEnd;
        do {
            newRefStart = refPeriodEnd.plus(Months.months(months * i));
            newRefEnd = refPeriodEnd.plus(Months.months(months * (i + 1)));
            if (endCalendar.isBefore(newRefEnd)) {
                break;
            } else {
                sum += period;
                i++;
            }
        } while (true);
        double secondSum = calculateDaycountFraction(
                new SchedulePeriod(newRefStart, endCalendar, newRefStart, newRefEnd));

        sum += secondSum;
        return sum;
    }
}

From source file:com.mbc.jfin.holiday.impl.DefaultDateAdjustmentServiceImpl.java

License:Open Source License

public LocalDate following(LocalDate calendar, HolidayCalendar holidayCalendar) {
    LocalDate d1 = calendar;
    while (holidayCalendar.isHoliday(d1) || holidayCalendar.isWeekend(d1)) {
        d1 = d1.plus(Days.ONE);
    }//from   w w w  .j  av a 2s .  c o m
    return d1;
}

From source file:com.mbc.jfin.holiday.impl.DefaultDateAdjustmentServiceImpl.java

License:Open Source License

public LocalDate modFollowing(LocalDate calendar, HolidayCalendar holidayCalendar) {
    LocalDate d1 = calendar;
    while (holidayCalendar.isHoliday(d1) || holidayCalendar.isWeekend(d1)) {
        d1 = d1.plus(Days.ONE);
    }//from w  w  w.j  a v  a 2  s  .  c  o  m

    if (d1.getMonthOfYear() != calendar.getMonthOfYear()) {
        return preceding(calendar, holidayCalendar);
    }

    return d1;
}

From source file:com.mbc.jfin.schedule.impl.LongLastStubScheduleGenerator.java

License:Open Source License

public Schedule generate(LocalDate start, LocalDate end, ReadablePeriod frequency) throws ScheduleException {
    ArrayList<SchedulePeriod> schedulePeriods = new ArrayList<SchedulePeriod>();

    LocalDate holdDate = start;/* w ww.  j ava  2s . c om*/

    int periodCount = 1;

    while (holdDate.isBefore(end)) {
        LocalDate nextDate = start.plus(multiplyPeriod(frequency, periodCount));

        LocalDate nextDate2 = start.plus(multiplyPeriod(frequency, periodCount + 1));

        if (nextDate2.isAfter(end)) {
            SchedulePeriod schedulePeriod = new SchedulePeriod(holdDate, end, holdDate, nextDate);

            schedulePeriods.add(schedulePeriod);

            holdDate = nextDate2;
        } else {
            SchedulePeriod schedulePeriod = new SchedulePeriod(holdDate, nextDate);

            schedulePeriods.add(schedulePeriod);

            holdDate = nextDate;
        }

        periodCount++;
        if (maxPeriods > 0 && periodCount > maxPeriods) {
            throw new ScheduleTooLongException(maxPeriods);
        }
    }

    return new Schedule(schedulePeriods);
}

From source file:com.mbc.jfin.schedule.impl.NoStubScheduleGenerator.java

License:Open Source License

public Schedule generate(LocalDate start, LocalDate end, ReadablePeriod frequency) throws ScheduleException {
    ArrayList<SchedulePeriod> schedulePeriods = new ArrayList<SchedulePeriod>();

    LocalDate holdDate = start;//from  ww w.j  av  a  2s.  com

    int periodCount = 1;

    while (holdDate.isBefore(end)) {
        LocalDate nextDate = start.plus(multiplyPeriod(frequency, periodCount));

        if (nextDate.isAfter(end)) {
            throw new ScheduleWontFitException(start, end, frequency);
        }

        SchedulePeriod schedulePeriod = new SchedulePeriod(holdDate, nextDate);

        schedulePeriods.add(schedulePeriod);

        holdDate = nextDate;
        periodCount++;
        if (maxPeriods > 0 && periodCount > maxPeriods) {
            throw new ScheduleTooLongException(maxPeriods);
        }
    }

    return new Schedule(schedulePeriods);
}

From source file:com.mbc.jfin.schedule.impl.ShortLastStubScheduleGenerator.java

License:Open Source License

public Schedule generate(LocalDate start, LocalDate end, ReadablePeriod frequency) throws ScheduleException {
    ArrayList<SchedulePeriod> schedulePeriods = new ArrayList<SchedulePeriod>();

    LocalDate holdDate = start;//  w  ww.  j  a  va  2s. c o  m

    int periodCount = 1;

    while (holdDate.isBefore(end)) {
        LocalDate nextDate = start.plus(multiplyPeriod(frequency, periodCount));

        LocalDate notionalStartDate = null;
        LocalDate notionalEndDate = null;

        if (nextDate.isAfter(end)) {
            notionalStartDate = holdDate;
            notionalEndDate = nextDate;
            nextDate = end;
        }

        SchedulePeriod schedulePeriod = new SchedulePeriod(holdDate, nextDate, notionalStartDate,
                notionalEndDate);

        schedulePeriods.add(schedulePeriod);

        holdDate = nextDate;
        periodCount++;
        if (maxPeriods > 0 && periodCount > maxPeriods) {
            throw new ScheduleTooLongException(maxPeriods);
        }
    }

    return new Schedule(schedulePeriods);
}

From source file:energy.usef.brp.workflow.settlement.send.BrpSendSettlementMessagesCoordinator.java

License:Apache License

/**
 * This method starts the workflow when triggered by an event.
 *
 * @param event {@link SendSettlementMessageEvent} event which starts the workflow.
 *//*from   w w  w.j  av a  2 s.c  om*/
public void invokeWorkflow(@Observes SendSettlementMessageEvent event) {
    LOGGER.debug(USEFConstants.LOG_COORDINATOR_START_HANDLING_EVENT, event);
    LocalDate dateFrom = new LocalDate(event.getYear(), event.getMonth(), 1);
    LocalDate dateUntil = dateFrom.plus(Months.ONE).minusDays(1);

    LOGGER.debug("SendSettlementMessageEvent for {} until {}.", dateFrom, dateUntil);

    // Fetch all aggregators having active connections in the period defined by [dateFrom, dateUntil] .
    List<String> aggregators = corePlanboardBusinessService
            .findConnectionGroupWithConnectionsWithOverlappingValidity(dateFrom, dateUntil).values().stream()
            .flatMap(map -> map.keySet().stream())
            .map(connectionGroup -> ((AgrConnectionGroup) connectionGroup).getAggregatorDomain()).distinct()
            .collect(Collectors.toList());

    // Fetch all FlexOrderSettlement for the period
    Map<String, List<energy.usef.core.model.FlexOrderSettlement>> flexOrderSettlementPerAggregator = coreSettlementBusinessService
            .findFlexOrderSettlementsForPeriod(dateFrom, dateUntil, Optional.empty(), Optional.empty()).stream()
            .collect(Collectors.groupingBy(
                    flexOrderSettlement -> flexOrderSettlement.getFlexOrder().getParticipantDomain()));

    if (aggregators.isEmpty()) {
        LOGGER.error(
                "SendSettlementMessageEvent triggered while there are no aggregators eligible for settlement.");
        return;
    }

    for (String aggregator : aggregators) {
        SettlementMessage settlementMessage = buildSettlementMessage(
                flexOrderSettlementPerAggregator.get(aggregator), dateFrom);
        populateSettlementMessageData(settlementMessage, aggregator, dateFrom, dateUntil);
        storeSettlementMessage(aggregator, flexOrderSettlementPerAggregator.get(aggregator));
        jmsHelperService.sendMessageToOutQueue(XMLUtil.messageObjectToXml(settlementMessage));
    }
    LOGGER.debug(USEFConstants.LOG_COORDINATOR_FINISHED_HANDLING_EVENT, event);
}

From source file:energy.usef.dso.workflow.settlement.send.DsoSendSettlementMessagesCoordinator.java

License:Apache License

/**
 * This method starts the workflow when triggered by an event.
 *
 * @param event {@link SendSettlementMessageEvent} event which starts the workflow.
 *///from w  ww.  ja  v a2 s. c o  m
public void invokeWorkflow(@Observes SendSettlementMessageEvent event) {
    LOGGER.debug(USEFConstants.LOG_COORDINATOR_START_HANDLING_EVENT, event);

    LocalDate dateFrom = new LocalDate(event.getYear(), event.getMonth(), 1);
    LocalDate dateUntil = dateFrom.plus(Months.ONE).minusDays(1);

    // Fetch all aggregators having ptusettlement in the period defined by [dateFrom, dateUntil].
    List<String> aggregators = dsoPlanboardBusinessService
            .findAggregatorsWithOverlappingActivityForPeriod(dateFrom, dateUntil).stream()
            .map(AggregatorOnConnectionGroupState::getAggregator).map(Aggregator::getDomain).distinct()
            .collect(Collectors.toList());

    // Fetch all FlexOrderSettlement for the period
    Map<String, List<energy.usef.core.model.FlexOrderSettlement>> flexOrderSettlementPerAggregator = coreSettlementBusinessService
            .findFlexOrderSettlementsForPeriod(dateFrom, dateUntil, Optional.empty(), Optional.empty()).stream()
            .collect(Collectors.groupingBy(
                    flexOrderSettlement -> flexOrderSettlement.getFlexOrder().getParticipantDomain()));

    for (String aggregator : aggregators) {
        SettlementMessage settlementMessage = buildSettlementMessage(
                flexOrderSettlementPerAggregator.get(aggregator), dateFrom);
        populateSettlementMessageData(settlementMessage, aggregator, dateFrom, dateUntil);
        storeSettlementMessage(aggregator, flexOrderSettlementPerAggregator.get(aggregator));
        jmsHelperService.sendMessageToOutQueue(XMLUtil.messageObjectToXml(settlementMessage));
    }
    LOGGER.debug(USEFConstants.LOG_COORDINATOR_FINISHED_HANDLING_EVENT, event);
}

From source file:org.angnysa.yaba.service.impl.DefaultTransactionService.java

License:Open Source License

@Override
public List<Transaction> computeTransactions(TransactionDefinition td, LocalDate start, LocalDate end) {

    if (start.isAfter(end)) {
        throw new IllegalArgumentException("start is after end");
    }/*from  ww w.  ja v  a2  s .  co  m*/

    List<Transaction> result = new ArrayList<Transaction>();

    if (td.getPeriod() == null) {
        // non repeating
        if ((td.getDate().isAfter(start) || td.getDate().isEqual(start))
                && (td.getDate().isBefore(end) || td.getDate().isEqual(end))) {

            Transaction at = new Transaction();
            at.setTransactionId(td.getId());
            at.setDate(td.getDate());
            at.setAmount(td.getAmount());
            result.add(at);
        }
    } else {
        // repeating

        // get first valid date
        LocalDate current = td.getDate();
        while (current.isBefore(start)) {
            current = current.plus(td.getPeriod());
        }

        // get true last limit
        if (td.getEnd() != null && td.getEnd().isBefore(end)) {
            end = td.getEnd();
        }

        // list occurrences
        while (current.isBefore(end) || current.isEqual(end)) {

            Transaction at = new Transaction();
            at.setTransactionId(td.getId());
            at.setDate(current);
            if (td.getReconciliation(current) == null) {
                at.setAmount(td.getAmount());
            } else {
                at.setAmount(td.getReconciliation(current));
            }
            result.add(at);

            current = current.plus(td.getPeriod());
        }
    }

    Collections.sort(result, new Comparator<Transaction>() {

        @Override
        public int compare(Transaction t1, Transaction t2) {
            return t1.getDate().compareTo(t2.getDate());
        }
    });

    return result;
}