Example usage for org.joda.time DateTime getDayOfYear

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

Introduction

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

Prototype

public int getDayOfYear() 

Source Link

Document

Get the day of year field value.

Usage

From source file:org.jruby.truffle.core.time.RubyDateFormatter.java

License:LGPL

public ByteList formatToByteList(List<Token> compiledPattern, DateTime dt, long nsec) {
    RubyTimeOutputFormatter formatter = RubyTimeOutputFormatter.DEFAULT_FORMATTER;
    ByteList toAppendTo = new ByteList();

    for (Token token : compiledPattern) {
        String output = null;//  w  ww . j  a v a  2  s .c om
        long value = 0;
        FieldType type = TEXT;
        Format format = token.getFormat();

        switch (format) {
        case FORMAT_ENCODING:
            toAppendTo.setEncoding((Encoding) token.getData());
            continue; // go to next token
        case FORMAT_OUTPUT:
            formatter = (RubyTimeOutputFormatter) token.getData();
            continue; // go to next token
        case FORMAT_STRING:
            output = token.getData().toString();
            break;
        case FORMAT_WEEK_LONG:
            // This is GROSS, but Java API's aren't ISO 8601 compliant at all
            int v = (dt.getDayOfWeek() + 1) % 8;
            if (v == 0) {
                v++;
            }
            output = FORMAT_SYMBOLS.getWeekdays()[v];
            break;
        case FORMAT_WEEK_SHORT:
            // This is GROSS, but Java API's aren't ISO 8601 compliant at all
            v = (dt.getDayOfWeek() + 1) % 8;
            if (v == 0) {
                v++;
            }
            output = FORMAT_SYMBOLS.getShortWeekdays()[v];
            break;
        case FORMAT_MONTH_LONG:
            output = FORMAT_SYMBOLS.getMonths()[dt.getMonthOfYear() - 1];
            break;
        case FORMAT_MONTH_SHORT:
            output = FORMAT_SYMBOLS.getShortMonths()[dt.getMonthOfYear() - 1];
            break;
        case FORMAT_DAY:
            type = NUMERIC2;
            value = dt.getDayOfMonth();
            break;
        case FORMAT_DAY_S:
            type = NUMERIC2BLANK;
            value = dt.getDayOfMonth();
            break;
        case FORMAT_HOUR:
            type = NUMERIC2;
            value = dt.getHourOfDay();
            break;
        case FORMAT_HOUR_BLANK:
            type = NUMERIC2BLANK;
            value = dt.getHourOfDay();
            break;
        case FORMAT_HOUR_M:
        case FORMAT_HOUR_S:
            value = dt.getHourOfDay();
            if (value == 0) {
                value = 12;
            } else if (value > 12) {
                value -= 12;
            }

            type = (format == Format.FORMAT_HOUR_M) ? NUMERIC2 : NUMERIC2BLANK;
            break;
        case FORMAT_DAY_YEAR:
            type = NUMERIC3;
            value = dt.getDayOfYear();
            break;
        case FORMAT_MINUTES:
            type = NUMERIC2;
            value = dt.getMinuteOfHour();
            break;
        case FORMAT_MONTH:
            type = NUMERIC2;
            value = dt.getMonthOfYear();
            break;
        case FORMAT_MERIDIAN:
            output = dt.getHourOfDay() < 12 ? "AM" : "PM";
            break;
        case FORMAT_MERIDIAN_LOWER_CASE:
            output = dt.getHourOfDay() < 12 ? "am" : "pm";
            break;
        case FORMAT_SECONDS:
            type = NUMERIC2;
            value = dt.getSecondOfMinute();
            break;
        case FORMAT_WEEK_YEAR_M:
            type = NUMERIC2;
            value = formatWeekYear(dt, Calendar.MONDAY);
            break;
        case FORMAT_WEEK_YEAR_S:
            type = NUMERIC2;
            value = formatWeekYear(dt, Calendar.SUNDAY);
            break;
        case FORMAT_DAY_WEEK:
            type = NUMERIC;
            value = dt.getDayOfWeek() % 7;
            break;
        case FORMAT_DAY_WEEK2:
            type = NUMERIC;
            value = dt.getDayOfWeek();
            break;
        case FORMAT_YEAR_LONG:
            value = year(dt, dt.getYear());
            type = (value >= 0) ? NUMERIC4 : NUMERIC5;
            break;
        case FORMAT_YEAR_SHORT:
            type = NUMERIC2;
            value = year(dt, dt.getYear()) % 100;
            break;
        case FORMAT_COLON_ZONE_OFF:
            // custom logic because this is so weird
            value = dt.getZone().getOffset(dt.getMillis()) / 1000;
            int colons = (Integer) token.getData();
            output = formatZone(colons, (int) value, formatter);
            break;
        case FORMAT_ZONE_ID:
            output = getRubyTimeZoneName(dt);
            break;
        case FORMAT_CENTURY:
            type = NUMERIC;
            value = year(dt, dt.getYear()) / 100;
            break;
        case FORMAT_EPOCH:
            type = NUMERIC;
            value = dt.getMillis() / 1000;
            break;
        case FORMAT_WEEK_WEEKYEAR:
            type = NUMERIC2;
            value = dt.getWeekOfWeekyear();
            break;
        case FORMAT_MILLISEC:
        case FORMAT_NANOSEC:
            int defaultWidth = (format == Format.FORMAT_NANOSEC) ? 9 : 3;
            int width = formatter.getWidth(defaultWidth);

            output = RubyTimeOutputFormatter.formatNumber(dt.getMillisOfSecond(), 3, '0');
            if (width > 3) {
                output += RubyTimeOutputFormatter.formatNumber(nsec, 6, '0');
            }

            if (width < output.length()) {
                output = output.substring(0, width);
            } else {
                // Not enough precision, fill with 0
                while (output.length() < width)
                    output += "0";
            }
            formatter = RubyTimeOutputFormatter.DEFAULT_FORMATTER; // no more formatting
            break;
        case FORMAT_WEEKYEAR:
            value = year(dt, dt.getWeekyear());
            type = (value >= 0) ? NUMERIC4 : NUMERIC5;
            break;
        case FORMAT_WEEKYEAR_SHORT:
            type = NUMERIC2;
            value = year(dt, dt.getWeekyear()) % 100;
            break;
        case FORMAT_MICROSEC_EPOCH:
            // only available for Date
            type = NUMERIC;
            value = dt.getMillis();
            break;
        case FORMAT_SPECIAL:
            throw new Error("FORMAT_SPECIAL is a special token only for the lexer.");
        }

        try {
            output = formatter.format(output, value, type);
        } catch (IndexOutOfBoundsException ioobe) {
            throw new RaiseException(
                    context.getCoreExceptions().errnoError(Errno.ERANGE.intValue(), "strftime", currentNode));
        }

        // reset formatter
        formatter = RubyTimeOutputFormatter.DEFAULT_FORMATTER;

        toAppendTo.append(
                output.getBytes(context.getEncodingManager().charsetForEncoding(toAppendTo.getEncoding())));
    }

    return toAppendTo;
}

