Example usage for org.joda.time DateTime getHourOfDay

List of usage examples for org.joda.time DateTime getHourOfDay

Introduction

In this page you can find the example usage for org.joda.time DateTime getHourOfDay.

Prototype

public int getHourOfDay() 

Source Link

Document

Get the hour of day field value.

Usage

From source file:org.kitesdk.apps.examples.report.ScheduledReportJob.java

License:Apache License

public void run() {

    // TODO: Switch to parameterized views.
    View<ExampleEvent> view = Datasets.load(ScheduledReportApp.EXAMPLE_DS_URI, ExampleEvent.class);

    RefinableView<GenericRecord> target = Datasets.load(ScheduledReportApp.REPORT_DS_URI, GenericRecord.class);

    // Get the view into which this report will be written.
    DateTime dateTime = getNominalTime().toDateTime(DateTimeZone.UTC);

    View<GenericRecord> output = target.with("year", dateTime.getYear())
            .with("month", dateTime.getMonthOfYear()).with("day", dateTime.getDayOfMonth())
            .with("hour", dateTime.getHourOfDay()).with("minute", dateTime.getMinuteOfHour());

    Pipeline pipeline = getPipeline();/*  w  w  w  .  j a v a  2 s . co m*/

    PCollection<ExampleEvent> events = pipeline.read(CrunchDatasets.asSource(view));

    PTable<Long, ExampleEvent> eventsByUser = events.by(new GetEventId(), Avros.longs());

    // Count of events by user ID.
    PTable<Long, Long> userEventCounts = eventsByUser.keys().count();

    PCollection<GenericData.Record> report = userEventCounts.parallelDo(new ToUserReport(),
            Avros.generics(SCHEMA));

    pipeline.write(report, CrunchDatasets.asTarget(output));

    pipeline.run();
}

From source file:org.kitesdk.apps.spi.oozie.CronConverter.java

License:Apache License

public static Instant nextInstant(String cronSchedule, Instant current) {

    DateTime currentTime = new DateTime(current, DateTimeZone.UTC).withSecondOfMinute(0).withMillisOfSecond(0);

    validate(cronSchedule);// ww w  .  ja va2s .  c o  m

    String[] splits = cronSchedule.split(" ");

    String minutePart = splits[0];
    String hourPart = splits[1];
    String dayPart = splits[2];

    // TODO: fold these together like the hour.
    if (isWildCard(minutePart)) {
        return currentTime.plusMinutes(1).toInstant();
    }

    if (isInterval(minutePart)) {

        // Roll minutes forward until we hit a start time
        // that matches the cron interval.
        int interval = getInterval(minutePart);

        DateTime next = currentTime.withSecondOfMinute(0).plusMinutes(1);

        while (!(next.getMinuteOfHour() % interval == 0)) {

            next = next.plusMinutes(1);
        }

        return next.toInstant();
    }

    assert (isConstant(minutePart));

    // The minute part must be a constant, so
    // simply get the value.
    int minute = Integer.parseInt(minutePart);

    // The schedule is based on hours.
    if (!isConstant(hourPart)) {

        int hourModulus = isWildCard(hourPart) ? 1 : getInterval(hourPart);

        DateTime next = currentTime.withMinuteOfHour(minute);

        while (next.isBefore(current) || !(next.getHourOfDay() % hourModulus == 0)) {

            next = next.plusHours(1);
        }

        return next.toInstant();
    }

    int hour = Integer.parseInt(hourPart);

    // The schedule is based on days, and therfore the day cannot
    // be a constant. This is is checked in validation as well.
    assert (!isConstant(dayPart));

    DateTime next = currentTime.withMinuteOfHour(minute).withHourOfDay(hour);

    while (next.isBefore(current)) {

        next = next.plusDays(1);
    }

    return next.toInstant();
}

From source file:org.kuali.kpme.core.assignment.service.AssignmentServiceImpl.java

License:Educational Community License

public List<Assignment> getAssignmentsByPayEntry(String principalId, CalendarEntry payCalendarEntry) {
    DateTime entryEndDate = payCalendarEntry.getEndPeriodLocalDateTime().toDateTime();
    if (entryEndDate.getHourOfDay() == 0) {
        entryEndDate = entryEndDate.minusDays(1);
    }/*from  www . ja  v a2s  .  c o  m*/
    List<Assignment> beginPeriodAssign = getAssignments(principalId,
            payCalendarEntry.getBeginPeriodFullDateTime().toLocalDate());
    List<Assignment> endPeriodAssign = getAssignments(principalId, entryEndDate.toLocalDate());
    List<Assignment> assignsWithPeriod = getAssignments(principalId,
            payCalendarEntry.getBeginPeriodFullDateTime().toLocalDate(), entryEndDate.toLocalDate());

    List<Assignment> finalAssignments = new ArrayList<Assignment>();
    Map<String, Assignment> assignKeyToAssignmentMap = new HashMap<String, Assignment>();
    for (Assignment assign : endPeriodAssign) {
        assignKeyToAssignmentMap.put(
                TKUtils.formatAssignmentKey(assign.getJobNumber(), assign.getWorkArea(), assign.getTask()),
                assign);
        finalAssignments.add(assign);
    }

    //Compare the begin and end and add any assignments to the end thats are not there
    for (Assignment assign : beginPeriodAssign) {
        String assignKey = TKUtils.formatAssignmentKey(assign.getJobNumber(), assign.getWorkArea(),
                assign.getTask());
        if (!assignKeyToAssignmentMap.containsKey(assignKey)) {
            finalAssignments.add(assign);
        }
    }

    // Add the assignments within the pay period
    for (Assignment assign : assignsWithPeriod) {
        String assignKey = TKUtils.formatAssignmentKey(assign.getJobNumber(), assign.getWorkArea(),
                assign.getTask());
        if (!assignKeyToAssignmentMap.containsKey(assignKey)) {
            finalAssignments.add(assign);
        }
    }

    return finalAssignments;

}

