Example usage for org.joda.time DateTime plusYears

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

Introduction

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

Prototype

public DateTime plusYears(int years) 

Source Link

Document

Returns a copy of this datetime plus the specified number of years.

Usage

From source file:org.obm.imap.archive.services.SchedulingDatesService.java

License:Open Source License

private DateTime yearlyNextTreatmentDate(SchedulingConfiguration schedulingConfiguration,
        DateTime currentDateTime, DateTime currentDateWithScheduledTime) {
    DateTime dayOfYear = currentDateWithScheduledTime
            .withDayOfYear(schedulingConfiguration.getDayOfYear().getDayOfYear());
    if (dayOfYear.isAfter(currentDateTime)) {
        return dayOfYear;
    }/*from www  .  j a v  a  2  s . c om*/
    return dayOfYear.plusYears(1);
}

From source file:org.openvpms.archetype.i18n.time.DateDurationFormatter.java

License:Open Source License

/**
 * Formats the duration between two timestamps.
 * <p/>//from  w  w w . j a v  a 2 s . com
 * NOTE: this currently doesn't do anything sensible for from > to. Possible solution would be to simply
 * reverse the times, and then prepend a - between each field using  the
 *
 * @param from the starting time
 * @param to   the ending time
 * @return the formatted duration
 */
protected String format(DateTime from, DateTime to) {
    int years = 0;
    int months = 0;
    int weeks = 0;
    int days = 0;
    int hours = 0;
    int minutes = 0;

    DateTime start = from;
    if (showYears) {
        years = Years.yearsBetween(start, to).getYears();
        start = start.plusYears(years);
    }
    if (showMonths) {
        months = Months.monthsBetween(start, to).getMonths();
        start = start.plusMonths(months);
    }
    if (showWeeks) {
        weeks = Weeks.weeksBetween(start, to).getWeeks();
        start = start.plusWeeks(weeks);
    }
    if (showDays) {
        days = Days.daysBetween(start, to).getDays();
        start = start.plusDays(days);
    }
    if (showHours) {
        hours = Hours.hoursBetween(start, to).getHours();
        start = start.plusHours(hours);
    }
    if (showMinutes) {
        minutes = Minutes.minutesBetween(start, to).getMinutes();
    }

    Period period = new Period(years, months, weeks, days, hours, minutes, 0, 0);
    return formatter.print(period);
}

From source file:org.projectforge.business.teamcal.servlet.CalendarAboServlet.java

License:Open Source License

/**
 * builds the list of events//from w  w w .j av a  2 s.  c  o m
 *
 * @return
 */
