Example usage for org.joda.time Interval contains

List of usage examples for org.joda.time Interval contains

Introduction

In this page you can find the example usage for org.joda.time Interval contains.

Prototype

public boolean contains(long millisInstant) 

Source Link

Document

Does this time interval contain the specified millisecond instant.

Usage

From source file:org.jevis.commons.dataprocessing.processor.ImpulsProcessor.java

License:Open Source License

@Override
public List<JEVisSample> getResult(Task mainTask) {
    List<JEVisSample> result = new ArrayList<>();

    if (mainTask.getSubTasks().size() > 1) {
        System.out.println("Impuscleaner cannot work with more than one imput, using first only.");
    } else if (mainTask.getSubTasks().size() < 1) {
        System.out.println("Impuscleaner, no input nothing to do");
    }/*www.  j a v  a2s.c  o m*/

    List<JEVisSample> samples = mainTask.getSubTasks().get(0).getResult();

    DateTime firstTS = DateTime.now();
    DateTime lastTS = DateTime.now();
    try {
        firstTS = samples.get(0).getTimestamp();
        lastTS = samples.get(samples.size()).getTimestamp();
    } catch (JEVisException ex) {
        Logger.getLogger(ImpulsProcessor.class.getName()).log(Level.SEVERE, null, ex);
    }

    List<Interval> intervals = Options.getIntervals(mainTask, firstTS, lastTS);

    int lastPos = 0;
    for (Interval interval : intervals) {
        List<JEVisSample> samplesInPeriod = new ArrayList<>();

        for (int i = lastPos; i < samples.size(); i++) {
            try {
                if (interval.contains(samples.get(i).getTimestamp())) {
                    //                        System.out.println("add sample: " + samples.get(i));
                    samplesInPeriod.add(samples.get(i));
                } else if (samples.get(i).getTimestamp().isAfter(interval.getEnd())) {
                    lastPos = i;
                    break;
                }
            } catch (JEVisException ex) {
                System.out.println("JEVisExeption while going trou sample: " + ex.getMessage());
            }
        }

        //TODO: thi sis an dummy for 
        JEVisSample bestmatch = null;
        for (JEVisSample sample : samplesInPeriod) {

            long bestDiff = 99999999999999999l;
            try {
                long middelMili = ((interval.getEndMillis() - interval.getStartMillis()) / 2)
                        + interval.getStartMillis();
                long diff = Math.abs(sample.getTimestamp().getMillis() - middelMili);
                //                    System.out.println("Diff for: " + sample.getTimestamp() + "      -> " + diff);

                if (bestmatch != null) {
                    if (bestDiff < diff) {
                        bestDiff = diff;
                        bestmatch = sample;
                    }
                } else {
                    bestmatch = sample;
                    bestDiff = diff;
                }

            } catch (JEVisException ex) {
                System.out.println("JEVisExeption while going trou sample2: " + ex.getMessage());
            }
        }
        if (bestmatch != null) {
            System.out.println("Best match: " + bestmatch);
            result.add(bestmatch);
        }
    }

    return result;
}

From source file:org.jevis.commons.dataprocessing.processor.ImpulsProcessor.java

License:Open Source License

public List<JEVisSample> getResult(Options options, List<List<JEVisSample>> allSamples) {
    List<JEVisSample> result = new ArrayList<>();
    for (List<JEVisSample> samples : allSamples) {

        try {/*from  w ww  .j  a va  2 s . c  om*/
            _durations = Options.buildIntervals(Period.minutes(15), _offset, samples.get(0).getTimestamp(),
                    samples.get(samples.size() - 1).getTimestamp());
        } catch (JEVisException ex) {
            Logger.getLogger(ImpulsProcessor.class.getName()).log(Level.SEVERE, null, ex);
        }

        //Samples list is sorted by default
        int lastPos = 0;
        for (Interval interval : _durations) {
            //            System.out.println("Interval: " + interval);
            List<JEVisSample> samplesInPeriod = new ArrayList<>();

            for (int i = lastPos; i < samples.size(); i++) {
                try {
                    if (interval.contains(samples.get(i).getTimestamp())) {
                        //                        System.out.println("add sample: " + samples.get(i));
                        samplesInPeriod.add(samples.get(i));
                    } else if (samples.get(i).getTimestamp().isAfter(interval.getEnd())) {
                        lastPos = i;
                        break;
                    }
                } catch (JEVisException ex) {
                    System.out.println("JEVisExeption while going trou sample: " + ex.getMessage());
                }
            }

            //TODO: thi sis an dummy for 
            JEVisSample bestmatch = null;
            for (JEVisSample sample : samplesInPeriod) {

                long bestDiff = 99999999999999999l;
                try {
                    long middelMili = ((interval.getEndMillis() - interval.getStartMillis()) / 2)
                            + interval.getStartMillis();
                    long diff = Math.abs(sample.getTimestamp().getMillis() - middelMili);
                    //                    System.out.println("Diff for: " + sample.getTimestamp() + "      -> " + diff);

                    if (bestmatch != null) {
                        if (bestDiff < diff) {
                            bestDiff = diff;
                            bestmatch = sample;
                        }
                    } else {
                        bestmatch = sample;
                        bestDiff = diff;
                    }

                } catch (JEVisException ex) {
                    System.out.println("JEVisExeption while going trou sample2: " + ex.getMessage());
                }
            }
            if (bestmatch != null) {
                System.out.println("Best match: " + bestmatch);
                result.add(bestmatch);
            }

        }

    }
    return result;
}

From source file:org.killbill.clock.ClockUtil.java

License:Apache License

/**
 * The method will convert the provided LocalDate into an instant (DateTime).
 * The conversion will use a reference time that should be interpreted from a UTC standpoint.
 *
 * The the provided LocalDate overlaps with the present, the current point in time is returned (to make sure we don't
 * end up with future instant).//from   w  w  w . j  a  v a 2  s . com
 *
 * If not, we use both the provide LocalDate and LocalTime to return the DateTime in UTC
 *
 * @param inputDateInTargetTimeZone The input LocalDate as interpreted in the specified targetTimeZone
 * @param inputTimeInUTCTimeZone    The referenceTime in UTC
 * @param targetTimeZone            The target timeZone
 * @param clock                     The current clock
 * @return
 */