From source file:org.kuali.kpme.core.util.TKUtils.java

License:Educational Community License

public static boolean isVirtualWorkDay(DateTime beginPeriodDateTime) {
    return (beginPeriodDateTime.getHourOfDay() != 0 || beginPeriodDateTime.getMinuteOfHour() != 0
            && beginPeriodDateTime.get(DateTimeFieldType.halfdayOfDay()) != DateTimeConstants.AM);
}

From source file:org.kuali.kpme.core.util.TKUtils.java

License:Educational Community License

public static List<Interval> getFullWeekDaySpanForCalendarEntry(CalendarEntry calendarEntry,
        DateTimeZone timeZone) {//from  w  w w  .  ja  v  a2s  . co  m
    DateTime beginDateTime = calendarEntry.getBeginPeriodLocalDateTime().toDateTime(timeZone);
    DateTime endDateTime = calendarEntry.getEndPeriodLocalDateTime().toDateTime(timeZone);

    List<Interval> dayIntervals = new ArrayList<Interval>();

    DateTime currDateTime = beginDateTime;
    if (beginDateTime.getDayOfWeek() != 7) {
        currDateTime = beginDateTime.plusDays(0 - beginDateTime.getDayOfWeek());
    }

    int afterEndDate = 6 - endDateTime.getDayOfWeek();
    if (endDateTime.getDayOfWeek() == 7 && endDateTime.getHourOfDay() != 0) {
        afterEndDate = 6;
    }
    if (endDateTime.getHourOfDay() == 0) {
        afterEndDate += 1;
    }
    DateTime aDate = endDateTime.plusDays(afterEndDate);
    while (currDateTime.isBefore(aDate)) {
        DateTime prevDateTime = currDateTime;
        currDateTime = currDateTime.plusDays(1);
        Interval daySpan = new Interval(prevDateTime, currDateTime);
        dayIntervals.add(daySpan);
    }

    return dayIntervals;
}

From source file:org.kuali.kpme.tklm.leave.calendar.web.LeaveCalendarAction.java

License:Educational Community License

protected void setLeaveSummary(LeaveCalendarForm leaveCalendarForm) throws Exception {
    String principalId = HrContext.getTargetPrincipalId();
    CalendarEntry calendarEntry = leaveCalendarForm.getCalendarEntry();
    PrincipalHRAttributes principalHRAttributes = HrServiceLocator.getPrincipalHRAttributeService()
            .getPrincipalCalendar(principalId, calendarEntry.getEndPeriodFullDateTime().toLocalDate());

    //check to see if we are on a previous leave plan
    if (principalHRAttributes != null) {
        DateTime currentYearBeginDate = HrServiceLocator.getLeavePlanService()
                .getFirstDayOfLeavePlan(principalHRAttributes.getLeavePlan(), LocalDate.now());
        DateTime calEntryEndDate = calendarEntry.getEndPeriodFullDateTime();
        if (calEntryEndDate.getMillis() > currentYearBeginDate.getMillis()) {
            //current or future year
            LeaveSummary ls = LmServiceLocator.getLeaveSummaryService().getLeaveSummary(principalId,
                    calendarEntry);/*  w w  w .  j av  a2  s. c  o  m*/
            leaveCalendarForm.setLeaveSummary(ls);
        } else {
            //current year roll over date has been passed, all previous calendars belong to the previous leave plan calendar year.
            DateTime effDate = HrServiceLocator.getLeavePlanService().getRolloverDayOfLeavePlan(
                    principalHRAttributes.getLeavePlan(), calEntryEndDate.minusDays(1).toLocalDate());
            LeaveSummary ls = LmServiceLocator.getLeaveSummaryService()
                    .getLeaveSummaryAsOfDateWithoutFuture(principalId, effDate.toLocalDate());
            //override title element (based on date passed in)
            DateFormat formatter = new SimpleDateFormat("MMMM d");
            DateFormat formatter2 = new SimpleDateFormat("MMMM d yyyy");
            DateTime entryEndDate = new LocalDateTime(calendarEntry.getEndPeriodDate()).toDateTime();
            if (entryEndDate.getHourOfDay() == 0) {
                entryEndDate = entryEndDate.minusDays(1);
            }
            String aString = formatter.format(calendarEntry.getBeginPeriodDate()) + " - "
                    + formatter2.format(entryEndDate.toDate());
            ls.setPendingDatesString(aString);
            DateTimeFormatter fmt = DateTimeFormat.forPattern("MMM d, yyyy");
            ls.setNote("Values as of: " + fmt.print(effDate));
            leaveCalendarForm.setLeaveSummary(ls);
        }
    }
}

