Example usage for org.joda.time LocalDate now

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

Introduction

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

Prototype

public static LocalDate now() 

Source Link

Document

Obtains a LocalDate set to the current system millisecond time using ISOChronology in the default time zone.

Usage

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

License:Educational Community License

public YearToDateUsageLeaveBalance(AccrualCategory accrualCategory, PrincipalHRAttributes principalCalendar) {
    super(accrualCategory, principalCalendar);
    asOfDate = LocalDate.now();
    leaveBlocks = new ArrayList<LeaveBlock>();
}

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;
            }//from   ww  w . j  a v a  2  s.co 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.AccrualServiceImpl.java

License:Educational Community License

@Override
public boolean isEmpoyeementFutureStatusChanged(String principalId, DateTime startDate, DateTime endDate) {
    if (endDate.isAfter(LocalDate.now().toDateTimeAtStartOfDay())) {
        RateRangeAggregate rrAggregate = this.buildRateRangeAggregate(principalId, startDate, endDate);
        if (rrAggregate.isRateRangeChanged()) {
            return true;
        }//from ww w.j a  v a2 s  . c  o  m
    }
    return false;
}

From source file:org.kuali.kpme.tklm.leave.adjustment.dao.LeaveAdjustmentDaoOjbImpl.java

License:Educational Community License

@Override
public List<LeaveAdjustment> getLeaveAdjustments(LocalDate fromEffdt, LocalDate toEffdt, String principalId,
        String accrualCategory, String earnCode) {
    List<LeaveAdjustment> results = new ArrayList<LeaveAdjustment>();

    Criteria root = new Criteria();

    Criteria effectiveDateFilter = new Criteria();
    if (fromEffdt != null) {
        effectiveDateFilter.addGreaterOrEqualThan("effectiveDate", fromEffdt.toDate());
    }//from   ww w.j a  v a  2 s. c o  m
    if (toEffdt != null) {
        effectiveDateFilter.addLessOrEqualThan("effectiveDate", toEffdt.toDate());
    }
    if (fromEffdt == null && toEffdt == null) {
        effectiveDateFilter.addLessOrEqualThan("effectiveDate", LocalDate.now().toDate());
    }
    root.addAndCriteria(effectiveDateFilter);

    if (StringUtils.isNotBlank(principalId)) {
        root.addLike("principalId", principalId);
    }

    if (StringUtils.isNotBlank(accrualCategory)) {
        root.addLike("accrualCategory", accrualCategory);
    }

    if (StringUtils.isNotBlank(earnCode)) {
        root.addLike("earnCode", earnCode);
    }

    Query query = QueryFactory.newQuery(LeaveAdjustment.class, root);
    results.addAll(getPersistenceBrokerTemplate().getCollectionByQuery(query));

    return results;
}

From source file:org.kuali.kpme.tklm.leave.approval.service.LeaveApprovalServiceImpl.java

License:Educational Community License

@Override
public void removeNonLeaveEmployees(List<String> principalIds) {
    if (CollectionUtils.isNotEmpty(principalIds)) {
        LocalDate asOfDate = LocalDate.now();
        List<String> idList = new ArrayList<String>();
        idList.addAll(principalIds);//w w w  .  j a  v a 2 s. com
        for (String principalId : idList) {
            boolean leaveFlag = false;
            List<Assignment> activeAssignments = HrServiceLocator.getAssignmentService()
                    .getAssignments(principalId, asOfDate);
            if (CollectionUtils.isNotEmpty(activeAssignments)) {
                for (Assignment assignment : activeAssignments) {
                    if (assignment != null && assignment.getJob() != null
                            && assignment.getJob().isEligibleForLeave()) {
                        leaveFlag = true;
                        break;
                    }
                }
                if (!leaveFlag) { // employee is not eligible for leave, remove the id from principalIds
                    principalIds.remove(principalId);
                }
            }
        }
    }
}

From source file:org.kuali.kpme.tklm.leave.approval.service.LeaveApprovalServiceImpl.java

License:Educational Community License