public static DateTime computeDateTimeWithUTCReferenceTime(final LocalDate inputDateInTargetTimeZone,
        final LocalTime inputTimeInUTCTimeZone, final DateTimeZone targetTimeZone, final Clock clock) {

    final Interval interval = inputDateInTargetTimeZone.toInterval(targetTimeZone);
    // If the input date overlaps with the present, we return NOW.
    if (interval.contains(clock.getUTCNow())) {
        return clock.getUTCNow();
    }
    // If not, we convert the inputTimeInUTCTimeZone -> inputTimeInTargetTimeZone, compute the resulting DateTime in targetTimeZone, and convert into a UTC DateTime:
    final LocalTime inputTimeInTargetTimeZone = inputTimeInUTCTimeZone
            .plusMillis(targetTimeZone.getOffset(clock.getUTCNow()));
    final DateTime resultInTargetTimeZone = new DateTime(inputDateInTargetTimeZone.getYear(),
            inputDateInTargetTimeZone.getMonthOfYear(), inputDateInTargetTimeZone.getDayOfMonth(),
            inputTimeInTargetTimeZone.getHourOfDay(), inputTimeInTargetTimeZone.getMinuteOfHour(),
            inputTimeInTargetTimeZone.getSecondOfMinute(), targetTimeZone);
    return resultInTargetTimeZone.toDateTime(DateTimeZone.UTC);
}

From source file:org.kuali.kpme.tklm.common.CalendarValidationUtil.java

License:Educational Community License

public static List<String> validateInterval(CalendarEntry payCalEntry, Long startTime, Long endTime) {
    List<String> errors = new ArrayList<String>();
    LocalDateTime pcb_ldt = payCalEntry.getBeginPeriodLocalDateTime();
    LocalDateTime pce_ldt = payCalEntry.getEndPeriodLocalDateTime();
    /*/*from www. j  a  v a 2s .c o m*/
     * LeaveCalendarValidationUtil uses DateTimeZone... TimeDetailValidation does not...
     * Does one require a non converted DateTime and the other not?
     */
    //DateTimeZone utz = HrServiceLocator.getTimezoneService().getUserTimezoneWithFallback();
    //DateTime p_cal_b_dt = pcb_ldt.toDateTime(utz);
    //DateTime p_cal_e_dt = pce_ldt.toDateTime(utz);
    DateTime p_cal_b_dt = pcb_ldt.toDateTime();
    DateTime p_cal_e_dt = pce_ldt.toDateTime();

    Interval payInterval = new Interval(p_cal_b_dt, p_cal_e_dt);
    if (errors.size() == 0 && !payInterval.contains(startTime)) {
        errors.add("The start date/time is outside the calendar period");
    }
    if (errors.size() == 0 && !payInterval.contains(endTime) && p_cal_e_dt.getMillis() != endTime) {
        errors.add("The end date/time is outside the calendar period");
    }
    return errors;
}

From source file:org.kuali.kpme.tklm.leave.accrual.bucket.KPMEAccrualCategoryBucket.java

License:Educational Community License

private void adjustAsOfDates(CalendarEntry calendarEntry, List<CalendarEntry> calendarEntries) {

    LocalDate newAsOfDate = null;

    //determine if the bucket is being switched to the current leave year
    //also compute max end date to determine if the bucket is being switched to a future leave year. ( could use leave plan service's getRollOverDate )
    boolean switchingToCurrentLeaveYear = false;
    LocalDate maxEndDate = LocalDate.now();
    for (CalendarEntry entry : calendarEntries) {
        if (entry.getHrCalendarEntryId().equals(calendarEntry.getHrCalendarEntryId())
                && entry.getHrCalendarId().equals(calendarEntry.getHrCalendarId())) {
            switchingToCurrentLeaveYear = true;
        }/*from w  w  w .j av a 2 s .  c o m*/
        if (entry.getEndPeriodDate().after(maxEndDate.toDate()))
            maxEndDate = LocalDate.fromDateFields(entry.getEndPeriodDate());
    }

    if (switchingToCurrentLeaveYear) {
        Interval otherCalendarInterval = new Interval(calendarEntry.getBeginPeriodDate().getTime(),
                calendarEntry.getEndPeriodDate().getTime());
        if (otherCalendarInterval.contains(LocalDate.now().toDate().getTime())) {
            //switching to the present calendar.
            newAsOfDate = LocalDate.now();
        } else if (otherCalendarInterval.getEnd().isBefore(LocalDate.now().toDate().getTime())) {
            //switching to a historical calendar in the current leave plan year, use calendar end date
            newAsOfDate = otherCalendarInterval.getEnd().toLocalDate().minusDays(1);
        } else {
            //switching to a future/planning calendar in the current leave plan year, use calendar start date.
            newAsOfDate = otherCalendarInterval.getStart().toLocalDate().minusDays(1);
        }
    } else if (calendarEntry.getEndPeriodDate().after(maxEndDate.toDate())) {
        //switching to a leave year beyond the current leave year, same as future/planning calendar in current leave year.
        newAsOfDate = LocalDate.fromDateFields(calendarEntry.getBeginPeriodDate()).minusDays(1);
    } else {
        //switching to a calendar period within a past leave calendar year.
        DateTime otherCalendarRolloverDate = HrServiceLocator.getLeavePlanService().getRolloverDayOfLeavePlan(
                principalCalendar.getLeavePlan(), LocalDate.fromDateFields(calendarEntry.getEndPeriodDate()));
        //for past leave calendar years, regardless of calendar period, we require values as of the rollover day.
        newAsOfDate = LocalDate.fromDateFields(otherCalendarRolloverDate.toDate()).minusDays(1);
    }

    //update asOfDates and calendar period end point dates for all leave balance objects
    for (Entry<String, List<LeaveBalance>> entry : leaveBalances.entrySet()) {
        for (LeaveBalance leaveBalance : entry.getValue()) {
            leaveBalance.asOfDate = newAsOfDate;
            leaveBalance.calendarPeriodBeginDate = LocalDate.fromDateFields(calendarEntry.getBeginPeriodDate());
            leaveBalance.calendarPeriodEndDate = LocalDate.fromDateFields(calendarEntry.getEndPeriodDate());
        }
    }

    //reset this buckets asOfDate
    asOfDate = newAsOfDate;

}