From source file:org.kuali.kpme.tklm.leave.summary.service.LeaveSummaryServiceImpl.java

License:Educational Community License

protected LeaveSummary getLeaveSummary(String principalId, LocalDate startDate, LocalDate endDate,
        String accrualCategory, boolean includeFuture) {
    LeaveSummary ls = new LeaveSummary();
    List<LeaveSummaryRow> rows = new ArrayList<LeaveSummaryRow>();

    if (StringUtils.isEmpty(principalId) || startDate == null || endDate == null) {
        return ls;
    }//from   w ww  .ja va  2  s.c o m

    Set<String> leavePlans = getLeavePlans(principalId, startDate, endDate);
    PrincipalHRAttributes pha = getPrincipalHrAttributes(principalId, startDate, endDate);
    if (CollectionUtils.isNotEmpty(leavePlans)) {
        for (String aLpString : leavePlans) {
            LeavePlan lp = HrServiceLocator.getLeavePlanService().getLeavePlan(aLpString, startDate);
            if (lp == null) {
                continue;
            }
            DateTimeFormatter formatter = DateTimeFormat.forPattern("MMMM d");
            DateTimeFormatter formatter2 = DateTimeFormat.forPattern("MMMM d yyyy");
            DateTime entryEndDate = endDate.toDateTimeAtStartOfDay();
            if (entryEndDate.getHourOfDay() == 0) {
                entryEndDate = entryEndDate.minusDays(1);
            }
            String aString = formatter.print(startDate) + " - " + formatter2.print(entryEndDate);
            ls.setPendingDatesString(aString);

            LeaveCalendarDocumentHeader approvedLcdh = LmServiceLocator.getLeaveCalendarDocumentHeaderService()
                    .getMaxEndDateApprovedLeaveCalendar(principalId);
            if (approvedLcdh != null) {
                DateTime endApprovedDate = approvedLcdh.getEndDateTime();
                LocalDateTime aLocalTime = approvedLcdh.getEndDateTime().toLocalDateTime();
                DateTime endApprovedTime = aLocalTime
                        .toDateTime(HrServiceLocator.getTimezoneService().getUserTimezoneWithFallback());
                if (endApprovedTime.getHourOfDay() == 0) {
                    endApprovedDate = endApprovedDate.minusDays(1);
                }
                String datesString = formatter.print(approvedLcdh.getBeginDateTime()) + " - "
                        + formatter2.print(endApprovedDate);
                ls.setYtdDatesString(datesString);
            }

            //until we have something that creates carry over, we need to grab everything.
            // Calculating leave bLocks from Calendar Year start instead of Service Date
            Map<String, LeaveBlock> carryOverBlocks = getLeaveBlockService().getLastCarryOverBlocks(principalId,
                    startDate);

            boolean filterByAccrualCategory = false;
            if (StringUtils.isNotEmpty(accrualCategory)) {
                filterByAccrualCategory = true;
                //remove unwanted carry over blocks from map
                LeaveBlock carryOverBlock = carryOverBlocks.get(accrualCategory);
                carryOverBlocks = new HashMap<String, LeaveBlock>(1);
                if (ObjectUtils.isNotNull(carryOverBlock))
                    carryOverBlocks.put(carryOverBlock.getAccrualCategory(), carryOverBlock);
            }
            List<LeaveBlock> leaveBlocks = getLeaveBlockService().getLeaveBlocksSinceCarryOver(principalId,
                    carryOverBlocks, endDate, filterByAccrualCategory);

            List<LeaveBlock> futureLeaveBlocks = new ArrayList<LeaveBlock>();
            if (includeFuture) {
                if (!filterByAccrualCategory) {
                    futureLeaveBlocks = getLeaveBlockService().getLeaveBlocks(principalId, endDate,
                            endDate.plusMonths(Integer.parseInt(lp.getPlanningMonths())));
                } else {
                    futureLeaveBlocks = getLeaveBlockService().getLeaveBlocksWithAccrualCategory(principalId,
                            endDate, endDate.plusMonths(Integer.parseInt(lp.getPlanningMonths())),
                            accrualCategory);
                }
            }
            Map<String, List<LeaveBlock>> leaveBlockMap = mapLeaveBlocksByAccrualCategory(leaveBlocks);
            Map<String, List<LeaveBlock>> futureLeaveBlockMap = mapLeaveBlocksByAccrualCategory(
                    futureLeaveBlocks);
            List<AccrualCategory> acList = HrServiceLocator.getAccrualCategoryService()
                    .getActiveAccrualCategoriesForLeavePlan(lp.getLeavePlan(), endDate);
            if (CollectionUtils.isNotEmpty(acList)) {
                for (AccrualCategory ac : acList) {
                    if (ac.getShowOnGrid().equals("Y")) {

                        LeaveSummaryRow lsr = new LeaveSummaryRow();
                        lsr.setAccrualCategory(ac.getAccrualCategory());
                        lsr.setAccrualCategoryId(ac.getLmAccrualCategoryId());
                        //get max balances
                        AccrualCategoryRule acRule = HrServiceLocator.getAccrualCategoryRuleService()
                                .getAccrualCategoryRuleForDate(ac, endDate, pha.getServiceLocalDate());
                        //accrual category rule id set on a leave summary row will be useful in generating a relevant balance transfer
                        //document from the leave calendar display. Could put this id in the request for balance transfer document.
                        EmployeeOverride maxUsageOverride = LmServiceLocator.getEmployeeOverrideService()
                                .getEmployeeOverride(principalId, lp.getLeavePlan(), ac.getAccrualCategory(),
                                        "MU", endDate);

                        lsr.setAccrualCategoryRuleId(
                                acRule == null ? null : acRule.getLmAccrualCategoryRuleId());
                        if (acRule != null
                                && (acRule.getMaxBalance() != null || acRule.getMaxUsage() != null)) {
                            if (acRule.getMaxUsage() != null) {
                                lsr.setUsageLimit(new BigDecimal(acRule.getMaxUsage()).setScale(2));
                            } else {
                                lsr.setUsageLimit(null);
                            }

                        } else {
                            lsr.setUsageLimit(null);
                        }

                        if (maxUsageOverride != null)
                            lsr.setUsageLimit(new BigDecimal(maxUsageOverride.getOverrideValue()));

                        //Fetching leaveblocks for accCat with type CarryOver -- This is logic according to the CO blocks created from scheduler job.
                        BigDecimal carryOver = BigDecimal.ZERO.setScale(2);
                        lsr.setCarryOver(carryOver);

                        //handle up to current leave blocks
                        //CalendarEntry.getEndPeriodDate passed to fetch leave block amounts on last day of Calendar period
                        assignApprovedValuesToRow(lsr, ac.getAccrualCategory(),
                                leaveBlockMap.get(ac.getAccrualCategory()), lp, startDate, endDate);

                        //how about the leave blocks on the calendar entry being currently handled??
                        /*                            if(carryOverBlocks.containsKey(lsr.getAccrualCategory())) {
                                                       LeaveBlock carryOverBlock = carryOverBlocks.get(lsr.getAccrualCategory());
                                                       DateTime carryOverBlockLPStart = HrServiceLocator.getLeavePlanService().getFirstDayOfLeavePlan(lp.getLeavePlan(), carryOverBlock.getLeaveDate());
                                                       DateTime currentLPStart = HrServiceLocator.getLeavePlanService().getFirstDayOfLeavePlan(lp.getLeavePlan(), TKUtils.getCurrentDate());
                                                       if(carryOverBlockLPStart.equals(currentLPStart))
                          carryOver = carryOverBlock.getLeaveAmount();
                                                    }*/
                        //figure out past carry over values!!!
                        //We now have list of past years accrual and use (with ordered keys!!!)

                        //merge key sets
                        if (carryOverBlocks.containsKey(lsr.getAccrualCategory())) {
                            carryOver = carryOverBlocks.get(lsr.getAccrualCategory()).getLeaveAmount();
                            carryOver = carryOver.setScale(2);
                        }
                        Set<String> keyset = new HashSet<String>();
                        keyset.addAll(lsr.getPriorYearsUsage().keySet());
                        keyset.addAll(lsr.getPriorYearsTotalAccrued().keySet());
                        for (String key : keyset) {
                            BigDecimal value = lsr.getPriorYearsTotalAccrued().get(key);
                            if (value == null) {
                                value = BigDecimal.ZERO;
                            }
                            carryOver = carryOver.add(value);
                            BigDecimal use = lsr.getPriorYearsUsage().containsKey(key)
                                    ? lsr.getPriorYearsUsage().get(key)
                                    : BigDecimal.ZERO;
                            carryOver = carryOver.add(use);
                            EmployeeOverride carryOverOverride = LmServiceLocator.getEmployeeOverrideService()
                                    .getEmployeeOverride(principalId, lp.getLeavePlan(),
                                            ac.getAccrualCategory(), "MAC", endDate);
                            if (acRule != null && acRule.getMaxCarryOver() != null) {
                                BigDecimal carryOverDisplay = BigDecimal.ZERO;
                                if (carryOverOverride != null)
                                    carryOverDisplay = new BigDecimal(
                                            carryOverOverride.getOverrideValue() < carryOver.longValue()
                                                    ? carryOverOverride.getOverrideValue()
                                                    : carryOver.longValue());
                                else
                                    carryOverDisplay = new BigDecimal(
                                            acRule.getMaxCarryOver() < carryOver.longValue()
                                                    ? acRule.getMaxCarryOver()
                                                    : carryOver.longValue());
                                carryOver = carryOverDisplay;
                            }
                        }

                        lsr.setCarryOver(carryOver);
                        if (acRule != null && acRule.getMaxCarryOver() != null) {
                            EmployeeOverride carryOverOverride = LmServiceLocator.getEmployeeOverrideService()
                                    .getEmployeeOverride(principalId, lp.getLeavePlan(),
                                            ac.getAccrualCategory(), "MAC", endDate);
                            if (carryOverOverride != null)
                                lsr.setMaxCarryOver(new BigDecimal(carryOverOverride.getOverrideValue()));
                            else
                                lsr.setMaxCarryOver(
                                        new BigDecimal(acRule.getMaxCarryOver() < carryOver.longValue()
                                                ? acRule.getMaxCarryOver()
                                                : carryOver.longValue()));
                        }

                        //handle future leave blocks
                        assignPendingValuesToRow(lsr, ac.getAccrualCategory(),
                                futureLeaveBlockMap.get(ac.getAccrualCategory()));

                        //compute Leave Balance
                        BigDecimal leaveBalance = lsr.getAccruedBalance()
                                .subtract(lsr.getPendingLeaveRequests());
                        //if leave balance is set
                        //Employee overrides have already been taken into consideration and the appropriate values
                        //for usage have been set by this point.
                        //                            if (acRule != null && StringUtils.equals(acRule.getMaxBalFlag(), "Y")) {
                        //there exists an accrual category rule with max balance limit imposed.
                        //max bal flag = 'Y' has no precedence here with max-bal / balance transfers implemented.
                        //unless institutions are not required to define a max balance limit for action_at_max_bal = LOSE.
                        //Possibly preferable to procure forfeiture blocks through balance transfer
                        if (lsr.getUsageLimit() != null) { //should not set leave balance to usage limit simply because it's not null.
                            BigDecimal availableUsage = lsr.getUsageLimit()
                                    .subtract(lsr.getYtdApprovedUsage().add(lsr.getPendingLeaveRequests()));
                            if (leaveBalance.compareTo(availableUsage) > 0)
                                lsr.setLeaveBalance(availableUsage);
                            else
                                lsr.setLeaveBalance(leaveBalance);
                        } else { //no usage limit
                            lsr.setLeaveBalance(leaveBalance);
                        }

                        rows.add(lsr);
                    }
                }
                // let's check for 'empty' accrual categories
                if (leaveBlockMap.containsKey(null) || futureLeaveBlockMap.containsKey(null)) {
                    LeaveSummaryRow otherLeaveSummary = new LeaveSummaryRow();
                    //otherLeaveSummary.setAccrualCategory("Other");

                    assignApprovedValuesToRow(otherLeaveSummary, null, leaveBlockMap.get(null), lp, startDate,
                            endDate);
                    BigDecimal carryOver = BigDecimal.ZERO.setScale(2);
                    for (Map.Entry<String, BigDecimal> entry : otherLeaveSummary.getPriorYearsTotalAccrued()
                            .entrySet()) {
                        carryOver = carryOver.add(entry.getValue());
                        BigDecimal use = otherLeaveSummary.getPriorYearsUsage().containsKey(entry.getKey())
                                ? otherLeaveSummary.getPriorYearsUsage().get(entry.getKey())
                                : BigDecimal.ZERO;
                        carryOver = carryOver.add(use);
                    }
                    otherLeaveSummary.setCarryOver(carryOver);
                    assignPendingValuesToRow(otherLeaveSummary, null, futureLeaveBlockMap.get(null));
                    otherLeaveSummary.setAccrualCategory("Other");

                    //compute Leave Balance
                    // blank the avail
                    otherLeaveSummary.setUsageLimit(null);
                    otherLeaveSummary.setLeaveBalance(null);

                    rows.add(otherLeaveSummary);
                }
            }
        }
    }
    ls.setLeaveSummaryRows(rows);
    return ls;
}