@Override
public boolean isActiveAssignmentFoundOnJobFlsaStatus(String principalId, String flsaStatus,
        boolean chkForLeaveEligible) {
    boolean isActiveAssFound = false;
    LocalDate asOfDate = LocalDate.now();
    List<Assignment> activeAssignments = HrServiceLocator.getAssignmentService().getAssignments(principalId,
            asOfDate);/*from w w  w  . jav a 2  s  . c o  m*/
    if (activeAssignments != null && !activeAssignments.isEmpty()) {
        for (Assignment assignment : activeAssignments) {
            if (assignment != null && assignment.getJob() != null && assignment.getJob().getFlsaStatus() != null
                    && assignment.getJob().getFlsaStatus().equalsIgnoreCase(flsaStatus)) {
                if (chkForLeaveEligible) {
                    isActiveAssFound = assignment.getJob().isEligibleForLeave();
                    if (!isActiveAssFound) {
                        continue;
                    }
                }
                isActiveAssFound = true;
                break;
            }
        }
    }
    return isActiveAssFound;
}

From source file:org.kuali.kpme.tklm.leave.approval.web.LeaveApprovalAction.java

License:Educational Community License

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    LeaveApprovalActionForm leaveApprovalActionForm = (LeaveApprovalActionForm) form;
    String documentId = leaveApprovalActionForm.getDocumentId();

    setSearchFields(leaveApprovalActionForm);

    CalendarEntry calendarEntry = null;/*  ww  w .jav a  2  s . c o m*/
    if (StringUtils.isNotBlank(documentId)) {
        LeaveCalendarDocument leaveCalendarDocument = LmServiceLocator.getLeaveCalendarService()
                .getLeaveCalendarDocument(documentId);

        if (leaveCalendarDocument != null) {
            calendarEntry = leaveCalendarDocument.getCalendarEntry();
            leaveApprovalActionForm.setCalendarDocument(leaveCalendarDocument);
        }
    } else if (leaveApprovalActionForm.getHrCalendarEntryId() != null) {
        calendarEntry = HrServiceLocator.getCalendarEntryService()
                .getCalendarEntry(leaveApprovalActionForm.getHrCalendarEntryId());
    } else {
        Calendar calendar = HrServiceLocator.getCalendarService()
                .getCalendarByGroup(leaveApprovalActionForm.getSelectedPayCalendarGroup());
        if (calendar != null) {
            calendarEntry = HrServiceLocator.getCalendarEntryService().getCurrentCalendarEntryByCalendarId(
                    calendar.getHrCalendarId(), LocalDate.now().toDateTimeAtStartOfDay());
        }
    }

    if (calendarEntry != null) {
        leaveApprovalActionForm.setHrCalendarEntryId(calendarEntry.getHrCalendarEntryId());
        leaveApprovalActionForm.setCalendarEntry(calendarEntry);
        leaveApprovalActionForm.setBeginCalendarEntryDate(calendarEntry.getBeginPeriodDateTime());
        leaveApprovalActionForm
                .setEndCalendarEntryDate(DateUtils.addMilliseconds(calendarEntry.getEndPeriodDateTime(), -1));

        CalendarEntry prevCalendarEntry = HrServiceLocator.getCalendarEntryService()
                .getPreviousCalendarEntryByCalendarId(calendarEntry.getHrCalendarId(), calendarEntry);
        leaveApprovalActionForm.setPrevHrCalendarEntryId(
                prevCalendarEntry != null ? prevCalendarEntry.getHrCalendarEntryId() : null);

        CalendarEntry nextCalendarEntry = HrServiceLocator.getCalendarEntryService()
                .getNextCalendarEntryByCalendarId(calendarEntry.getHrCalendarId(), calendarEntry);
        leaveApprovalActionForm.setNextHrCalendarEntryId(
                nextCalendarEntry != null ? nextCalendarEntry.getHrCalendarEntryId() : null);

        setCalendarFields(leaveApprovalActionForm);
    }

    ActionForward actionForward = super.execute(mapping, form, request, response);

    if (calendarEntry != null) {
        leaveApprovalActionForm.setLeaveCalendarDates(
                LmServiceLocator.getLeaveSummaryService().getLeaveSummaryDates(calendarEntry));
        setApprovalTables(leaveApprovalActionForm, request, getPrincipalIds(leaveApprovalActionForm));
    }

    return actionForward;
}