From source file:org.jruby.util.RubyDateFormatter.java

License:LGPL

public ByteList formatToByteList(List<Token> compiledPattern, DateTime dt, long nsec, IRubyObject sub_millis) {
    RubyTimeOutputFormatter formatter = RubyTimeOutputFormatter.DEFAULT_FORMATTER;
    ByteList toAppendTo = new ByteList();

    for (Token token : compiledPattern) {
        String output = null;//from   w  ww. jav a2s  . c om
        long value = 0;
        FieldType type = TEXT;
        Format format = token.getFormat();

        switch (format) {
        case FORMAT_ENCODING:
            toAppendTo.setEncoding((Encoding) token.getData());
            continue; // go to next token
        case FORMAT_OUTPUT:
            formatter = (RubyTimeOutputFormatter) token.getData();
            continue; // go to next token
        case FORMAT_STRING:
            output = token.getData().toString();
            break;
        case FORMAT_WEEK_LONG:
            // This is GROSS, but Java API's aren't ISO 8601 compliant at all
            int v = (dt.getDayOfWeek() + 1) % 8;
            if (v == 0) {
                v++;
            }
            output = FORMAT_SYMBOLS.getWeekdays()[v];
            break;
        case FORMAT_WEEK_SHORT:
            // This is GROSS, but Java API's aren't ISO 8601 compliant at all
            v = (dt.getDayOfWeek() + 1) % 8;
            if (v == 0) {
                v++;
            }
            output = FORMAT_SYMBOLS.getShortWeekdays()[v];
            break;
        case FORMAT_MONTH_LONG:
            output = FORMAT_SYMBOLS.getMonths()[dt.getMonthOfYear() - 1];
            break;
        case FORMAT_MONTH_SHORT:
            output = FORMAT_SYMBOLS.getShortMonths()[dt.getMonthOfYear() - 1];
            break;
        case FORMAT_DAY:
            type = NUMERIC2;
            value = dt.getDayOfMonth();
            break;
        case FORMAT_DAY_S:
            type = NUMERIC2BLANK;
            value = dt.getDayOfMonth();
            break;
        case FORMAT_HOUR:
            type = NUMERIC2;
            value = dt.getHourOfDay();
            break;
        case FORMAT_HOUR_BLANK:
            type = NUMERIC2BLANK;
            value = dt.getHourOfDay();
            break;
        case FORMAT_HOUR_M:
        case FORMAT_HOUR_S:
            value = dt.getHourOfDay();
            if (value == 0) {
                value = 12;
            } else if (value > 12) {
                value -= 12;
            }

            type = (format == Format.FORMAT_HOUR_M) ? NUMERIC2 : NUMERIC2BLANK;
            break;
        case FORMAT_DAY_YEAR:
            type = NUMERIC3;
            value = dt.getDayOfYear();
            break;
        case FORMAT_MINUTES:
            type = NUMERIC2;
            value = dt.getMinuteOfHour();
            break;
        case FORMAT_MONTH:
            type = NUMERIC2;
            value = dt.getMonthOfYear();
            break;
        case FORMAT_MERIDIAN:
            output = dt.getHourOfDay() < 12 ? "AM" : "PM";
            break;
        case FORMAT_MERIDIAN_LOWER_CASE:
            output = dt.getHourOfDay() < 12 ? "am" : "pm";
            break;
        case FORMAT_SECONDS:
            type = NUMERIC2;
            value = dt.getSecondOfMinute();
            break;
        case FORMAT_WEEK_YEAR_M:
            type = NUMERIC2;
            value = formatWeekYear(dt, java.util.Calendar.MONDAY);
            break;
        case FORMAT_WEEK_YEAR_S:
            type = NUMERIC2;
            value = formatWeekYear(dt, java.util.Calendar.SUNDAY);
            break;
        case FORMAT_DAY_WEEK:
            type = NUMERIC;
            value = dt.getDayOfWeek() % 7;
            break;
        case FORMAT_DAY_WEEK2:
            type = NUMERIC;
            value = dt.getDayOfWeek();
            break;
        case FORMAT_YEAR_LONG:
            value = year(dt, dt.getYear());
            type = (value >= 0) ? NUMERIC4 : NUMERIC5;
            break;
        case FORMAT_YEAR_SHORT:
            type = NUMERIC2;
            value = year(dt, dt.getYear()) % 100;
            break;
        case FORMAT_COLON_ZONE_OFF:
            // custom logic because this is so weird
            value = dt.getZone().getOffset(dt.getMillis()) / 1000;
            int colons = (Integer) token.getData();
            output = formatZone(colons, (int) value, formatter);
            break;
        case FORMAT_ZONE_ID:
            output = dt.getZone().getShortName(dt.getMillis());
            break;
        case FORMAT_CENTURY:
            type = NUMERIC;
            value = year(dt, dt.getYear()) / 100;
            break;
        case FORMAT_EPOCH:
            type = NUMERIC;
            value = dt.getMillis() / 1000;
            break;
        case FORMAT_WEEK_WEEKYEAR:
            type = NUMERIC2;
            value = dt.getWeekOfWeekyear();
            break;
        case FORMAT_MILLISEC:
        case FORMAT_NANOSEC:
            int defaultWidth = (format == Format.FORMAT_NANOSEC) ? 9 : 3;
            int width = formatter.getWidth(defaultWidth);

            output = RubyTimeOutputFormatter.formatNumber(dt.getMillisOfSecond(), 3, '0');
            if (width > 3) {
                if (sub_millis == null || sub_millis.isNil()) { // Time
                    output += RubyTimeOutputFormatter.formatNumber(nsec, 6, '0');
                } else { // Date, DateTime
                    int prec = width - 3;
                    IRubyObject power = context.runtime.newFixnum(10).callMethod("**",
                            context.runtime.newFixnum(prec));
                    IRubyObject truncated = sub_millis.callMethod(context, "numerator").callMethod(context, "*",
                            power);
                    truncated = truncated.callMethod(context, "/",
                            sub_millis.callMethod(context, "denominator"));
                    long decimals = truncated.convertToInteger().getLongValue();
                    output += RubyTimeOutputFormatter.formatNumber(decimals, prec, '0');
                }
            }

            if (width < output.length()) {
                output = output.substring(0, width);
            } else {
                // Not enough precision, fill with 0
                while (output.length() < width)
                    output += "0";
            }
            formatter = RubyTimeOutputFormatter.DEFAULT_FORMATTER; // no more formatting
            break;
        case FORMAT_WEEKYEAR:
            value = year(dt, dt.getWeekyear());
            type = (value >= 0) ? NUMERIC4 : NUMERIC5;
            break;
        case FORMAT_WEEKYEAR_SHORT:
            type = NUMERIC2;
            value = year(dt, dt.getWeekyear()) % 100;
            break;
        case FORMAT_MICROSEC_EPOCH:
            // only available for Date
            type = NUMERIC;
            value = dt.getMillis();
            break;
        case FORMAT_SPECIAL:
            throw new Error("FORMAT_SPECIAL is a special token only for the lexer.");
        }

        output = formatter.format(output, value, type);
        // reset formatter
        formatter = RubyTimeOutputFormatter.DEFAULT_FORMATTER;

        toAppendTo.append(output
                .getBytes(context.runtime.getEncodingService().charsetForEncoding(toAppendTo.getEncoding())));
    }

    return toAppendTo;
}

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  ww . j a  v a  2s . co 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.validation.TimeDetailValidationUtil.java