From source file:org.kuali.kpme.tklm.time.detail.validation.TimeDetailValidationUtil.java

License:Educational Community License

public static List<String> validateTimeEntryDetails(BigDecimal hours, BigDecimal amount, String startTimeS,
        String endTimeS, String startDateS, String endDateS, TimesheetDocument timesheetDocument,
        String selectedEarnCode, String selectedAssignment, boolean acrossDays, String timeblockId,
        String overtimePref, boolean spanningWeeks) {
    List<String> errors = new ArrayList<String>();

    if (timesheetDocument == null) {
        errors.add("No timesheet document found.");
    }//from w  w  w.  j  a  v  a 2 s. c  o  m
    if (errors.size() > 0)
        return errors;

    CalendarEntry payCalEntry = timesheetDocument.getCalendarEntry();

    errors.addAll(TimeDetailValidationUtil.validateDates(startDateS, endDateS));
    errors.addAll(TimeDetailValidationUtil.validateTimes(startTimeS, endTimeS));
    if (errors.size() > 0)
        return errors;

    Long startTime;
    Long endTime;

    startTime = TKUtils.convertDateStringToDateTimeWithoutZone(startDateS, startTimeS).getMillis();
    endTime = TKUtils.convertDateStringToDateTimeWithoutZone(endDateS, endTimeS).getMillis();

    errors.addAll(validateInterval(payCalEntry, startTime, endTime));
    if (errors.size() > 0)
        return errors;

    EarnCode earnCode = new EarnCode();
    if (StringUtils.isNotBlank(selectedEarnCode)) {
        earnCode = HrServiceLocator.getEarnCodeService().getEarnCode(selectedEarnCode,
                payCalEntry.getEndPeriodFullDateTime().toLocalDate());

        if (earnCode != null && earnCode.getRecordMethod() != null
                && earnCode.getRecordMethod().equalsIgnoreCase(HrConstants.EARN_CODE_TIME)) {
            if (startTimeS == null)
                errors.add("The start time is blank.");
            if (endTimeS == null)
                errors.add("The end time is blank.");
            if (startTime - endTime == 0)
                errors.add("Start time and end time cannot be equivalent");
        }
    }
    if (errors.size() > 0)
        return errors;

    DateTime startTemp = new DateTime(startTime);
    DateTime endTemp = new DateTime(endTime);

    if (errors.size() == 0 && !acrossDays && !StringUtils.equals(TkConstants.EARN_CODE_CPE, overtimePref)) {
        Hours hrs = Hours.hoursBetween(startTemp, endTemp);
        if (hrs.getHours() >= 24)
            errors.add("One timeblock cannot exceed 24 hours");
    }
    if (errors.size() > 0)
        return errors;

    //Check that assignment is valid for both days
    AssignmentDescriptionKey assignKey = HrServiceLocator.getAssignmentService()
            .getAssignmentDescriptionKey(selectedAssignment);
    Assignment assign = HrServiceLocator.getAssignmentService().getAssignment(assignKey,
            startTemp.toLocalDate());
    if (assign == null)
        errors.add("Assignment is not valid for start date " + TKUtils.formatDate(new LocalDate(startTime)));
    assign = HrServiceLocator.getAssignmentService().getAssignment(assignKey, endTemp.toLocalDate());
    if (assign == null)
        errors.add("Assignment is not valid for end date " + TKUtils.formatDate(new LocalDate(endTime)));
    if (errors.size() > 0)
        return errors;

    //------------------------
    // some of the simple validations are in the js side in order to reduce the server calls
    // 1. check if the begin / end time is empty - tk.calenadr.js
    // 2. check the time format - timeparse.js
    // 3. only allows decimals to be entered in the hour field
    //------------------------

    //------------------------
    // check if the begin / end time are valid
    //------------------------
    if ((startTime.compareTo(endTime) > 0 || endTime.compareTo(startTime) < 0)) {
        errors.add("The time or date is not valid.");
    }
    if (errors.size() > 0)
        return errors;

    // KPME-1446 
    // -------------------------------
    // check if there is a weekend day when the include weekends flag is checked
    //--------------------------------
    errors.addAll(validateSpanningWeeks(spanningWeeks, startTemp, endTemp));
    if (errors.size() > 0)
        return errors;

    //------------------------
    // check if the overnight shift is across days
    //------------------------
    if (acrossDays && hours == null && amount == null) {
        if (startTemp.getHourOfDay() > endTemp.getHourOfDay()
                && !(endTemp.getDayOfYear() - startTemp.getDayOfYear() <= 1 && endTemp.getHourOfDay() == 0)) {
            errors.add("The \"apply to each day\" box should not be checked.");
        }
    }
    if (errors.size() > 0)
        return errors;

    //------------------------
    // Amount cannot be zero
    //------------------------
    if (amount != null && earnCode != null
            && StringUtils.equals(earnCode.getEarnCodeType(), HrConstants.EARN_CODE_AMOUNT)) {
        if (amount.equals(BigDecimal.ZERO)) {
            errors.add("Amount cannot be zero.");
        }
        if (amount.scale() > 2) {
            errors.add("Amount cannot have more than two digits after decimal point.");
        }
    }
    if (errors.size() > 0)
        return errors;

    //------------------------
    // check if the hours entered for hourly earn code is greater than 24 hours per day
    // Hours cannot be zero
    //------------------------
    if (hours != null && earnCode != null
            && StringUtils.equals(earnCode.getEarnCodeType(), HrConstants.EARN_CODE_HOUR)) {
        if (hours.equals(BigDecimal.ZERO)) {
            errors.add("Hours cannot be zero.");
        }
        if (hours.scale() > 2) {
            errors.add("Hours cannot have more than two digits after decimal point.");
        }
        int dayDiff = endTemp.getDayOfYear() - startTemp.getDayOfYear() + 1;
        if (hours.compareTo(new BigDecimal(dayDiff * 24)) == 1) {
            errors.add("Cannot enter more than 24 hours per day.");
        }
    }
    if (errors.size() > 0)
        return errors;

    //------------------------
    // check if time blocks overlap with each other. Note that the tkTimeBlockId is used to
    // determine is it's updating an existing time block or adding a new one
    //------------------------

    boolean isRegularEarnCode = StringUtils.equals(assign.getJob().getPayTypeObj().getRegEarnCode(),
            selectedEarnCode);
    errors.addAll(validateOverlap(startTime, endTime, acrossDays, startDateS, endTimeS, startTemp, endTemp,
            timesheetDocument, timeblockId, isRegularEarnCode));
    if (errors.size() > 0)
        return errors;

    // Accrual Hour Limits Validation
    //errors.addAll(TkServiceLocator.getTimeOffAccrualService().validateAccrualHoursLimitByEarnCode(timesheetDocument, selectedEarnCode));

    return errors;
}