From source file:org.kuali.kpme.tklm.leave.accrual.bucket.KPMEAccrualCategoryBucket.java

License:Educational Community License

private void adjustBalances(CalendarEntry calendarEntry, DateTime rolloverDate, Set<String> assignmentKeys)
        throws KPMEBalanceException {

    //fetch calendar entries in this sequence belonging to the current leave year.
    String dateString = TKUtils.formatDate(LocalDate.now());
    List<CalendarEntry> calendarEntries = HrServiceLocator.getCalendarEntryService()
            .getAllCalendarEntriesForCalendarIdAndYear(calendarEntry.getHrCalendarId(),
                    dateString.substring(6, 10));

    //calendar change into a different leave calendar year
    if (rolloverDate != null) {

        //clear all balances.
        clearLeaveBalances();//from www. j  a  v a  2  s . co  m

        //reset the asOfDate this bucket will go off of, as well as those of the leave balances
        adjustAsOfDates(calendarEntry, calendarEntries);

        //TODO: if in current calendar year, use current date + planning months for extent of fetch.
        List<LeaveBlock> leaveBlocks = LmServiceLocator.getLeaveBlockService().getLeaveBlocksSinceCarryOver(
                principalCalendar.getPrincipalId(),
                LmServiceLocator.getLeaveBlockService().getLastCarryOverBlocks(
                        principalCalendar.getPrincipalId(), rolloverDate.minusDays(1).toLocalDate()),
                rolloverDate.plusDays(365).toLocalDate(), true);

        //retrieve (if any) last carryover blocks given the new asOfDate
        Map<String, LeaveBlock> carryOverBlocks = LmServiceLocator.getLeaveBlockService()
                .getLastCarryOverBlocks(principalCalendar.getPrincipalId(), asOfDate);

        //method taken from leave summary service - map general leave block fetch by accrual category
        Map<String, List<LeaveBlock>> accrualCategoryMappedLeaveBlocks = mapLeaveBlocksByAccrualCategory(
                leaveBlocks);

        //merge carryOverBlock map with accrualCategoryMappedLeaveBlocks.
        for (Entry<String, LeaveBlock> entry : carryOverBlocks.entrySet()) {
            //TODO: modify CarryOverLeaveBalance to identify and make use of CARRY_OVER type leave block
            if (accrualCategoryMappedLeaveBlocks.containsKey(entry.getKey()))
                accrualCategoryMappedLeaveBlocks.get(entry.getKey()).add(entry.getValue());
            else {
                List<LeaveBlock> carryOverList = new ArrayList<LeaveBlock>();
                carryOverList.add(entry.getValue());
                accrualCategoryMappedLeaveBlocks.put(entry.getKey(), carryOverList);
            }

        }
        //add leave blocks, accrual category by accrual category, to this bucket.
        for (Entry<String, List<LeaveBlock>> entry : accrualCategoryMappedLeaveBlocks.entrySet()) {
            for (LeaveBlock leaveBlock : entry.getValue()) {
                try {
                    addLeaveBlock(leaveBlock);
                } catch (KPMEBalanceException e) {
                    InstantiationException ie = new InstantiationException();
                    ie.setStackTrace(e.getStackTrace());
                    ie.printStackTrace();
                }
            }
        }
    } else {
        //Calendar change within the same leave year.

        List<String> assignmentKeyList = new ArrayList<String>();
        assignmentKeyList.addAll(assignmentKeys);

        List<LeaveBlock> leaveBlocks = new ArrayList<LeaveBlock>();

        //determine which leave blocks are affected by the calendar change, remove them, and re-add them under the new asOfDate
        if (calendarEntry.getEndPeriodFullDateTime()
                .isBefore(viewingCalendarEntry.getEndPeriodFullDateTime().getMillis())) {
            //need to remove leave blocks from otherLeaveCalendarDocument begin date to thisLeaveCalendarDocument end date
            leaveBlocks = LmServiceLocator.getLeaveBlockService().getLeaveBlocks(
                    principalCalendar.getPrincipalId(),
                    LocalDate.fromDateFields(calendarEntry.getBeginPeriodDateTime()),
                    LocalDate.fromDateFields(viewingCalendarEntry.getEndPeriodDateTime()));
            //leaveBlocks = LmServiceLocator.getLeaveBlockService().getLeaveBlocksForLeaveCalendar(principalCalendar.getPrincipalId(), LocalDate.fromDateFields(calendarEntry.getBeginPeriodDateTime()), LocalDate.fromDateFields(viewingCalendarEntry.getEndPeriodDateTime()), assignmentKeyList);
        } else {
            //need to remove leave blocks from thisLeaveCalendarDocument begin date to otherLeaveCalendarDocument end date
            leaveBlocks = LmServiceLocator.getLeaveBlockService().getLeaveBlocks(
                    principalCalendar.getPrincipalId(),
                    LocalDate.fromDateFields(viewingCalendarEntry.getBeginPeriodDateTime()),
                    LocalDate.fromDateFields(calendarEntry.getEndPeriodDateTime()));
            //leaveBlocks = LmServiceLocator.getLeaveBlockService().getLeaveBlocksForLeaveCalendar(principalCalendar.getPrincipalId(), LocalDate.fromDateFields(viewingCalendarEntry.getBeginPeriodDateTime()), LocalDate.fromDateFields(calendarEntry.getEndPeriodDateTime()), assignmentKeyList);
        }
        //remove affected leave blocks
        for (LeaveBlock block : leaveBlocks) {
            removeLeaveBlock(block);
        }

        //update this bucket and its leave balances with new relative date information
        LocalDate newAsOfDate = null;
        DateTime currentLeavePlanStartDate = HrServiceLocator.getLeavePlanService()
                .getFirstDayOfLeavePlan(principalCalendar.getLeavePlan(), LocalDate.now());
        if (calendarEntry.getEndPeriodDate().before(currentLeavePlanStartDate.toDate())) {
            //require balances as of the final day of the leave calendar year.
            DateTime calendarEntryLeavePlanRolloverDate = HrServiceLocator.getLeavePlanService()
                    .getRolloverDayOfLeavePlan(principalCalendar.getLeavePlan(),
                            LocalDate.fromDateFields(calendarEntry.getEndPeriodDate()));
            newAsOfDate = LocalDate.fromDateFields(calendarEntryLeavePlanRolloverDate.toDate()).minusDays(1);
        } else {
            Interval interval = new Interval(calendarEntry.getBeginPeriodDateTime().getTime(),
                    calendarEntry.getEndPeriodDateTime().getTime());
            if (interval.contains(LocalDate.now().toDate().getTime())) {
                newAsOfDate = LocalDate.now();
            } else if (calendarEntry.getBeginPeriodDate().before(LocalDate.now().toDate()))
                newAsOfDate = LocalDate.fromDateFields(calendarEntry.getEndPeriodDate()).minusDays(1);
            else // if it's in the calendar interval above, the equals case is taken care of, begin date must be after today
                newAsOfDate = LocalDate.fromDateFields(calendarEntry.getBeginPeriodDate()).minusDays(1);
        }

        asOfDate = newAsOfDate;

        for (Entry<String, List<LeaveBalance>> leaveBalance : leaveBalances.entrySet()) {
            for (LeaveBalance balance : leaveBalance.getValue()) {
                balance.calendarPeriodBeginDate = LocalDate
                        .fromDateFields(calendarEntry.getBeginPeriodDateTime());
                balance.calendarPeriodEndDate = LocalDate.fromDateFields(calendarEntry.getEndPeriodDateTime());
                balance.asOfDate = newAsOfDate;
            }
        }
        //re-add the affected leave blocks under the new date / calendar information
        for (LeaveBlock block : leaveBlocks) {
            addLeaveBlock(block);
        }
    }
}