License:Educational Community License

public static List<String> validateOverlap(Long startTime, Long endTime, boolean acrossDays, String startDateS,
        String endTimeS, DateTime startTemp, DateTime endTemp, TimesheetDocument timesheetDocument,
        String timeblockId, boolean isRegularEarnCode) {
    List<String> errors = new ArrayList<String>();
    Interval addedTimeblockInterval = new Interval(startTime, endTime);
    List<Interval> dayInt = new ArrayList<Interval>();

    //if the user is clocked in, check if this time block overlaps with the clock action
    ClockLog lastClockLog = TkServiceLocator.getClockLogService()
            .getLastClockLog(HrContext.getTargetPrincipalId());
    if (lastClockLog != null && (lastClockLog.getClockAction().equals(TkConstants.CLOCK_IN)
            || lastClockLog.getClockAction().equals(TkConstants.LUNCH_IN))) {
        DateTime lastClockDateTime = lastClockLog.getClockDateTime();
        String lastClockZone = lastClockLog.getClockTimestampTimezone();
        if (StringUtils.isEmpty(lastClockZone)) {
            lastClockZone = TKUtils.getSystemTimeZone();
        }/*  w w w .  j  a  v a 2 s.co m*/
        DateTimeZone zone = DateTimeZone.forID(lastClockZone);
        DateTime clockWithZone = lastClockDateTime.withZone(zone);
        DateTime currentTime = new DateTime(System.currentTimeMillis(), zone);
        Interval currentClockInInterval = new Interval(clockWithZone.getMillis(), currentTime.getMillis());

        if (isRegularEarnCode && addedTimeblockInterval.overlaps(currentClockInInterval)) {
            errors.add("The time block you are trying to add overlaps with the current clock action.");
            return errors;
        }
    }

    if (acrossDays) {
        DateTime start = new DateTime(startTime);
        DateTime end = TKUtils.convertDateStringToDateTime(startDateS, endTimeS);
        if (endTemp.getDayOfYear() - startTemp.getDayOfYear() < 1) {
            end = new DateTime(endTime);
        }
        DateTime groupEnd = new DateTime(endTime);
        Long startLong = start.getMillis();
        Long endLong = end.getMillis();
        //create interval span if start is before the end and the end is after the start except
        //for when the end is midnight ..that converts to midnight of next day
        DateMidnight midNight = new DateMidnight(endLong);
        while (start.isBefore(groupEnd.getMillis()) && ((endLong >= startLong) || end.isEqual(midNight))) {
            Interval tempInt = null;
            if (end.isEqual(midNight)) {
                tempInt = addedTimeblockInterval;
            } else {
                tempInt = new Interval(startLong, endLong);
            }
            dayInt.add(tempInt);
            start = start.plusDays(1);
            end = end.plusDays(1);
            startLong = start.getMillis();
            endLong = end.getMillis();
        }
    } else {
        dayInt.add(addedTimeblockInterval);
    }

    for (TimeBlock timeBlock : timesheetDocument.getTimeBlocks()) {
        if (errors.size() == 0 && StringUtils.equals(timeBlock.getEarnCodeType(), HrConstants.EARN_CODE_TIME)) {
            Interval timeBlockInterval = new Interval(timeBlock.getBeginTimestamp().getTime(),
                    timeBlock.getEndTimestamp().getTime());
            for (Interval intv : dayInt) {
                if (isRegularEarnCode && timeBlockInterval.overlaps(intv)
                        && (timeblockId == null || timeblockId.compareTo(timeBlock.getTkTimeBlockId()) != 0)) {
                    errors.add("The time block you are trying to add overlaps with an existing time block.");
                }
            }
        }
    }

    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 av a2 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.mifos.calendar.CalendarUtils.java

License:Open Source License

public static DateTime nearestDayOfWeekTo(final int dayOfWeek, final DateTime date) {

    DateTime withDayOfWeek = date.withDayOfWeek(dayOfWeek);

    if (date.getYear() == withDayOfWeek.getYear()) {

        if (date.getDayOfYear() > withDayOfWeek.getDayOfYear()) {
            return withDayOfWeek.plusWeeks(1);
        }//from   w ww . j  ava  2 s .  c om

        return withDayOfWeek;
    }

    // back a year
    if (date.getYear() > withDayOfWeek.getYear()) {
        return withDayOfWeek.plusWeeks(1);
    }

    return withDayOfWeek;
}

From source file:org.numenta.nupic.encoders.DateEncoder.java

License:Open Source License

/**
 * Returns an {@link TDoubleList} containing the sub-field scalar value(s) for
 * each sub-field of the inputData. To get the associated field names for each of
 * the scalar values, call getScalarNames().
 *
 * @param inputData   the input value, in this case a date object
 * @return   a list of one input double/*from   w ww. ja  v a2  s.  co m*/
 */
public TDoubleList getScalars(DateTime inputData) {
    if (inputData == null) {
        throw new IllegalArgumentException("DateEncoder requires a valid Date object but got null");
    }

    TDoubleList values = new TDoubleArrayList();

    //Get the scalar values for each sub-field

    double timeOfDay = inputData.getHourOfDay() + inputData.getMinuteOfHour() / 60.0;

    // The day of week was 1 based, so convert to 0 based
    int dayOfWeek = inputData.getDayOfWeek() - 1; // + timeOfDay / 24.0

    if (seasonEncoder != null) {
        // The day of year was 1 based, so convert to 0 based
        double dayOfYear = inputData.getDayOfYear() - 1;
        values.add(dayOfYear);
    }

    if (dayOfWeekEncoder != null) {
        values.add(dayOfWeek);
    }

    if (weekendEncoder != null) {

        //saturday, sunday or friday evening
        boolean isWeekend = dayOfWeek == 6 || dayOfWeek == 5 || (dayOfWeek == 4 && timeOfDay > 18);

        int weekend = isWeekend ? 1 : 0;

        values.add(weekend);
    }

    if (customDaysEncoder != null) {
        boolean isCustomDays = customDaysList.contains(dayOfWeek);

        int customDay = isCustomDays ? 1 : 0;

        values.add(customDay);
    }

    if (holidayEncoder != null) {
        // A "continuous" binary value. = 1 on the holiday itself and smooth ramp
        //  0->1 on the day before the holiday and 1->0 on the day after the holiday.

        double holidayness = 0;

        for (Tuple h : holidaysList) {
            //hdate is midnight on the holiday
            DateTime hdate = new DateTime(inputData.getYear(), (int) h.get(0), (int) h.get(1), 0, 0, 0);

            if (inputData.isAfter(hdate)) {
                Duration diff = new Interval(hdate, inputData).toDuration();
                long days = diff.getStandardDays();
                if (days == 0) {
                    //return 1 on the holiday itself
                    holidayness = 1;
                    break;
                } else if (days == 1) {
                    //ramp smoothly from 1 -> 0 on the next day
                    holidayness = 1.0 - ((diff.getStandardSeconds() - 86400.0 * days) / 86400.0);
                    break;
                }

            } else {
                //TODO This is not the same as when date.isAfter(hdate), why?
                Duration diff = new Interval(inputData, hdate).toDuration();
                long days = diff.getStandardDays();
                if (days == 0) {
                    //ramp smoothly from 0 -> 1 on the previous day
                    holidayness = 1.0 - ((diff.getStandardSeconds() - 86400.0 * days) / 86400.0);
                    //TODO Why no break?
                }
            }
        }

        values.add(holidayness);
    }

    if (timeOfDayEncoder != null) {
        values.add(timeOfDay);
    }

    return values;
}

From source file:org.projectforge.common.DateHelper.java

License:Open Source License

/**
 * @param d1/*from w  w  w  .  j a  v  a2 s .  com*/
 * @param d2
 * @return True if the dates are both null or both represents the same day (year, month, day) independant of the hours, minutes etc.
 * @see DateHolder#isSameDay(Date)
 */
public static boolean isSameDay(final DateTime d1, final DateTime d2) {
    if (d1 == null) {
        if (d2 == null) {
            return true;
        } else {
            return false;
        }
    } else if (d2 == null) {
        return false;
    }
    return d1.getYear() == d2.getYear() && d1.getDayOfYear() == d2.getDayOfYear();
}

From source file:org.projectforge.web.calendar.TimesheetEventsProvider.java

License:Open Source License

/**
 * @see org.projectforge.web.calendar.MyFullCalendarEventsProvider#buildEvents(org.joda.time.DateTime,
 *      org.joda.time.DateTime)//from  w w  w.j a  v  a  2s .  co  m
 */
@Override
protected void buildEvents(final DateTime start, final DateTime end) {
    totalDuration = 0;
    for (int i = 0; i < durationsPerDayOfMonth.length; i++) {
        durationsPerDayOfMonth[i] = 0;
    }
    for (int i = 0; i < durationsPerDayOfYear.length; i++) {
        durationsPerDayOfYear[i] = 0;
    }
    final Integer userId = calFilter.getTimesheetUserId();
    if (userId == null) {
        return;
    }
    breaksMap = new HashMap<String, TimesheetDO>();
    int breaksCounter = 0;
    final TimesheetFilter filter = new TimesheetFilter();
    filter.setUserId(userId);
    filter.setStartTime(start.toDate());
    filter.setStopTime(end.toDate());
    filter.setOrderType(OrderDirection.ASC);
    timesheets = timesheetDao.getList(filter);
    boolean longFormat = false;
    days = Days.daysBetween(start, end).getDays();
    if (days < 10) {
        // Week or day view:
        longFormat = true;
        month = null;
        firstDayOfMonth = null;
    } else {
        // Month view:
        final DateTime currentMonth = new DateTime(start.plusDays(10),
                ThreadLocalUserContext.getDateTimeZone()); // Now we're definitely in the right
        // month.
        month = currentMonth.getMonthOfYear();
        firstDayOfMonth = currentMonth.withDayOfMonth(1);
    }
    if (CollectionUtils.isEmpty(timesheets) == false) {
        DateTime lastStopTime = null;
        for (final TimesheetDO timesheet : timesheets) {
            final DateTime startTime = new DateTime(timesheet.getStartTime(),
                    ThreadLocalUserContext.getDateTimeZone());
            final DateTime stopTime = new DateTime(timesheet.getStopTime(),
                    ThreadLocalUserContext.getDateTimeZone());
            if (stopTime.isBefore(start) == true || startTime.isAfter(end) == true) {
                // Time sheet doesn't match time period start - end.
                continue;
            }
            if (calFilter.isShowBreaks() == true) {
                if (lastStopTime != null && DateHelper.isSameDay(stopTime, lastStopTime) == true
                        && startTime.getMillis() - lastStopTime.getMillis() > 60000) {
                    // Show breaks between time sheets of one day (> 60s).
                    final Event breakEvent = new Event();
                    breakEvent.setEditable(false);
                    final String breakId = String.valueOf(++breaksCounter);
                    breakEvent.setClassName(Const.BREAK_EVENT_CLASS_NAME).setId(breakId).setStart(lastStopTime)
                            .setEnd(startTime).setTitle(getString("timesheet.break"));
                    breakEvent.setTextColor("#666666").setBackgroundColor("#F9F9F9").setColor("#F9F9F9");
                    events.put(breakId, breakEvent);
                    final TimesheetDO breakTimesheet = new TimesheetDO().setStartDate(lastStopTime.toDate())
                            .setStopTime(startTime.getMillis());
                    breaksMap.put(breakId, breakTimesheet);
                }
                lastStopTime = stopTime;
            }
            final long duration = timesheet.getDuration();
            final MyWicketEvent event = new MyWicketEvent();
            final String id = "" + timesheet.getId();
            event.setClassName(Const.EVENT_CLASS_NAME);
            event.setId(id);
            event.setStart(startTime);
            event.setEnd(stopTime);
            final String title = CalendarHelper.getTitle(timesheet);
            if (longFormat == true) {
                // Week or day view:
                event.setTitle(title + "\n" + getToolTip(timesheet) + "\n" + formatDuration(duration, false));
            } else {
                // Month view:
                event.setTitle(title);
            }
            if (month != null && startTime.getMonthOfYear() != month && stopTime.getMonthOfYear() != month) {
                // Display time sheets of other month as grey blue:
                event.setTextColor("#222222").setBackgroundColor("#ACD9E8").setColor("#ACD9E8");
            }
            events.put(id, event);
            if (month == null || startTime.getMonthOfYear() == month) {
                totalDuration += duration;
                addDurationOfDay(startTime.getDayOfMonth(), duration);
            }
            final int dayOfYear = startTime.getDayOfYear();
            addDurationOfDayOfYear(dayOfYear, duration);
            event.setTooltip(getString("timesheet"),
                    new String[][] { { title }, { timesheet.getLocation(), getString("timesheet.location") },
                            { KostFormatter.formatLong(timesheet.getKost2()), getString("fibu.kost2") },
                            { TaskFormatter.getTaskPath(timesheet.getTaskId(), true, OutputType.PLAIN),
                                    getString("task") },
                            { timesheet.getDescription(), getString("description") } });
        }
    }
    if (calFilter.isShowStatistics() == true) {
        // Show statistics: duration of every day is shown as all day event.
        DateTime day = start;
        final Calendar cal = DateHelper.getCalendar();
        cal.setTime(start.toDate());
        final int numberOfDaysInYear = cal.getActualMaximum(Calendar.DAY_OF_YEAR);
        int paranoiaCounter = 0;
        do {
            if (++paranoiaCounter > 1000) {
                log.error(
                        "Paranoia counter exceeded! Dear developer, please have a look at the implementation of buildEvents.");
                break;
            }
            final int dayOfYear = day.getDayOfYear();
            final long duration = durationsPerDayOfYear[dayOfYear];
            final boolean firstDayOfWeek = day.getDayOfWeek() == ThreadLocalUserContext.getJodaFirstDayOfWeek();
            if (firstDayOfWeek == false && duration == 0) {
                day = day.plusDays(1);
                continue;
            }
            final Event event = new Event().setAllDay(true);
            final String id = "s-" + (dayOfYear);
            event.setId(id);
            event.setStart(day);
            final String durationString = formatDuration(duration, false);
            if (firstDayOfWeek == true) {
                // Show week of year at top of first day of week.
                long weekDuration = 0;
                for (short i = 0; i < 7; i++) {
                    int d = dayOfYear + i;
                    if (d > numberOfDaysInYear) {
                        d -= numberOfDaysInYear;
                    }
                    weekDuration += durationsPerDayOfYear[d];
                }
                final StringBuffer buf = new StringBuffer();
                buf.append(getString("calendar.weekOfYearShortLabel")).append(DateHelper.getWeekOfYear(day));
                if (days > 1 && weekDuration > 0) {
                    // Show total sum of durations over all time sheets of current week (only in week and month view).
                    buf.append(": ").append(formatDuration(weekDuration, false));
                }
                if (duration > 0) {
                    buf.append(", ").append(durationString);
                }
                event.setTitle(buf.toString());
            } else {
                event.setTitle(durationString);
            }
            event.setTextColor("#666666").setBackgroundColor("#F9F9F9").setColor("#F9F9F9");
            event.setEditable(false);
            events.put(id, event);
            day = day.plusDays(1);
        } while (day.isAfter(end) == false);
    }
}

From source file:org.projectforge.web.timesheet.TimesheetEventsProvider.java

License:Open Source License

/**
 * @see org.projectforge.web.calendar.MyFullCalendarEventsProvider#buildEvents(org.joda.time.DateTime, org.joda.time.DateTime)
 *//*  w  w w  .j  a v  a 2  s.co  m*/
@Override
protected void buildEvents(final DateTime start, final DateTime end) {
    totalDuration = 0;
    for (int i = 0; i < durationsPerDayOfMonth.length; i++) {
        durationsPerDayOfMonth[i] = 0;
    }
    for (int i = 0; i < durationsPerDayOfYear.length; i++) {
        durationsPerDayOfYear[i] = 0;
    }
    final Integer userId = calFilter.getTimesheetUserId();
    if (userId == null) {
        return;
    }
    breaksMap = new HashMap<String, TimesheetDO>();
    int breaksCounter = 0;
    final TimesheetFilter filter = new TimesheetFilter();
    filter.setUserId(userId);
    filter.setStartTime(start.toDate());
    filter.setStopTime(end.toDate());
    filter.setOrderType(OrderDirection.ASC);
    timesheets = timesheetDao.getList(filter);
    boolean longFormat = false;
    days = Days.daysBetween(start, end).getDays();
    if (days < 10) {
        // Week or day view:
        longFormat = true;
        month = null;
        firstDayOfMonth = null;
    } else {
        // Month view:
        final DateTime currentMonth = new DateTime(start.plusDays(10), PFUserContext.getDateTimeZone()); // Now we're definitely in the right
        // month.
        month = currentMonth.getMonthOfYear();
        firstDayOfMonth = currentMonth.withDayOfMonth(1);
    }
    if (CollectionUtils.isEmpty(timesheets) == false) {
        DateTime lastStopTime = null;
        for (final TimesheetDO timesheet : timesheets) {
            final DateTime startTime = new DateTime(timesheet.getStartTime(), PFUserContext.getDateTimeZone());
            final DateTime stopTime = new DateTime(timesheet.getStopTime(), PFUserContext.getDateTimeZone());
            if (stopTime.isBefore(start) == true || startTime.isAfter(end) == true) {
                // Time sheet doesn't match time period start - end.
                continue;
            }
            if (calFilter.isShowBreaks() == true) {
                if (lastStopTime != null && DateHelper.isSameDay(stopTime, lastStopTime) == true
                        && startTime.getMillis() - lastStopTime.getMillis() > 60000) {
                    // Show breaks between time sheets of one day (> 60s).
                    final Event breakEvent = new Event();
                    breakEvent.setEditable(false);
                    final String breakId = String.valueOf(++breaksCounter);
                    breakEvent.setClassName(BREAK_EVENT_CLASS_NAME).setId(breakId).setStart(lastStopTime)
                            .setEnd(startTime).setTitle(getString("timesheet.break"));
                    breakEvent.setTextColor("#666666").setBackgroundColor("#F9F9F9").setColor("#F9F9F9");
                    events.put(breakId, breakEvent);
                    final TimesheetDO breakTimesheet = new TimesheetDO().setStartDate(lastStopTime.toDate())
                            .setStopTime(startTime.getMillis());
                    breaksMap.put(breakId, breakTimesheet);
                }
                lastStopTime = stopTime;
            }
            final long duration = timesheet.getDuration();
            final MyEvent event = new MyEvent();
            final String id = "" + timesheet.getId();
            event.setClassName(EVENT_CLASS_NAME);
            event.setId(id);
            event.setStart(startTime);
            event.setEnd(stopTime);
            final String title = getTitle(timesheet);
            if (longFormat == true) {
                // Week or day view:
                event.setTitle(title + "\n" + getToolTip(timesheet) + "\n" + formatDuration(duration, false));
            } else {
                // Month view:
                event.setTitle(title);
            }
            if (month != null && startTime.getMonthOfYear() != month && stopTime.getMonthOfYear() != month) {
                // Display time sheets of other month as grey blue:
                event.setTextColor("#222222").setBackgroundColor("#ACD9E8").setColor("#ACD9E8");
            }
            events.put(id, event);
            if (month == null || startTime.getMonthOfYear() == month) {
                totalDuration += duration;
                addDurationOfDay(startTime.getDayOfMonth(), duration);
            }
            final int dayOfYear = startTime.getDayOfYear();
            addDurationOfDayOfYear(dayOfYear, duration);
            event.setTooltip(getString("timesheet"),
                    new String[][] { { title }, { timesheet.getLocation(), getString("timesheet.location") },
                            { KostFormatter.formatLong(timesheet.getKost2()), getString("fibu.kost2") },
                            { TaskFormatter.instance().getTaskPath(timesheet.getTaskId(), true,
                                    OutputType.PLAIN), getString("task") },
                            { timesheet.getDescription(), getString("description") } });
        }
    }
    if (calFilter.isShowStatistics() == true) {
        // Show statistics: duration of every day is shown as all day event.
        DateTime day = start;
        final Calendar cal = DateHelper.getCalendar();
        cal.setTime(start.toDate());
        final int numberOfDaysInYear = cal.getActualMaximum(Calendar.DAY_OF_YEAR);
        int paranoiaCounter = 0;
        do {
            if (++paranoiaCounter > 1000) {
                log.error(
                        "Paranoia counter exceeded! Dear developer, please have a look at the implementation of buildEvents.");
                break;
            }
            final int dayOfYear = day.getDayOfYear();
            final long duration = durationsPerDayOfYear[dayOfYear];
            final boolean firstDayOfWeek = day.getDayOfWeek() == PFUserContext.getJodaFirstDayOfWeek();
            if (firstDayOfWeek == false && duration == 0) {
                day = day.plusDays(1);
                continue;
            }
            final Event event = new Event().setAllDay(true);
            final String id = "s-" + (dayOfYear);
            event.setId(id);
            event.setStart(day);
            final String durationString = formatDuration(duration, false);
            if (firstDayOfWeek == true) {
                // Show week of year at top of first day of week.
                long weekDuration = 0;
                for (short i = 0; i < 7; i++) {
                    int d = dayOfYear + i;
                    if (d > numberOfDaysInYear) {
                        d -= numberOfDaysInYear;
                    }
                    weekDuration += durationsPerDayOfYear[d];
                }
                final StringBuffer buf = new StringBuffer();
                buf.append(getString("calendar.weekOfYearShortLabel")).append(DateHelper.getWeekOfYear(day));
                if (days > 1 && weekDuration > 0) {
                    // Show total sum of durations over all time sheets of current week (only in week and month view).
                    buf.append(": ").append(formatDuration(weekDuration, false));
                }
                if (duration > 0) {
                    buf.append(", ").append(durationString);
                }
                event.setTitle(buf.toString());
            } else {
                event.setTitle(durationString);
            }
            event.setTextColor("#666666").setBackgroundColor("#F9F9F9").setColor("#F9F9F9");
            event.setEditable(false);
            events.put(id, event);
            day = day.plusDays(1);
        } while (day.isAfter(end) == false);
    }
}