From source file:org.kuali.kpme.tklm.time.detail.web.TimeDetailAction.java

License:Educational Community License

private void changeTimeBlocks(TimeDetailActionForm tdaf) {
    DateTime overtimeBeginDateTime = null;
    DateTime overtimeEndDateTime = null;
    boolean isClockLogCreated = false;

    // This is for updating a timeblock or changing
    // If tkTimeBlockId is not null and the new timeblock is valid, delete the existing timeblock and a new one will be created after submitting the form.
    if (tdaf.getTkTimeBlockId() != null) {
        TimeBlock tb = TkServiceLocator.getTimeBlockService().getTimeBlock(tdaf.getTkTimeBlockId());
        if (tb != null) {
            isClockLogCreated = tb.getClockLogCreated();
            if (StringUtils.isNotEmpty(tdaf.getOvertimePref())) {
                //TODO:  This doesn't do anything!!! these variables are never used.  Should they be?
                overtimeBeginDateTime = tb.getBeginDateTime();
                overtimeEndDateTime = tb.getEndDateTime();
            }//from w w w. j  a v  a 2 s .co  m
        }
        // old time block is deleted from addTimeBlock method
        // this.removeOldTimeBlock(tdaf);
    }

    Assignment currentAssignment = tdaf.getTimesheetDocument()
            .getAssignment(AssignmentDescriptionKey.get(tdaf.getSelectedAssignment()));

    // Surgery point - Need to construct a Date/Time with Appropriate Timezone.
    DateTime startTime = TKUtils.convertDateStringToDateTime(tdaf.getStartDate(), tdaf.getStartTime());
    DateTime endTime = TKUtils.convertDateStringToDateTime(tdaf.getEndDate(), tdaf.getEndTime());

    // We need a  cloned reference set so we know whether or not to
    // persist any potential changes without making hundreds of DB calls.
    List<TimeBlock> referenceTimeBlocks = new ArrayList<TimeBlock>(
            tdaf.getTimesheetDocument().getTimeBlocks().size());
    for (TimeBlock tb : tdaf.getTimesheetDocument().getTimeBlocks()) {
        referenceTimeBlocks.add(tb.copy());
    }

    // This is just a reference, for code clarity, the above list is actually
    // separate at the object level.
    List<TimeBlock> newTimeBlocks = tdaf.getTimesheetDocument().getTimeBlocks();
    List<TimeBlock> timeBlocksToAdd = null;
    // KPME-1446 add spanningweeks to the calls below 
    if (StringUtils.equals(tdaf.getAcrossDays(), "y")
            && !(endTime.getDayOfYear() - startTime.getDayOfYear() <= 1 && endTime.getHourOfDay() == 0)) {

        timeBlocksToAdd = TkServiceLocator.getTimeBlockService().buildTimeBlocksSpanDates(currentAssignment,
                tdaf.getSelectedEarnCode(), tdaf.getTimesheetDocument(), startTime, endTime, tdaf.getHours(),
                tdaf.getAmount(), isClockLogCreated, Boolean.parseBoolean(tdaf.getLunchDeleted()),
                tdaf.getSpanningWeeks(), HrContext.getPrincipalId());

    } else {
        timeBlocksToAdd = TkServiceLocator.getTimeBlockService().buildTimeBlocks(currentAssignment,
                tdaf.getSelectedEarnCode(), tdaf.getTimesheetDocument(), startTime, endTime, tdaf.getHours(),
                tdaf.getAmount(), isClockLogCreated, Boolean.parseBoolean(tdaf.getLunchDeleted()),
                HrContext.getPrincipalId());
    }

    TimeBlock existingTimeBlock = null;
    TimeBlock timeBlockToUpdate = null;

    if (tdaf.getTkTimeBlockId() != null) {
        timeBlockToUpdate = timeBlocksToAdd.get(0);
        TkServiceLocator.getTimeHourDetailService().removeTimeHourDetails(tdaf.getTkTimeBlockId());
        timeBlockToUpdate.setTkTimeBlockId(tdaf.getTkTimeBlockId());
    }

    List<TimeBlock> finalNewTimeBlocks = new ArrayList<TimeBlock>();

    for (TimeBlock tb : newTimeBlocks) {
        if (!ObjectUtils.equals(tb.getTkTimeBlockId(), tdaf.getTkTimeBlockId())) {
            finalNewTimeBlocks.add(tb);
        } else {
            existingTimeBlock = tb;
            existingTimeBlock.copy(timeBlockToUpdate);
            finalNewTimeBlocks.add(existingTimeBlock);
        }
    }

    for (TimeBlock tb : timeBlocksToAdd) {
        if (tdaf.getTkTimeBlockId() != null) {
            if (!ObjectUtils.equals(tb.getTkTimeBlockId(), tdaf.getTkTimeBlockId())) {
                finalNewTimeBlocks.add(tb);
            }
        } else {
            finalNewTimeBlocks.add(tb);
        }
    }

    //reset time block
    TkServiceLocator.getTimesheetService().resetTimeBlock(finalNewTimeBlocks,
            tdaf.getTimesheetDocument().getAsOfDate());

    // apply overtime pref
    // I changed start and end times comparison below. it used to be overtimeBeginTimestamp and overtimeEndTimestamp but
    // for some reason, they're always null because, we have removed the time block before getting here. KPME-2162
    if (StringUtils.isNotEmpty(tdaf.getOvertimePref())) {
        for (TimeBlock tb : finalNewTimeBlocks) {
            if ((StringUtils.isNotEmpty(tdaf.getTkTimeBlockId())
                    && tdaf.getTkTimeBlockId().equals(tb.getTkTimeBlockId()))
                    || (tb.getBeginTimestamp().equals(startTime) && tb.getEndTimestamp().equals(endTime))) {
                tb.setOvertimePref(tdaf.getOvertimePref());
            }
        }
    }

    List<Assignment> assignments = tdaf.getTimesheetDocument().getAssignments();
    List<String> assignmentKeys = new ArrayList<String>();
    for (Assignment assignment : assignments) {
        assignmentKeys.add(assignment.getAssignmentKey());
    }

    List<LeaveBlock> leaveBlocks = LmServiceLocator.getLeaveBlockService().getLeaveBlocksForTimeCalendar(
            HrContext.getTargetPrincipalId(), tdaf.getTimesheetDocument().getAsOfDate(),
            tdaf.getTimesheetDocument().getDocEndDate(), assignmentKeys);

    TkServiceLocator.getTkRuleControllerService().applyRules(TkConstants.ACTIONS.ADD_TIME_BLOCK,
            finalNewTimeBlocks, leaveBlocks, tdaf.getCalendarEntry(), tdaf.getTimesheetDocument(),
            HrContext.getPrincipalId());

    TkServiceLocator.getTimeBlockService().saveTimeBlocks(referenceTimeBlocks, finalNewTimeBlocks,
            HrContext.getPrincipalId());

}