private List<VEvent> getEvents(final Map<String, String> params, PFUserDO timesheetUser) {
    final PFUserDO loggedInUser = ThreadLocalUserContext.getUser();
    if (loggedInUser == null) {
        throw new AccessException("No logged-in-user found!");
    }
    final List<VEvent> events = new ArrayList<VEvent>();
    final TimeZone timezone = ICal4JUtils.getUserTimeZone();
    final java.util.Calendar cal = java.util.Calendar.getInstance(ThreadLocalUserContext.getTimeZone());

    boolean eventsExist = false;
    final List<VEvent> list = teamCalCalendarFeedHook.getEvents(params, timezone);
    if (list != null && list.size() > 0) {
        events.addAll(list);
        eventsExist = true;
    }

    if (timesheetUser != null) {
        if (loggedInUser.getId().equals(timesheetUser.getId()) == false && isOtherUsersAllowed() == false) {
            // Only project managers, controllers and administrative staff is allowed to subscribe time-sheets of other users.
            log.warn("User tried to get time-sheets of other user: " + timesheetUser);
            timesheetUser = loggedInUser;
        }
        // initializes timesheet filter
        final TimesheetFilter filter = new TimesheetFilter();
        filter.setUserId(timesheetUser.getId());
        filter.setDeleted(false);
        filter.setStopTime(cal.getTime());
        // calculates the offset of the calendar
        final int offset = cal.get(java.util.Calendar.MONTH) - CalendarFeedConst.PERIOD_IN_MONTHS;
        if (offset < 0) {
            setCalDate(cal, cal.get(java.util.Calendar.YEAR) - 1, 12 + offset);
        } else {
            setCalDate(cal, cal.get(java.util.Calendar.YEAR), offset);
        }
        filter.setStartTime(cal.getTime());

        final List<TimesheetDO> timesheetList = timesheetDao.getList(filter);

        // iterate over all timesheets and adds each event to the calendar
        for (final TimesheetDO timesheet : timesheetList) {

            final String uid = TeamCalConfig.get().createTimesheetUid(timesheet.getId());
            String summary;
            if (eventsExist == true) {
                summary = CalendarHelper.getTitle(timesheet) + " (ts)";
            } else {
                summary = CalendarHelper.getTitle(timesheet);
            }
            final VEvent vEvent = ICal4JUtils.createVEvent(timesheet.getStartTime(), timesheet.getStopTime(),
                    uid, summary);
            if (StringUtils.isNotBlank(timesheet.getDescription()) == true) {
                vEvent.getProperties().add(new Description(timesheet.getDescription()));
            }
            if (StringUtils.isNotBlank(timesheet.getLocation()) == true) {
                vEvent.getProperties().add(new Location(timesheet.getLocation()));
            }
            events.add(vEvent);
        }
    }
    final String holidays = params.get(CalendarFeedConst.PARAM_NAME_HOLIDAYS);
    if ("true".equals(holidays) == true) {
        DateTime holidaysFrom = new DateTime(ThreadLocalUserContext.getDateTimeZone());
        holidaysFrom = holidaysFrom.dayOfYear().withMinimumValue().millisOfDay().withMinimumValue()
                .minusYears(2);
        final DateTime holidayTo = holidaysFrom.plusYears(6);
        events.addAll(teamCalService.getConfiguredHolidaysAsVEvent(holidaysFrom, holidayTo));
    }
    final String weeksOfYear = params.get(CalendarFeedConst.PARAM_NAME_WEEK_OF_YEARS);
    if ("true".equals(weeksOfYear) == true) {
        final DayHolder from = new DayHolder();
        from.setBeginOfYear().add(java.util.Calendar.YEAR, -2).setBeginOfWeek();
        final DayHolder to = new DayHolder(from);
        to.add(java.util.Calendar.YEAR, 6);
        final DayHolder current = new DayHolder(from);
        int paranoiaCounter = 0;
        do {
            final VEvent vEvent = ICal4JUtils.createVEvent(current.getDate(), current.getDate(),
                    "pf-weekOfYear" + current.getYear() + "-" + paranoiaCounter,
                    ThreadLocalUserContext.getLocalizedString("calendar.weekOfYearShortLabel") + " "
                            + current.getWeekOfYear(),
                    true);
            events.add(vEvent);
            current.add(java.util.Calendar.WEEK_OF_YEAR, 1);
            if (++paranoiaCounter > 500) {
                log.warn(
                        "Dear developer, please have a look here, paranoiaCounter exceeded! Aborting calculation of weeks of year.");
            }
        } while (current.before(to) == true);
    }
    // Integer hrPlanningUserId = NumberHelper.parseInteger(params.get(PARAM_NAME_HR_PLANNING));
    // if (hrPlanningUserId != null) {
    // if (loggedInUser.getId().equals(hrPlanningUserId) == false && isOtherUsersAllowed() == false) {
    // // Only project managers, controllers and administrative staff is allowed to subscribe time-sheets of other users.
    // log.warn("User tried to get time-sheets of other user: " + timesheetUser);
    // hrPlanningUserId = loggedInUser.getId();
    // }
    // final HRPlanningDao hrPlanningDao = Registry.instance().getDao(HRPlanningDao.class);
    // final HRPlanningEventsProvider hrPlanningEventsProvider = new HRPlanningEventsProvider(new CalendarFilter().setShowPlanning(true)
    // .setTimesheetUserId(hrPlanningUserId), hrPlanningDao);
    // DateTime planningFrom = new DateTime(ThreadLocalUserContext.getDateTimeZone());
    // planningFrom = planningFrom.dayOfYear().withMinimumValue().millisOfDay().withMinimumValue().minusYears(1);
    // final DateTime planningTo = planningFrom.plusYears(4);
    // for (final Event event : hrPlanningEventsProvider.getEvents(planningFrom, planningTo)) {
    // final Date fromDate = event.getStart().toDate();
    // final Date toDate = event.getEnd() != null ? event.getEnd().toDate() : fromDate;
    // final VEvent vEvent = ICal4JUtils.createVEvent(fromDate, toDate, "pf-hr-planning" + event.getId(), event.getTitle(), true);
    // events.add(vEvent);
    // }
    // }
    return events;
}

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