From source file:org.kuali.kpme.tklm.leave.accrual.service.AccrualCategoryMaxBalanceServiceImpl.java

License:Educational Community License

@Override
public Map<String, Set<LeaveBlock>> getMaxBalanceViolations(CalendarEntry entry, String principalId) {

    Map<String, Set<LeaveBlock>> maxBalanceViolations = new HashMap<String, Set<LeaveBlock>>();

    Map<String, Set<LeaveBlock>> eligibilities = new HashMap<String, Set<LeaveBlock>>();

    eligibilities.put(HrConstants.MAX_BAL_ACTION_FREQ.LEAVE_APPROVE, new HashSet<LeaveBlock>());
    eligibilities.put(HrConstants.MAX_BAL_ACTION_FREQ.YEAR_END, new HashSet<LeaveBlock>());
    eligibilities.put(HrConstants.MAX_BAL_ACTION_FREQ.ON_DEMAND, new HashSet<LeaveBlock>());

    Interval thisEntryInterval = new Interval(entry.getBeginPeriodDate().getTime(),
            entry.getEndPeriodDate().getTime());

    LocalDate asOfDate = LocalDate.now();

    if (!thisEntryInterval.contains(asOfDate.toDate().getTime()))
        asOfDate = entry.getEndPeriodFullDateTime().minusDays(1).toLocalDate();

    PrincipalHRAttributes pha = HrServiceLocator.getPrincipalHRAttributeService()
            .getPrincipalCalendar(principalId, asOfDate);

    if (pha == null)
        return eligibilities;

    Calendar cal = pha.getLeaveCalObj();

    if (cal == null)
        return eligibilities;

    List<CalendarEntry> leaveCalEntries = HrServiceLocator.getCalendarEntryService()
            .getCalendarEntriesEndingBetweenBeginAndEndDate(cal.getHrCalendarId(),
                    entry.getBeginPeriodFullDateTime(), entry.getEndPeriodFullDateTime());
    CalendarEntry yearEndLeaveEntry = null;
    CalendarEntry leaveLeaveEntry = null;
    if (!leaveCalEntries.isEmpty()) {
        for (CalendarEntry leaveEntry : leaveCalEntries) {
            if (StringUtils.equals(cal.getCalendarName(), leaveEntry.getCalendarName())) {
                if (leaveEntry.getEndPeriodDate().compareTo(entry.getBeginPeriodDate()) > 0)
                    leaveLeaveEntry = leaveEntry;
            }/*  w  w w  .  jav a  2 s . c  o m*/
        }
    }

    Interval leavePeriodInterval = null;
    Interval yearEndPeriodInterval = null;
    if (leaveLeaveEntry != null) {
        leavePeriodInterval = new Interval(entry.getBeginPeriodDate().getTime(),
                leaveLeaveEntry.getEndPeriodDate().getTime());
        if (HrServiceLocator.getLeavePlanService().isLastCalendarPeriodOfLeavePlan(leaveLeaveEntry,
                pha.getLeavePlan(), asOfDate))
            yearEndPeriodInterval = leavePeriodInterval;
    }

    List<AccrualCategory> accrualCategories = HrServiceLocator.getAccrualCategoryService()
            .getActiveAccrualCategoriesForLeavePlan(pha.getLeavePlan(), asOfDate);

    if (!accrualCategories.isEmpty()) {

        List<LeaveBlock> leaveBlocks = new ArrayList<LeaveBlock>();
        Map<String, BigDecimal> accruedBalance = new HashMap<String, BigDecimal>();

        for (AccrualCategory accrualCategory : accrualCategories) {
            leaveBlocks.addAll(LmServiceLocator.getLeaveBlockService().getLeaveBlocksWithAccrualCategory(
                    principalId, pha.getServiceLocalDate(), asOfDate.plusDays(1),
                    accrualCategory.getAccrualCategory()));
            accruedBalance.put(accrualCategory.getLmAccrualCategoryId(), BigDecimal.ZERO);
            /*   Un-comment to consider service interval end-point changes. i.e. when defining a new action frequency - "ON_SERVICE_MILESTONE"
                        List<AccrualCategoryRule> accrualRules = HrServiceLocator.getAccrualCategoryRuleService().getActiveAccrualCategoryRules(accrualCategory.getLmAccrualCategoryId());
                        for(AccrualCategoryRule rule : accrualRules) {
                           String serviceUnits = rule.getServiceUnitOfTime();
                           LocalDate rollOverDate = null;
                           //TODO: Accrual Category Rules' start and end field allow only whole integer values. This should be reflected in storage.
                           if(StringUtils.equals(serviceUnits, "M")) {
                              rollOverDate = pha.getServiceLocalDate().plusMonths(rule.getEnd().intValue());
                           }
                           else if(StringUtils.equals(serviceUnits, "Y")) {
                              rollOverDate = pha.getServiceLocalDate().plusYears(rule.getEnd().intValue());
                           }
                           if(ObjectUtils.isNotNull(rollOverDate)) {
                              if(thisEntryInterval.contains(rollOverDate.minusDays(1).toDate().getTime())) {
             //Add a max balance allocation leave block.
             LeaveBlock allocation = new LeaveBlock();
             allocation.setAccrualCategory(accrualCategory.getAccrualCategory());
             allocation.setLeaveLocalDate(rollOverDate.minusDays(1));
             allocation.setLeaveAmount(BigDecimal.ZERO);
             allocation.setPrincipalId(principalId);
             leaveBlocks.add(allocation);
                              }
                           }
                        }
            */

            //Add a max balance allocation leave block.
            LeaveBlock allocation = new LeaveBlock();
            allocation.setAccrualCategory(accrualCategory.getAccrualCategory());

            if (thisEntryInterval.contains(LocalDate.now().toDate().getTime()))
                allocation.setLeaveLocalDate(LocalDate.now());
            else
                allocation.setLeaveLocalDate(entry.getEndPeriodFullDateTime().toLocalDate().minusDays(1));

            allocation.setLeaveAmount(BigDecimal.ZERO);
            allocation.setPrincipalId(principalId);
            allocation.setLeaveBlockType("allocation");
            leaveBlocks.add(allocation);

            if (ObjectUtils.isNotNull(leaveLeaveEntry)) {
                //if entry belongs to a time calendar, check the balances at the end date for the calendar year that ends
                //within entry's interval.
                //if entry belongs to a leave calendar, this empty block will simply duplicate and override
                //the block created above.
                allocation = new LeaveBlock();
                allocation.setAccrualCategory(accrualCategory.getAccrualCategory());
                allocation.setLeaveLocalDate(
                        leaveLeaveEntry.getEndPeriodFullDateTime().toLocalDate().minusDays(1));
                allocation.setLeaveAmount(BigDecimal.ZERO);
                allocation.setPrincipalId(principalId);
                allocation.setLeaveBlockType("allocation");
                leaveBlocks.add(allocation);
            }

            if (!leaveBlocks.isEmpty()) {
                Collections.sort(leaveBlocks, new Comparator() {

                    @Override
                    public int compare(Object o1, Object o2) {
                        LeaveBlock l1 = (LeaveBlock) o1;
                        LeaveBlock l2 = (LeaveBlock) o2;
                        return l1.getLeaveDate().compareTo(l2.getLeaveDate());
                    }

                });
            }
        }

        for (LeaveBlock lb : leaveBlocks) {
            if (StringUtils.equals(lb.getRequestStatus(), HrConstants.REQUEST_STATUS.DISAPPROVED)
                    || StringUtils.equals(lb.getRequestStatus(), HrConstants.REQUEST_STATUS.DEFERRED))
                continue;
            AccrualCategory accrualCategory = HrServiceLocator.getAccrualCategoryService()
                    .getAccrualCategory(lb.getAccrualCategory(), lb.getLeaveLocalDate());
            BigDecimal tally = accruedBalance.get(accrualCategory.getLmAccrualCategoryId());
            tally = tally.add(lb.getLeaveAmount());

            AccrualCategoryRule asOfLeaveDateRule = HrServiceLocator.getAccrualCategoryRuleService()
                    .getAccrualCategoryRuleForDate(accrualCategory, lb.getLeaveLocalDate(),
                            pha.getServiceLocalDate());

            //Employee overrides...
            if (ObjectUtils.isNotNull(asOfLeaveDateRule)) {
                if (StringUtils.equals(asOfLeaveDateRule.getMaxBalFlag(), "Y")) {
                    if (StringUtils.isNotBlank(asOfLeaveDateRule.getActionAtMaxBalance())) {
                        if (ObjectUtils.isNotNull(asOfLeaveDateRule.getMaxBalanceActionFrequency())) {

                            if (maxBalanceViolations.get(asOfLeaveDateRule.getLmAccrualCategoryId()) == null)
                                maxBalanceViolations.put(asOfLeaveDateRule.getLmAccrualCategoryId(),
                                        new HashSet<LeaveBlock>());

                            BigDecimal maxBalance = asOfLeaveDateRule.getMaxBalance();

                            BigDecimal fte = HrServiceLocator.getJobService()
                                    .getFteSumForAllActiveLeaveEligibleJobs(principalId, LocalDate.now());
                            BigDecimal adjustedMaxBalance = maxBalance.multiply(fte);

                            BigDecimal maxAnnualCarryOver = null;
                            if (ObjectUtils.isNotNull(asOfLeaveDateRule.getMaxCarryOver()))
                                maxAnnualCarryOver = new BigDecimal(asOfLeaveDateRule.getMaxCarryOver());

                            BigDecimal adjustedMaxAnnualCarryOver = null;
                            if (ObjectUtils.isNotNull(maxAnnualCarryOver)) {
                                adjustedMaxAnnualCarryOver = maxAnnualCarryOver.multiply(fte);
                            }

                            List<EmployeeOverride> overrides = LmServiceLocator.getEmployeeOverrideService()
                                    .getEmployeeOverrides(principalId, lb.getLeaveLocalDate());
                            for (EmployeeOverride override : overrides) {
                                if (StringUtils.equals(override.getAccrualCategory(),
                                        lb.getAccrualCategory())) {
                                    //Do not pro-rate override values for FTE.
                                    if (StringUtils.equals(override.getOverrideType(), "MB"))
                                        adjustedMaxBalance = new BigDecimal(override.getOverrideValue());
                                    if (StringUtils.equals(override.getOverrideType(), "MAC"))
                                        adjustedMaxAnnualCarryOver = new BigDecimal(
                                                override.getOverrideValue());
                                }
                            }

                            boolean yearEndCandidate = false;
                            if (StringUtils.equals(asOfLeaveDateRule.getMaxBalanceActionFrequency(),
                                    HrConstants.MAX_BAL_ACTION_FREQ.YEAR_END)
                                    && adjustedMaxAnnualCarryOver != null) {
                                yearEndCandidate = true;
                            }
                            //callers must determine if the violation exists on the calendar prior to the leave plan's calendar year end date.
                            if (tally.compareTo(adjustedMaxBalance) > 0
                                    || (yearEndCandidate && tally.compareTo(adjustedMaxAnnualCarryOver) > 0)) {
                                if (maxBalanceViolations.get(asOfLeaveDateRule.getLmAccrualCategoryId())
                                        .isEmpty()) {
                                    maxBalanceViolations.get(asOfLeaveDateRule.getLmAccrualCategoryId())
                                            .add(lb);
                                } else {
                                    Set<LeaveBlock> eligibleLeaveBlocks = maxBalanceViolations
                                            .get(asOfLeaveDateRule.getLmAccrualCategoryId());
                                    CalendarBlockContract previousInfraction = retreivePreviousInfraction(
                                            eligibleLeaveBlocks, lb, leavePeriodInterval, yearEndPeriodInterval,
                                            thisEntryInterval, asOfLeaveDateRule);

                                    if (previousInfraction != null)
                                        eligibleLeaveBlocks.remove(previousInfraction);
                                    /* Replace the leave block with the most recent infraction that occurred so long as the infraction takes place
                                     * before the end of the [underlying] leave period. This includes accrual categories that undergo a rule change
                                     * as the result of the employee crossing a service milestone.
                                     * Doing so will correctly trigger the action on timesheets that stagger a leave
                                     * period end date, since the block would exist on a leave period whose end date is not contained within
                                     * the time period. For on-demand frequencies, we want to replace the block with the latest no matter what.
                                     * Doing so will ensure that the latest rule is used to initiate the action.
                                     * 
                                     */
                                    eligibleLeaveBlocks.add(lb);
                                    maxBalanceViolations.put(asOfLeaveDateRule.getLmAccrualCategoryId(),
                                            eligibleLeaveBlocks);
                                }
                            } else // the leave amount (usage), as of lb's leave date, is under the balance limit.
                            if (!maxBalanceViolations.get(asOfLeaveDateRule.getLmAccrualCategoryId())
                                    .isEmpty()) {
                                //if there was a previous infraction, it must be removed so long as the leave date of lb lies within
                                //the same period as the previous infraction.
                                Set<LeaveBlock> eligibleLeaveBlocks = maxBalanceViolations
                                        .get(asOfLeaveDateRule.getLmAccrualCategoryId());
                                CalendarBlockContract previousInfraction = retreivePreviousInfraction(
                                        eligibleLeaveBlocks, lb, leavePeriodInterval, yearEndPeriodInterval,
                                        thisEntryInterval, asOfLeaveDateRule);
                                if (previousInfraction != null) {
                                    eligibleLeaveBlocks.remove(previousInfraction);
                                    maxBalanceViolations.put(asOfLeaveDateRule.getLmAccrualCategoryId(),
                                            eligibleLeaveBlocks);
                                }
                            }
                        }
                    }
                }
            }
            accruedBalance.put(accrualCategory.getLmAccrualCategoryId(), tally);
        }
    }

    for (Entry<String, Set<LeaveBlock>> entries : maxBalanceViolations.entrySet()) {
        for (LeaveBlock lb : entries.getValue()) {
            AccrualCategoryRule aRule = HrServiceLocator.getAccrualCategoryRuleService()
                    .getAccrualCategoryRule(lb.getAccrualCategoryRuleId());
            eligibilities.get(aRule.getMaxBalanceActionFrequency()).add(lb);
        }
    }

    return eligibilities;
}