From source file:org.kuali.kpme.tklm.time.rules.graceperiod.service.GracePeriodServiceImpl.java

License:Educational Community License

public DateTime processGracePeriodRule(DateTime actualDateTime, LocalDate asOfDate) {
    DateTime gracePeriodDateTime = actualDateTime;

    GracePeriodRule gracePeriodRule = getGracePeriodRule(asOfDate);
    if (gracePeriodRule != null) {
        //go ahead and round off seconds
        gracePeriodDateTime = gracePeriodDateTime.withSecondOfMinute(0);

        BigDecimal minuteIncrement = gracePeriodRule.getHourFactor();
        BigDecimal minutes = new BigDecimal(gracePeriodDateTime.getMinuteOfHour());
        int bottomIntervalFactor = minutes.divide(minuteIncrement, 0, BigDecimal.ROUND_FLOOR).intValue();
        BigDecimal bottomInterval = new BigDecimal(bottomIntervalFactor).multiply(minuteIncrement);
        BigDecimal topInterval = new BigDecimal(bottomIntervalFactor + 1).multiply(minuteIncrement);
        if (bottomInterval.subtract(minutes).abs().intValue() < topInterval.subtract(minutes).abs()
                .intValue()) {//from w  ww . j  a v a 2  s  .  c  o  m
            gracePeriodDateTime = gracePeriodDateTime
                    .withMinuteOfHour(bottomInterval.setScale(0, BigDecimal.ROUND_HALF_UP).intValue());
        } else {
            if (topInterval.equals(new BigDecimal(60))) {
                gracePeriodDateTime = gracePeriodDateTime.withHourOfDay(gracePeriodDateTime.getHourOfDay() + 1)
                        .withMinuteOfHour(0);
            } else {
                gracePeriodDateTime = gracePeriodDateTime
                        .withMinuteOfHour(topInterval.setScale(0, BigDecimal.ROUND_HALF_UP).intValue());
            }
        }
    }
    return gracePeriodDateTime;
}