License:Open Source License

/**
 * builds the list of events/*  ww  w  . j av  a  2  s. c  o  m*/
 * 
 * @return
 */
private List<VEvent> getEvents(final Map<String, String> params, PFUserDO timesheetUser) {
    final PFUserDO loggedInUser = PFUserContext.getUser();
    if (loggedInUser == null) {
        throw new AccessException("No logged-in-user found!");
    }
    final List<VEvent> events = new ArrayList<VEvent>();
    final TimeZone timezone = ICal4JUtils.getUserTimeZone();
    final java.util.Calendar cal = java.util.Calendar.getInstance(PFUserContext.getTimeZone());

    boolean eventsExist = false;
    for (final CalendarFeedHook hook : feedHooks) {
        final List<VEvent> list = hook.getEvents(params, timezone);
        if (list != null && list.size() > 0) {
            events.addAll(list);
            eventsExist = true;
        }
    }

    if (timesheetUser != null) {
        if (loggedInUser.getId().equals(timesheetUser.getId()) == false && isOtherUsersAllowed() == false) {
            // Only project managers, controllers and administrative staff is allowed to subscribe time-sheets of other users.
            log.warn("User tried to get time-sheets of other user: " + timesheetUser);
            timesheetUser = loggedInUser;
        }
        // initializes timesheet filter
        final TimesheetFilter filter = new TimesheetFilter();
        filter.setUserId(timesheetUser.getId());
        filter.setDeleted(false);
        filter.setStopTime(cal.getTime());
        // calculates the offset of the calendar
        final int offset = cal.get(java.util.Calendar.MONTH) - PERIOD_IN_MONTHS;
        if (offset < 0) {
            setCalDate(cal, cal.get(java.util.Calendar.YEAR) - 1, 12 + offset);
        } else {
            setCalDate(cal, cal.get(java.util.Calendar.YEAR), offset);
        }
        filter.setStartTime(cal.getTime());

        final TimesheetDao timesheetDao = Registry.instance().getDao(TimesheetDao.class);
        final List<TimesheetDO> timesheetList = timesheetDao.getList(filter);

        // iterate over all timesheets and adds each event to the calendar
        for (final TimesheetDO timesheet : timesheetList) {
            final String uid = TeamCalConfig.get().createTimesheetUid(timesheet.getId());
            String summary;
            if (eventsExist == true) {
                summary = TimesheetEventsProvider.getTitle(timesheet) + " (ts)";
            } else {
                summary = TimesheetEventsProvider.getTitle(timesheet);
            }
            final VEvent vEvent = ICal4JUtils.createVEvent(timesheet.getStartTime(), timesheet.getStopTime(),
                    uid, summary);
            if (StringUtils.isNotBlank(timesheet.getDescription()) == true) {
                vEvent.getProperties().add(new Description(timesheet.getDescription()));
            }
            if (StringUtils.isNotBlank(timesheet.getLocation()) == true) {
                vEvent.getProperties().add(new Location(timesheet.getLocation()));
            }
            events.add(vEvent);
        }
    }
    final String holidays = params.get(PARAM_NAME_HOLIDAYS);
    if ("true".equals(holidays) == true) {
        final HolidayEventsProvider holidaysEventsProvider = new HolidayEventsProvider();
        DateTime holidaysFrom = new DateTime(PFUserContext.getDateTimeZone());
        holidaysFrom = holidaysFrom.dayOfYear().withMinimumValue().millisOfDay().withMinimumValue()
                .minusYears(2);
        final DateTime holidayTo = holidaysFrom.plusYears(6);
        for (final Event event : holidaysEventsProvider.getEvents(holidaysFrom, holidayTo)) {
            final Date fromDate = event.getStart().toDate();
            final Date toDate = event.getEnd() != null ? event.getEnd().toDate() : fromDate;
            final VEvent vEvent = ICal4JUtils.createVEvent(fromDate, toDate, "pf-holiday" + event.getId(),
                    event.getTitle(), true);
            events.add(vEvent);
        }
    }
    final String weeksOfYear = params.get(PARAM_NAME_WEEK_OF_YEARS);
    if ("true".equals(weeksOfYear) == true) {
        final DayHolder from = new DayHolder();
        from.setBeginOfYear().add(java.util.Calendar.YEAR, -2).setBeginOfWeek();
        final DayHolder to = new DayHolder(from);
        to.add(java.util.Calendar.YEAR, 6);
        final DayHolder current = new DayHolder(from);
        int paranoiaCounter = 0;
        do {
            final VEvent vEvent = ICal4JUtils.createVEvent(current.getDate(), current.getDate(),
                    "pf-weekOfYear" + current.getYear() + "-" + paranoiaCounter,
                    PFUserContext.getLocalizedString("calendar.weekOfYearShortLabel") + " "
                            + current.getWeekOfYear(),
                    true);
            events.add(vEvent);
            current.add(java.util.Calendar.WEEK_OF_YEAR, 1);
            if (++paranoiaCounter > 500) {
                log.warn(
                        "Dear developer, please have a look here, paranoiaCounter exceeded! Aborting calculation of weeks of year.");
            }
        } while (current.before(to) == true);
    }
    // Integer hrPlanningUserId = NumberHelper.parseInteger(params.get(PARAM_NAME_HR_PLANNING));
    // if (hrPlanningUserId != null) {
    // if (loggedInUser.getId().equals(hrPlanningUserId) == false && isOtherUsersAllowed() == false) {
    // // Only project managers, controllers and administrative staff is allowed to subscribe time-sheets of other users.
    // log.warn("User tried to get time-sheets of other user: " + timesheetUser);
    // hrPlanningUserId = loggedInUser.getId();
    // }
    // final HRPlanningDao hrPlanningDao = Registry.instance().getDao(HRPlanningDao.class);
    // final HRPlanningEventsProvider hrPlanningEventsProvider = new HRPlanningEventsProvider(new CalendarFilter().setShowPlanning(true)
    // .setTimesheetUserId(hrPlanningUserId), hrPlanningDao);
    // DateTime planningFrom = new DateTime(PFUserContext.getDateTimeZone());
    // planningFrom = planningFrom.dayOfYear().withMinimumValue().millisOfDay().withMinimumValue().minusYears(1);
    // final DateTime planningTo = planningFrom.plusYears(4);
    // for (final Event event : hrPlanningEventsProvider.getEvents(planningFrom, planningTo)) {
    // final Date fromDate = event.getStart().toDate();
    // final Date toDate = event.getEnd() != null ? event.getEnd().toDate() : fromDate;
    // final VEvent vEvent = ICal4JUtils.createVEvent(fromDate, toDate, "pf-hr-planning" + event.getId(), event.getTitle(), true);
    // events.add(vEvent);
    // }
    // }
    return events;
}