From source file:org.kuali.kpme.tklm.leave.accrual.service.AccrualCategoryMaxBalanceServiceImpl.java

License:Educational Community License

protected CalendarBlockContract retreivePreviousInfraction(Set<LeaveBlock> eligibleLeaveBlocks, LeaveBlock lb,
        Interval leavePeriodInterval, Interval yearEndPeriodInterval, Interval thisEntryInterval,
        AccrualCategoryRule asOfLeaveDateRule) {
    CalendarBlockContract tempLB = null;
    for (LeaveBlock block : eligibleLeaveBlocks) {
        AccrualCategoryRule blockRule = HrServiceLocator.getAccrualCategoryRuleService()
                .getAccrualCategoryRule(block.getAccrualCategoryRuleId());
        if (StringUtils.equals(asOfLeaveDateRule.getLmAccrualCategoryRuleId(),
                blockRule.getLmAccrualCategoryRuleId())) {
            if ((StringUtils.equals(asOfLeaveDateRule.getMaxBalanceActionFrequency(),
                    HrConstants.MAX_BAL_ACTION_FREQ.ON_DEMAND)
                    && StringUtils.equals(blockRule.getMaxBalanceActionFrequency(),
                            HrConstants.MAX_BAL_ACTION_FREQ.ON_DEMAND))
                    || (leavePeriodInterval != null && leavePeriodInterval.contains(lb.getLeaveDate().getTime())
                            && leavePeriodInterval.contains(block.getLeaveDate().getTime()))
                    || (leavePeriodInterval == null
                            && thisEntryInterval.contains(block.getLeaveDate().getTime())
                            && thisEntryInterval.contains(lb.getLeaveDate().getTime()))
                    || (StringUtils.equals(asOfLeaveDateRule.getMaxBalanceActionFrequency(),
                            HrConstants.MAX_BAL_ACTION_FREQ.YEAR_END)
                            && StringUtils.equals(blockRule.getMaxBalanceActionFrequency(),
                                    HrConstants.MAX_BAL_ACTION_FREQ.YEAR_END)
                            && (yearEndPeriodInterval == null
                                    || (yearEndPeriodInterval.contains(block.getLeaveDate().getTime())
                                            && yearEndPeriodInterval.contains(lb.getLeaveDate().getTime())))
                            //year end we replace if the two infractions are not within the same leave period.
                            //if yearEndPeriodInterval != null, the conditional for leave approve should have already evaluated to true.
                            //i.e. yearEndPeriodInterval != null will never be evaluated.
                            || block.getLeaveDate().before(thisEntryInterval.getStart().toDate()))) {
                tempLB = block;//from   ww w.ja va  2 s .  c  om
                break;
            }
        } else if (StringUtils.equals(blockRule.getMaxBalanceActionFrequency(),
                HrConstants.MAX_BAL_ACTION_FREQ.ON_DEMAND)
                //always supersede on-demand action frequencies
                || (StringUtils.equals(blockRule.getMaxBalanceActionFrequency(),
                        HrConstants.MAX_BAL_ACTION_FREQ.LEAVE_APPROVE)
                        && ((leavePeriodInterval != null
                                && leavePeriodInterval.contains(block.getLeaveDate().getTime())
                                && leavePeriodInterval.contains(lb.getLeaveDate().getTime()))
                                || (leavePeriodInterval == null
                                        && thisEntryInterval.contains(block.getLeaveDate().getTime())
                                        && thisEntryInterval.contains(lb.getLeaveDate().getTime()))))
                //leave approve is replaced only if the replacement lies within the same leave period.
                || (StringUtils.equals(blockRule.getMaxBalanceActionFrequency(),
                        HrConstants.MAX_BAL_ACTION_FREQ.YEAR_END)
                        && (yearEndPeriodInterval == null
                                || (yearEndPeriodInterval.contains(block.getLeaveDate().getTime())
                                        && yearEndPeriodInterval.contains(lb.getLeaveDate().getTime()))))
                //year end is superseded only if the new rule goes into effect before the current leave plan calendar year end date.
                || block.getLeaveDate().before(thisEntryInterval.getStart().toDate())) {
            tempLB = block;
            break;
        }
    }
    return tempLB;
}