From source file:org.kuali.kpme.tklm.leave.batch.AccrualJob.java

License:Educational Community License

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    String batchUserPrincipalId = getBatchUserPrincipalId();

    if (batchUserPrincipalId != null) {
        LocalDate asOfDate = LocalDate.now();
        List<Assignment> assignments = getAssignmentService().getActiveAssignments(asOfDate);

        for (Assignment assignment : assignments) {
            if (assignment.getJob().isEligibleForLeave()) {
                String principalId = assignment.getPrincipalId();

                PrincipalHRAttributes principalHRAttributes = getPrincipalHRAttributesService()
                        .getPrincipalCalendar(principalId, asOfDate);
                if (principalHRAttributes != null) {
                    LeavePlan leavePlan = getLeavePlanService().getLeavePlan(
                            principalHRAttributes.getLeavePlan(),
                            principalHRAttributes.getEffectiveLocalDate());
                    if (leavePlan != null) {
                        DateTime endDate = asOfDate.toDateTimeAtStartOfDay()
                                .plusMonths(Integer.parseInt(leavePlan.getPlanningMonths()));
                        getAccrualService().runAccrual(principalId, asOfDate.toDateTimeAtStartOfDay(), endDate,
                                true, batchUserPrincipalId);
                    }//from   w ww  . j  ava  2  s.  c  om
                }
            }
        }
    } else {
        String principalName = ConfigContext.getCurrentContextConfig()
                .getProperty(TkConstants.BATCH_USER_PRINCIPAL_NAME);
        LOG.error("Could not run batch jobs due to missing batch user " + principalName);
    }
}

From source file:org.kuali.kpme.tklm.leave.batch.CarryOverJob.java

License:Educational Community License

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    String batchUserPrincipalId = getBatchUserPrincipalId();

    if (batchUserPrincipalId != null) {
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        String leavePlan = jobDataMap.getString("leavePlan");
        if (leavePlan != null) {

            LocalDate asOfDate = LocalDate.now();
            LeavePlan leavePlanObj = getLeavePlanService().getLeavePlan(leavePlan, asOfDate);
            List<Assignment> assignments = getAssignmentService().getActiveAssignments(asOfDate);

            //holds a list of principalIds so this isn't run multiple time for the same person
            Set<String> principalIds = new HashSet<String>();
            for (Assignment assignment : assignments) {
                String principalId = assignment.getPrincipalId();
                if (assignment.getJob().isEligibleForLeave() && !principalIds.contains(principalId)) {

                    PrincipalHRAttributes principalHRAttributes = getPrincipalHRAttributesService()
                            .getPrincipalCalendar(principalId, asOfDate);
                    principalIds.add(principalId);

                    if (principalHRAttributes != null) {
                        LocalDate serviceDate = principalHRAttributes.getServiceLocalDate();
                        if (serviceDate != null) {

                            if (leavePlanObj != null && leavePlanObj.getLeavePlan()
                                    .equalsIgnoreCase(principalHRAttributes.getLeavePlan())) {

                                DateTime leavePlanStartDate = getLeavePlanService()
                                        .getFirstDayOfLeavePlan(leavePlan, LocalDate.now());

                                DateTime lpPreviousLastDay = (new LocalDateTime(leavePlanStartDate))
                                        .toDateTime().minus(1);
                                DateTime lpPreviousFirstDay = getLeavePlanService()
                                        .getFirstDayOfLeavePlan(leavePlan, lpPreviousLastDay.toLocalDate());

                                List<LeaveBlock> prevYearCarryOverleaveBlocks = getLeaveBlockService()
                                        .getLeaveBlocksWithType(principalId, lpPreviousFirstDay.toLocalDate(),
                                                lpPreviousLastDay.toLocalDate(),
                                                LMConstants.LEAVE_BLOCK_TYPE.CARRY_OVER);
                                LeaveSummary leaveSummary = getLeaveSummaryService()
                                        .getLeaveSummaryAsOfDateWithoutFuture(principalId,
                                                lpPreviousLastDay.toLocalDate());
                                //no existing carry over blocks.  just create new
                                if (CollectionUtils.isEmpty(prevYearCarryOverleaveBlocks)) {
                                    getLeaveBlockService().saveLeaveBlocks(createCarryOverLeaveBlocks(
                                            principalId, lpPreviousLastDay, leaveSummary));
                                } else {
                                    Map<String, LeaveBlock> existingCarryOver = new HashMap<String, LeaveBlock>(
                                            prevYearCarryOverleaveBlocks.size());
                                    // just easier to get to things when in a map...
                                    for (LeaveBlock lb : prevYearCarryOverleaveBlocks) {
                                        existingCarryOver.put(lb.getAccrualCategory(), lb);
                                    }//from  ww w.j  a  v  a  2 s.  c  om

                                    // update existing first
                                    for (Map.Entry<String, LeaveBlock> entry : existingCarryOver.entrySet()) {
                                        LeaveBlock carryOverBlock = entry.getValue();
                                        LeaveSummaryRow lsr = leaveSummary
                                                .getLeaveSummaryRowForAccrualCtgy(entry.getKey());

                                        //update values
                                        if (lsr.getAccruedBalance() != null) {
                                            if (lsr.getMaxCarryOver() != null && lsr.getAccruedBalance()
                                                    .compareTo(lsr.getMaxCarryOver()) > 0) {
                                                carryOverBlock.setLeaveAmount(lsr.getMaxCarryOver());
                                            } else {
                                                carryOverBlock.setLeaveAmount(lsr.getAccruedBalance());
                                            }
                                        }
                                        getLeaveBlockService().updateLeaveBlock(carryOverBlock,
                                                batchUserPrincipalId);
                                        //remove row from leave summary
                                        leaveSummary.getLeaveSummaryRows().remove(lsr);
                                    }

                                    // create for any new accrual categories
                                    getLeaveBlockService().saveLeaveBlocks(createCarryOverLeaveBlocks(
                                            principalId, lpPreviousLastDay, leaveSummary));
                                }
                            }
                        }
                    }
                }
            }
        }
    } else {
        String principalName = ConfigContext.getCurrentContextConfig()
                .getProperty(TkConstants.BATCH_USER_PRINCIPAL_NAME);
        LOG.error("Could not run batch jobs due to missing batch user " + principalName);
    }

}