From source file:org.springframework.analytics.metrics.memory.InMemoryAggregateCounter.java

License:Apache License

public AggregateCounter getCounts(Interval interval, AggregateCounterResolution resolution) {
    DateTime start = interval.getStart();
    DateTime end = interval.getEnd();//  w w  w  .j a  va 2s .c o  m
    Chronology c = interval.getChronology();

    long[] counts;
    if (resolution == AggregateCounterResolution.minute) {
        List<long[]> days = accumulateDayCounts(minuteCountsByDay, start, end, 60 * 24);

        counts = MetricUtils.concatArrays(days, interval.getStart().getMinuteOfDay(),
                interval.toPeriod().toStandardMinutes().getMinutes() + 1);
    } else if (resolution == AggregateCounterResolution.hour) {
        List<long[]> days = accumulateDayCounts(hourCountsByDay, start, end, 24);

        counts = MetricUtils.concatArrays(days, interval.getStart().getHourOfDay(),
                interval.toPeriod().toStandardHours().getHours() + 1);
    } else if (resolution == AggregateCounterResolution.day) {
        DateTime startDay = new DateTime(c.dayOfYear().roundFloor(start.getMillis()));
        DateTime endDay = new DateTime(c.dayOfYear().roundFloor(end.plusDays(1).getMillis()));
        int nDays = Days.daysBetween(startDay, endDay).getDays();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> yearDays = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(end.getMillis()));

        while (cursor.isBefore(endYear)) {
            long[] dayCounts = dayCountsByYear.get(cursor.getYear());
            if (dayCounts == null) {
                // Querying where we have no data
                dayCounts = new long[daysInYear(cursor.getYear())];
            }
            yearDays.add(dayCounts);
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(yearDays, startDay.getDayOfYear() - 1, nDays);

    } else if (resolution == AggregateCounterResolution.month) {
        DateTime startMonth = new DateTime(c.monthOfYear().roundFloor(interval.getStartMillis()));
        DateTime endMonth = new DateTime(c.monthOfYear().roundFloor(end.plusMonths(1).getMillis()));
        int nMonths = Months.monthsBetween(startMonth, endMonth).getMonths();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> yearMonths = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(end.getMillis()));

        while (cursor.isBefore(endYear)) {
            long[] monthCounts = monthCountsByYear.get(cursor.getYear());
            if (monthCounts == null) {
                monthCounts = new long[12];
            }
            yearMonths.add(monthCounts);
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(yearMonths, startMonth.getMonthOfYear() - 1, nMonths);
    } else if (resolution == AggregateCounterResolution.year) {
        DateTime startYear = new DateTime(interval.getStart().getYear(), 1, 1, 0, 0);
        DateTime endYear = new DateTime(end.getYear() + 1, 1, 1, 0, 0);
        int nYears = Years.yearsBetween(startYear, endYear).getYears();
        counts = new long[nYears];

        for (int i = 0; i < nYears; i++) {
            long[] monthCounts = monthCountsByYear.get(startYear.plusYears(i).getYear());
            counts[i] = MetricUtils.sum(monthCounts);
        }

    } else {
        throw new IllegalStateException("Shouldn't happen. Unhandled resolution: " + resolution);
    }
    return new AggregateCounter(this.name, interval, counts, resolution);
}