From source file:org.kuali.kpme.tklm.leave.block.service.LeaveBlockServiceImpl.java

License:Educational Community License

@Override
public void addLeaveBlocks(DateTime beginDate, DateTime endDate, CalendarEntry ce, String selectedEarnCode,
        BigDecimal hours, String description, Assignment selectedAssignment, String spanningWeeks,
        String leaveBlockType, String principalId) {

    DateTimeZone timezone = HrServiceLocator.getTimezoneService().getUserTimezoneWithFallback();
    DateTime calBeginDateTime = beginDate;
    DateTime calEndDateTime = endDate;//from   ww  w . j  a  v a2 s .co m

    if (ce != null) {
        calBeginDateTime = ce.getBeginPeriodLocalDateTime().toDateTime();
        calEndDateTime = ce.getEndPeriodLocalDateTime().toDateTime();
    } else {
        LOG.error("Calendar Entry parameter is null.");
        return;
        //          throw new RuntimeException("Calendar Entry parameter is null.");
    }

    Interval calendarInterval = new Interval(calBeginDateTime, calEndDateTime);

    // To create the correct interval by the given begin and end dates,
    // we need to plus one day on the end date to include that date
    List<Interval> leaveBlockIntervals = TKUtils.createDaySpan(beginDate.toLocalDate().toDateTimeAtStartOfDay(),
            endDate.toLocalDate().toDateTimeAtStartOfDay().plusDays(1), TKUtils.getSystemDateTimeZone());

    // need to use beginDate and endDate of the calendar to find all leaveBlocks since LeaveCalendarDocument Id is not always available
    List<LeaveBlock> currentLeaveBlocks = getLeaveBlocks(principalId, calBeginDateTime.toLocalDate(),
            calEndDateTime.toLocalDate());

    // use the current calendar's begin and end date to figure out if this pay period has a leaveDocument
    LeaveCalendarDocumentHeader lcdh = LmServiceLocator.getLeaveCalendarDocumentHeaderService()
            .getDocumentHeader(principalId, ce.getBeginPeriodLocalDateTime().toDateTime(),
                    ce.getEndPeriodLocalDateTime().toDateTime());
    String docId = lcdh == null ? null : lcdh.getDocumentId();

    // TODO: need to integrate with the scheduled timeoff.
    Interval firstDay = null;
    DateTime currentDate = beginDate;
    for (Interval leaveBlockInt : leaveBlockIntervals) {
        if (calendarInterval.contains(leaveBlockInt)) {
            // KPME-1446 if "Include weekends" check box is checked, don't add Sat and Sun to the leaveblock list
            if (StringUtils.isEmpty(spanningWeeks)
                    && (leaveBlockInt.getStart().getDayOfWeek() == DateTimeConstants.SATURDAY
                            || leaveBlockInt.getStart().getDayOfWeek() == DateTimeConstants.SUNDAY)) {

                // do nothing
            } else {

                // Currently, we store the accrual category value in the leave code table, but store accrual category id in the leaveBlock.
                // That's why there is a two step server call to get the id. This might be changed in the future.

                CalendarEntry calendarEntry = HrServiceLocator.getCalendarEntryService()
                        .getCurrentCalendarEntryByCalendarId(ce.getHrCalendarId(),
                                new LocalDate().toDateTimeAtStartOfDay());
                DateTime leaveBlockDate = leaveBlockInt.getStart();

                String requestStatus = HrConstants.REQUEST_STATUS.USAGE;
                if (LmServiceLocator.getLeaveApprovalService().isActiveAssignmentFoundOnJobFlsaStatus(
                        principalId, HrConstants.FLSA_STATUS_NON_EXEMPT, true)) {
                    TimesheetDocumentHeader tdh = TkServiceLocator.getTimesheetDocumentHeaderService()
                            .getDocumentHeaderForDate(principalId, leaveBlockDate);
                    if (tdh != null) {
                        if (DateUtils.isSameDay(leaveBlockDate.toDate(), tdh.getEndDate())
                                || leaveBlockDate.isAfter(tdh.getEndDateTime())) {
                            requestStatus = HrConstants.REQUEST_STATUS.PLANNED;
                        }
                    } else {
                        requestStatus = HrConstants.REQUEST_STATUS.PLANNED;
                    }
                } else {
                    if (DateUtils.isSameDay(leaveBlockDate.toDate(), calendarEntry.getEndPeriodDateTime())
                            || leaveBlockDate.isAfter(calendarEntry.getEndPeriodFullDateTime())) {
                        requestStatus = HrConstants.REQUEST_STATUS.PLANNED;
                    }
                }

                EarnCode earnCodeObj = HrServiceLocator.getEarnCodeService().getEarnCode(selectedEarnCode,
                        ce.getEndPeriodLocalDateTime().toDateTime().toLocalDate());

                if (earnCodeObj != null
                        && earnCodeObj.getRecordMethod().equals(HrConstants.RECORD_METHOD.TIME)) {
                    if (firstDay != null) {
                        if (!leaveBlockInt.contains(endDate)) {
                            currentDate = leaveBlockInt.getStart();
                        } else if ((leaveBlockInt.getStartMillis() - endDate.getMillis()) != 0) {

                            hours = TKUtils.getHoursBetween(leaveBlockInt.getStartMillis(),
                                    endDate.getMillis());
                            hours = negateHoursIfNecessary(leaveBlockType, hours);

                            LeaveBlock leaveBlock = buildLeaveBlock(leaveBlockInt.getStart().toLocalDate(),
                                    docId, principalId, selectedEarnCode, hours, description,
                                    earnCodeObj.getAccrualCategory(), selectedAssignment, requestStatus,
                                    leaveBlockType, leaveBlockInt.getStart(), endDate);

                            if (!currentLeaveBlocks.contains(leaveBlock)) {
                                currentLeaveBlocks.add(leaveBlock);
                            }
                            break;
                        }
                    }
                    if (leaveBlockInt.contains(currentDate)) {

                        firstDay = leaveBlockInt;

                        if (leaveBlockInt.contains(endDate)
                                || (endDate.getMillis() == leaveBlockInt.getEnd().getMillis())) {

                            hours = TKUtils.getHoursBetween(currentDate.getMillis(), endDate.getMillis());
                            hours = negateHoursIfNecessary(leaveBlockType, hours);

                            LeaveBlock leaveBlock = buildLeaveBlock(leaveBlockInt.getStart().toLocalDate(),
                                    docId, principalId, selectedEarnCode, hours, description,
                                    earnCodeObj.getAccrualCategory(), selectedAssignment, requestStatus,
                                    leaveBlockType, currentDate, endDate);

                            if (!currentLeaveBlocks.contains(leaveBlock)) {
                                currentLeaveBlocks.add(leaveBlock);
                            }

                            break;

                        } else {
                            // create a leave block that wraps the 24 hr day
                            hours = TKUtils.getHoursBetween(currentDate.getMillis(), firstDay.getEndMillis());
                            hours = negateHoursIfNecessary(leaveBlockType, hours);

                            LeaveBlock leaveBlock = buildLeaveBlock(leaveBlockInt.getStart().toLocalDate(),
                                    docId, principalId, selectedEarnCode, hours, description,
                                    earnCodeObj.getAccrualCategory(), selectedAssignment, requestStatus,
                                    leaveBlockType, currentDate, firstDay.getEnd());

                            if (!currentLeaveBlocks.contains(leaveBlock)) {
                                currentLeaveBlocks.add(leaveBlock);
                            }

                        }
                    }
                } else {
                    hours = negateHoursIfNecessary(leaveBlockType, hours);
                    LeaveBlock leaveBlock = buildLeaveBlock(leaveBlockInt.getStart().toLocalDate(), docId,
                            principalId, selectedEarnCode, hours, description, earnCodeObj.getAccrualCategory(),
                            selectedAssignment, requestStatus, leaveBlockType, null, null);
                    if (!currentLeaveBlocks.contains(leaveBlock)) {
                        currentLeaveBlocks.add(leaveBlock);
                    }
                }
            }
        }
    }
    saveLeaveBlocks(currentLeaveBlocks);
}

From source file:org.kuali.kpme.tklm.leave.calendar.validation.LeaveCalendarValidationUtil.java

License:Educational Community License

public static List<String> validateInterval(CalendarEntry payCalEntry, Long startTime, Long endTime) {
    List<String> errors = new ArrayList<String>();
    LocalDateTime pcb_ldt = payCalEntry.getBeginPeriodLocalDateTime();
    LocalDateTime pce_ldt = payCalEntry.getEndPeriodLocalDateTime();
    DateTimeZone utz = HrServiceLocator.getTimezoneService().getUserTimezoneWithFallback();
    DateTime p_cal_b_dt = pcb_ldt.toDateTime(utz);
    DateTime p_cal_e_dt = pce_ldt.toDateTime(utz);

    Interval payInterval = new Interval(p_cal_b_dt, p_cal_e_dt);
    if (errors.size() == 0 && !payInterval.contains(startTime)) {
        errors.add("The start date/time is outside the pay period");
    }/*w w w.  j  a  va 2s . c  om*/
    if (errors.size() == 0 && !payInterval.contains(endTime) && p_cal_e_dt.getMillis() != endTime) {
        errors.add("The end date/time is outside the pay period");
    }
    return errors;
}