From source file:org.kuali.kpme.tklm.leave.batch.CarryOverSchedulerJob.java

License:Educational Community License

@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
    LocalDate asOfDate = LocalDate.now();
    List<LeavePlan> leavePlans = HrServiceLocator.getLeavePlanService()
            .getLeavePlansNeedsCarryOverScheduled(getLeavePlanPollingWindow(), asOfDate);
    try {//from  w  w  w.j  ava 2  s.  com
        if (leavePlans != null && !leavePlans.isEmpty()) {
            DateTime current = asOfDate.toDateTimeAtStartOfDay();
            DateTime windowStart = current.minusDays(getLeavePlanPollingWindow());
            DateTime windowEnd = current.plusDays(getLeavePlanPollingWindow());

            // schedule batch job for all LeavePlans who fall in leave polling window.
            for (LeavePlan leavePlan : leavePlans) {
                if (leavePlan.getBatchPriorYearCarryOverStartDate() != null
                        && leavePlan.getBatchPriorYearCarryOverStartTime() != null) {
                    DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd");
                    DateTime batchPriorYearCarryOverStartDateTime = formatter
                            .parseDateTime(leavePlan.getBatchPriorYearCarryOverStartDate())
                            .plus(leavePlan.getBatchPriorYearCarryOverStartTime().getTime());
                    if (batchPriorYearCarryOverStartDateTime.compareTo(windowStart) >= 0
                            && batchPriorYearCarryOverStartDateTime.compareTo(windowEnd) <= 0) {
                        getBatchJobService().scheduleLeaveCarryOverJobs(leavePlan);
                    }
                }
            }
        }
    } catch (SchedulerException se) {
        LOG.warn("Exception thrown during job scheduling of Carry over for Leave", se);
        //           throw new JobExecutionException("Exception thrown during job scheduling of Carry over for Leave", se);
    }
}