From source file:org.springframework.analytics.metrics.redis.RedisAggregateCounterRepository.java

License:Apache License

/**
 * For each query, we need to convert the interval into two variations. One is the start and end points rounded to
 * the resolution (used to calculate the number of entries to be returned from the query). The second is the start
 * and end buckets we have to retrieve which may contain entries for the interval. For example, when querying
 * at day resolution, the number of entries is the number of Joda time days between the start (rounded down to a
 * day boundary) and the end plus one day (also rounded down). However, we need load the data from the buckets
 * from the month the start day occurs in to the month end day occurs in. These are then concatenated, using the
 * start day as the start index into the first array, and writing the total number of entries in sequence from that
 * point into the combined result counts array.
 *///  w  w  w . jav a 2 s.c  o m
@Override
public AggregateCounter getCounts(String name, Interval interval, AggregateCounterResolution resolution) {

    DateTime end = interval.getEnd();
    Chronology c = interval.getChronology();

    long[] counts;

    if (resolution == AggregateCounterResolution.minute) {
        // Iterate through each hour in the interval and load the minutes for it
        MutableDateTime dt = new MutableDateTime(interval.getStart());
        dt.setRounding(c.hourOfDay());
        Duration step = Duration.standardHours(1);
        List<long[]> hours = new ArrayList<long[]>();
        while (dt.isBefore(end) || dt.isEqual(end)) {
            hours.add(getMinCountsForHour(name, dt));
            dt.add(step);
        }
        counts = MetricUtils.concatArrays(hours, interval.getStart().getMinuteOfHour(),
                interval.toPeriod().toStandardMinutes().getMinutes() + 1);

    } else if (resolution == AggregateCounterResolution.hour) {
        DateTime cursor = new DateTime(c.dayOfMonth().roundFloor(interval.getStart().getMillis()));
        List<long[]> days = new ArrayList<long[]>();
        Duration step = Duration.standardHours(24);
        while (cursor.isBefore(end)) {
            days.add(getHourCountsForDay(name, cursor));
            cursor = cursor.plus(step);
        }

        counts = MetricUtils.concatArrays(days, interval.getStart().getHourOfDay(),
                interval.toPeriod().toStandardHours().getHours() + 1);

    } else if (resolution == AggregateCounterResolution.day) {
        DateTime startDay = new DateTime(c.dayOfYear().roundFloor(interval.getStart().getMillis()));
        DateTime endDay = new DateTime(c.dayOfYear().roundFloor(end.plusDays(1).getMillis()));
        int nDays = Days.daysBetween(startDay, endDay).getDays();
        DateTime cursor = new DateTime(c.monthOfYear().roundFloor(interval.getStart().getMillis()));
        List<long[]> months = new ArrayList<long[]>();
        DateTime endMonth = new DateTime(
                c.monthOfYear().roundCeiling(interval.getEnd().plusMonths(1).getMillis()));
        while (cursor.isBefore(endMonth)) {
            months.add(getDayCountsForMonth(name, cursor));
            cursor = cursor.plusMonths(1);
        }

        counts = MetricUtils.concatArrays(months, interval.getStart().getDayOfMonth() - 1, nDays);
    } else if (resolution == AggregateCounterResolution.month) {
        DateTime startMonth = new DateTime(c.monthOfYear().roundFloor(interval.getStartMillis()));
        DateTime endMonth = new DateTime(c.monthOfYear().roundFloor(end.plusMonths(1).getMillis()));
        int nMonths = Months.monthsBetween(startMonth, endMonth).getMonths();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> years = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(interval.getEnd().plusYears(1).getMillis()));
        while (cursor.isBefore(endYear)) {
            years.add(getMonthCountsForYear(name, cursor));
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(years, interval.getStart().getMonthOfYear() - 1, nMonths);
    } else if (resolution == AggregateCounterResolution.year) {
        DateTime startYear = new DateTime(interval.getStart().getYear(), 1, 1, 0, 0);
        DateTime endYear = new DateTime(end.getYear() + 1, 1, 1, 0, 0);
        int nYears = Years.yearsBetween(startYear, endYear).getYears();
        Map<String, Long> yearCounts = getYearCounts(name);
        counts = new long[nYears];

        for (int i = 0; i < nYears; i++) {
            int year = startYear.plusYears(i).getYear();
            Long count = yearCounts.get(Integer.toString(year));
            if (count == null) {
                count = 0L;
            }
            counts[i] = count;
        }
    } else {
        throw new IllegalStateException("Shouldn't happen. Unhandled resolution: " + resolution);
    }
    return new AggregateCounter(name, interval, counts, resolution);
}

From source file:org.springframework.xd.analytics.metrics.memory.InMemoryAggregateCounter.java

License:Apache License

public AggregateCount getCounts(Interval interval, AggregateCountResolution resolution) {
    DateTime start = interval.getStart();
    DateTime end = interval.getEnd();/*  w w  w . j a  va 2 s .  co m*/
    Chronology c = interval.getChronology();

    long[] counts;
    if (resolution == AggregateCountResolution.minute) {
        List<long[]> days = accumulateDayCounts(minuteCountsByDay, start, end, 60 * 24);

        counts = MetricUtils.concatArrays(days, interval.getStart().getMinuteOfDay(),
                interval.toPeriod().toStandardMinutes().getMinutes() + 1);
    } else if (resolution == AggregateCountResolution.hour) {
        List<long[]> days = accumulateDayCounts(hourCountsByDay, start, end, 24);

        counts = MetricUtils.concatArrays(days, interval.getStart().getHourOfDay(),
                interval.toPeriod().toStandardHours().getHours() + 1);
    } else if (resolution == AggregateCountResolution.day) {
        DateTime startDay = new DateTime(c.dayOfYear().roundFloor(start.getMillis()));
        DateTime endDay = new DateTime(c.dayOfYear().roundFloor(end.plusDays(1).getMillis()));
        int nDays = Days.daysBetween(startDay, endDay).getDays();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> yearDays = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(end.getMillis()));

        while (cursor.isBefore(endYear)) {
            long[] dayCounts = dayCountsByYear.get(cursor.getYear());
            if (dayCounts == null) {
                // Querying where we have no data
                dayCounts = new long[daysInYear(cursor.getYear())];
            }
            yearDays.add(dayCounts);
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(yearDays, startDay.getDayOfYear() - 1, nDays);

    } else if (resolution == AggregateCountResolution.month) {
        DateTime startMonth = new DateTime(c.monthOfYear().roundFloor(interval.getStartMillis()));
        DateTime endMonth = new DateTime(c.monthOfYear().roundFloor(end.plusMonths(1).getMillis()));
        int nMonths = Months.monthsBetween(startMonth, endMonth).getMonths();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> yearMonths = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(end.getMillis()));

        while (cursor.isBefore(endYear)) {
            long[] monthCounts = monthCountsByYear.get(cursor.getYear());
            if (monthCounts == null) {
                monthCounts = new long[12];
            }
            yearMonths.add(monthCounts);
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(yearMonths, startMonth.getMonthOfYear() - 1, nMonths);
    } else if (resolution == AggregateCountResolution.year) {
        DateTime startYear = new DateTime(interval.getStart().getYear(), 1, 1, 0, 0);
        DateTime endYear = new DateTime(end.getYear() + 1, 1, 1, 0, 0);
        int nYears = Years.yearsBetween(startYear, endYear).getYears();
        counts = new long[nYears];

        for (int i = 0; i < nYears; i++) {
            long[] monthCounts = monthCountsByYear.get(startYear.plusYears(i).getYear());
            counts[i] = MetricUtils.sum(monthCounts);
        }

    } else {
        throw new IllegalStateException("Shouldn't happen. Unhandled resolution: " + resolution);
    }
    return new AggregateCount(getName(), interval, counts, resolution);
}

From source file:org.springframework.xd.analytics.metrics.redis.RedisAggregateCounterRepository.java

License:Apache License

/**
 * For each query, we need to convert the interval into two variations. One is the start and end points rounded to
 * the resolution (used to calculate the number of entries to be returned from the query). The second is the start
 * and end buckets we have to retrieve which may contain entries for the interval. For example, when querying
 * at day resolution, the number of entries is the number of Joda time days between the start (rounded down to a
 * day boundary) and the end plus one day (also rounded down). However, we need load the data from the buckets
 * from the month the start day occurs in to the month end day occurs in. These are then concatenated, using the
 * start day as the start index into the first array, and writing the total number of entries in sequence from that
 * point into the combined result counts array.
 *//*from ww  w .  jav a2s . c  om*/
@Override
public AggregateCount getCounts(String name, Interval interval, AggregateCountResolution resolution) {

    DateTime end = interval.getEnd();
    Chronology c = interval.getChronology();

    long[] counts;

    if (resolution == AggregateCountResolution.minute) {
        // Iterate through each hour in the interval and load the minutes for it
        MutableDateTime dt = new MutableDateTime(interval.getStart());
        dt.setRounding(c.hourOfDay());
        Duration step = Duration.standardHours(1);
        List<long[]> hours = new ArrayList<long[]>();
        while (dt.isBefore(end) || dt.isEqual(end)) {
            hours.add(getMinCountsForHour(name, dt));
            dt.add(step);
        }
        counts = MetricUtils.concatArrays(hours, interval.getStart().getMinuteOfHour(),
                interval.toPeriod().toStandardMinutes().getMinutes() + 1);

    } else if (resolution == AggregateCountResolution.hour) {
        DateTime cursor = new DateTime(c.dayOfMonth().roundFloor(interval.getStart().getMillis()));
        List<long[]> days = new ArrayList<long[]>();
        Duration step = Duration.standardHours(24);
        while (cursor.isBefore(end)) {
            days.add(getHourCountsForDay(name, cursor));
            cursor = cursor.plus(step);
        }

        counts = MetricUtils.concatArrays(days, interval.getStart().getHourOfDay(),
                interval.toPeriod().toStandardHours().getHours() + 1);

    } else if (resolution == AggregateCountResolution.day) {
        DateTime startDay = new DateTime(c.dayOfYear().roundFloor(interval.getStart().getMillis()));
        DateTime endDay = new DateTime(c.dayOfYear().roundFloor(end.plusDays(1).getMillis()));
        int nDays = Days.daysBetween(startDay, endDay).getDays();
        DateTime cursor = new DateTime(c.monthOfYear().roundFloor(interval.getStart().getMillis()));
        List<long[]> months = new ArrayList<long[]>();
        DateTime endMonth = new DateTime(
                c.monthOfYear().roundCeiling(interval.getEnd().plusMonths(1).getMillis()));
        while (cursor.isBefore(endMonth)) {
            months.add(getDayCountsForMonth(name, cursor));
            cursor = cursor.plusMonths(1);
        }

        counts = MetricUtils.concatArrays(months, interval.getStart().getDayOfMonth() - 1, nDays);
    } else if (resolution == AggregateCountResolution.month) {
        DateTime startMonth = new DateTime(c.monthOfYear().roundFloor(interval.getStartMillis()));
        DateTime endMonth = new DateTime(c.monthOfYear().roundFloor(end.plusMonths(1).getMillis()));
        int nMonths = Months.monthsBetween(startMonth, endMonth).getMonths();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> years = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(interval.getEnd().plusYears(1).getMillis()));
        while (cursor.isBefore(endYear)) {
            years.add(getMonthCountsForYear(name, cursor));
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(years, interval.getStart().getMonthOfYear() - 1, nMonths);
    } else if (resolution == AggregateCountResolution.year) {
        DateTime startYear = new DateTime(interval.getStart().getYear(), 1, 1, 0, 0);
        DateTime endYear = new DateTime(end.getYear() + 1, 1, 1, 0, 0);
        int nYears = Years.yearsBetween(startYear, endYear).getYears();
        Map<String, Long> yearCounts = getYearCounts(name);
        counts = new long[nYears];

        for (int i = 0; i < nYears; i++) {
            int year = startYear.plusYears(i).getYear();
            Long count = yearCounts.get(Integer.toString(year));
            if (count == null) {
                count = 0L;
            }
            counts[i] = count;
        }
    } else {
        throw new IllegalStateException("Shouldn't happen. Unhandled resolution: " + resolution);
    }
    return new AggregateCount(name, interval, counts, resolution);
}

From source file:org.terasoluna.tourreservation.app.searchtour.DepYearCodeList.java

License:Apache License

@Override
public Map<String, String> asMap() {
    DateTime dateTime = dateFactory.newDateTime();
    DateTime nextYearDateTime = dateTime.plusYears(1);

    Map<String, String> depYearMap = new LinkedHashMap<String, String>();

    String thisYear = dateTime.toString("Y");
    String nextYear = nextYearDateTime.toString("Y");
    depYearMap.put(thisYear, thisYear);/*from   w w  w. jav  a 2  s .c o  m*/
    depYearMap.put(nextYear, nextYear);

    return Collections.unmodifiableMap(depYearMap);
}

From source file:org.zkoss.ganttz.LeftTasksTreeRow.java

License:Open Source License

private Constraint generateConstraintForDates() {
    return new Constraint() {
        @Override//from   www  .  j  a v a  2 s.c  o m
        public void validate(Component comp, Object value) throws WrongValueException {

            // Getting parameters from properties file
            int yearLimit = Integer.parseInt(properties.getProperty("yearLimit"));
            int minimumYear = Integer.parseInt(properties.getProperty("minimumYear"));

            DateTime today = new DateTime();
            DateTime maximum = today.plusYears(yearLimit);

            DateTime minimum = new DateTime(
                    new GregorianCalendar(minimumYear, MINIMUM_MONTH, MINIMUM_DAY).getTime());

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yy");

            // Need to call dateFormat.set2DigitYearStart to force parser not to parse date to previous century
            simpleDateFormat.set2DigitYearStart(
                    new GregorianCalendar(CALENDAR_START_YEAR, MINIMUM_MONTH, MINIMUM_DAY).getTime());

            Date date = null;

            /*
             * Need to check value type because constraint is created for textbox and datebox.
             * Textbox returns value in String. Datebox returns value in java.util.Date.
             * Also need to take last two year digits because Datebox component formats it's value.
             */

            if (value instanceof Date) {
                try {

                    // Using DateTime (Joda Time class) because java.util.Date.getYear() returns invalid value
                    DateTime correct = new DateTime(value);
                    String year = Integer.valueOf(correct.getYear()).toString().substring(2);

                    // TODO Resolve deprecated methods
                    date = simpleDateFormat
                            .parse(((Date) value).getMonth() + "/" + ((Date) value).getDate() + "/" + year);

                } catch (ParseException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    date = simpleDateFormat.parse((String) value);
                } catch (ParseException ignored) {
                }
            }

            DateTime dateTimeInTextbox = new DateTime(date);

            if (dateTimeInTextbox.isAfter(maximum)) {
                throw new WrongValueException(comp,
                        _("The date you entered is invalid") + ". " + _("Please enter date not before") + " "
                                + minimumYear + " " + _("and no later than") + " " + maximum.getYear());
            }
            if (dateTimeInTextbox.isBefore(minimum)) {
                throw new WrongValueException(comp,
                        _("The date you entered is invalid") + ". " + _("Please enter date not before") + " "
                                + minimumYear + " " + _("and no later than") + " " + maximum.getYear());
            }
        }
    };
}