Example usage for org.joda.time DateTime plusDays

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

Introduction

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

Prototype

public DateTime plusDays(int days) 

Source Link

Document

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

Usage

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.
 *///  www.j  a  v a  2 s  .  co 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();
    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())];
            }//from   w  ww .j  a  va 2 s  .  c om
            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 w w  w  . ja v  a 2 s  .c o  m
@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.trakhound.www.trakhound.device_details.DeviceStatus.java

License:Open Source License

public static DeviceStatus get(UserConfiguration userConfig, String uniqueId) {

    if (userConfig != null) {

        DateTime now = DateTime.now();/*from  www  .  jav  a  2 s  .c  o m*/
        DateTime from = new DateTime(now.year().get(), now.monthOfYear().get(), now.dayOfMonth().get(), 0, 0,
                0);
        DateTime to = from.plusDays(1);

        DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
        String fromStr = fmt.print(from);
        String toStr = fmt.print(to);

        String urlSuffix = "data/get/?" + "token=" + userConfig.sessionToken + "&sender_id="
                + UserManagement.getSenderId() + "&devices=[{\"unique_id\":\"" + uniqueId + "\"}]" + "&from="
                + fromStr + "&to=" + toStr + "&command=" + "01111"; // Get Status, Controller, Oee, and Timers tables

        String url = Uri.withAppendedPath(ApiConfiguration.apiHost, urlSuffix).toString();

        String response = Requests.get(url);
        if (response != null && response.length() > 0) {

            try {

                JSONArray a = new JSONArray(response);

                if (a.length() > 0) {

                    JSONObject obj = a.getJSONObject(0);

                    DeviceStatus deviceStatus = new DeviceStatus();

                    deviceStatus.uniqueId = obj.getString("unique_id");

                    deviceStatus.statusInfo = StatusInfo.parse(obj.getJSONObject("status"));

                    deviceStatus.controllerInfo = ControllerInfo.parse(obj.getJSONObject("controller"));

                    deviceStatus.oeeInfo = OeeInfo.parse(obj.getJSONObject("oee"));

                    deviceStatus.timersInfo = TimersInfo.parse(obj.getJSONObject("timers"));

                    return deviceStatus;
                }
            } catch (JSONException ex) {
                Log.d("Exception", ex.getMessage());
            }
        }
    }

    return null;
}

From source file:org.trakhound.www.trakhound.device_list.DeviceStatus.java

License:Open Source License

public static DeviceStatus[] get(UserConfiguration userConfig) {

    if (userConfig != null) {

        try {/*from   w  w w.j  a v a2 s .c  o m*/

            DateTime now = DateTime.now();
            DateTime from = new DateTime(now.year().get(), now.monthOfYear().get(), now.dayOfMonth().get(), 0,
                    0, 0);
            DateTime to = from.plusDays(1);

            DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
            String fromStr = fmt.print(from);
            String toStr = fmt.print(to);

            String urlSuffix = "data/get/?" + "token=" + URLEncoder.encode(userConfig.sessionToken, "UTF-8")
                    + "&sender_id=" + URLEncoder.encode(UserManagement.getSenderId(), "UTF-8") + "&from="
                    + fromStr + "&to=" + toStr + "&command=0101"; // Get Status and Oee tables

            String url = Uri.withAppendedPath(ApiConfiguration.apiHost, urlSuffix).toString();

            String response = Requests.get(url);
            if (response != null && response.length() > 0) {

                ArrayList<DeviceStatus> devicesStatuses = new ArrayList<>();

                try {

                    JSONArray a = new JSONArray(response);

                    for (int i = 0; i < a.length(); i++) {

                        JSONObject obj = a.getJSONObject(i);

                        DeviceStatus deviceStatus = new DeviceStatus();

                        deviceStatus.uniqueId = obj.getString("unique_id");

                        deviceStatus.statusInfo = StatusInfo.parse(obj.getJSONObject("status"));

                        deviceStatus.oeeInfo = OeeInfo.parse(obj.getJSONObject("oee"));

                        devicesStatuses.add(deviceStatus);
                    }
                } catch (JSONException ex) {
                    Log.d("Exception", ex.getMessage());
                }

                DeviceStatus[] deviceStatusArray = new DeviceStatus[devicesStatuses.size()];
                return devicesStatuses.toArray(deviceStatusArray);
            }

        } catch (UnsupportedEncodingException ex) {
            Log.d("Exception", ex.getMessage());
        }
    }

    return null;
}

From source file:org.unitime.timetable.export.events.EventsExportEventsToICal.java

License:Open Source License

public boolean print(ICalendar ical, EventInterface event, Status status) throws IOException {
    if (event.getType() == EventType.Unavailabile)
        return false;

    TreeSet<ICalendarMeeting> meetings = new TreeSet<ICalendarMeeting>();
    Set<Integer> days = new TreeSet<Integer>();
    if (event.hasMeetings())
        meetings: for (MeetingInterface m : event.getMeetings()) {
            if (m.isArrangeHours())
                continue;
            if (m.getApprovalStatus() != ApprovalStatus.Approved
                    && m.getApprovalStatus() != ApprovalStatus.Pending)
                continue;
            ICalendarMeeting x = new ICalendarMeeting(m, status);

            for (ICalendarMeeting icm : meetings)
                if (icm.merge(x))
                    continue meetings;
            meetings.add(x);/*from  w  w  w . j a  v  a 2 s.c  om*/
            days.add(x.getStart().getDayOfWeek());
        }

    if (meetings.isEmpty())
        return false;

    ICalendarMeeting first = meetings.first();

    VEvent master = new VEvent();
    master.setDateStart(first.getDateStart());
    master.setDateEnd(first.getDateEnd());
    master.setLocation(first.getLocation());
    master.setStatus(first.getStatus());
    List<VEvent> events = new ArrayList<VEvent>();
    events.add(master);

    if (meetings.size() > 1) {
        // last day of the recurrence
        DateTime until = new DateTime(meetings.last().getStart().getYear(),
                meetings.last().getStart().getMonthOfYear(), meetings.last().getStart().getDayOfMonth(),
                first.getEnd().getHourOfDay(), first.getEnd().getMinuteOfHour(),
                first.getEnd().getSecondOfMinute());
        // count meeting days
        int nrMeetingDays = 0;
        for (DateTime date = first.getStart(); !date.isAfter(until); date = date.plusDays(1)) {
            // skip days of week with no meeting
            if (days.contains(date.getDayOfWeek()))
                nrMeetingDays++;
        }
        // make sure that there is enough meeting days to cover all meetings
        while (nrMeetingDays < meetings.size()) {
            until = until.plusDays(1);
            if (days.contains(until.getDayOfWeek()))
                nrMeetingDays++;
        }

        Recurrence.Builder recur = new Recurrence.Builder(Frequency.WEEKLY);
        for (Iterator<Integer> i = days.iterator(); i.hasNext();) {
            switch (i.next()) {
            case DateTimeConstants.MONDAY:
                recur.byDay(DayOfWeek.MONDAY);
                break;
            case DateTimeConstants.TUESDAY:
                recur.byDay(DayOfWeek.TUESDAY);
                break;
            case DateTimeConstants.WEDNESDAY:
                recur.byDay(DayOfWeek.WEDNESDAY);
                break;
            case DateTimeConstants.THURSDAY:
                recur.byDay(DayOfWeek.THURSDAY);
                break;
            case DateTimeConstants.FRIDAY:
                recur.byDay(DayOfWeek.FRIDAY);
                break;
            case DateTimeConstants.SATURDAY:
                recur.byDay(DayOfWeek.SATURDAY);
                break;
            case DateTimeConstants.SUNDAY:
                recur.byDay(DayOfWeek.SUNDAY);
                break;
            }
        }
        recur.workweekStarts(DayOfWeek.MONDAY).until(until.toDate());
        master.setRecurrenceRule(recur.build());

        ExceptionDates exdates = new ExceptionDates(true);
        // for all dates till the last date
        dates: for (DateTime date = first.getStart(); !date.isAfter(until); date = date.plusDays(1)) {
            // skip days of week with no meeting
            if (!days.contains(date.getDayOfWeek()))
                continue;
            // try to find a fully matching meeting
            for (Iterator<ICalendarMeeting> i = meetings.iterator(); i.hasNext();) {
                ICalendarMeeting ics = i.next();
                if (date.getYear() == ics.getStart().getYear()
                        && date.getDayOfYear() == ics.getStart().getDayOfYear() && first.same(ics)) {
                    i.remove();
                    continue dates;
                }
            }
            // try to find a meeting that is on the same day
            for (Iterator<ICalendarMeeting> i = meetings.iterator(); i.hasNext();) {
                ICalendarMeeting ics = i.next();
                if (date.getYear() == ics.getStart().getYear()
                        && date.getDayOfYear() == ics.getStart().getDayOfYear()) {
                    VEvent x = new VEvent();
                    RecurrenceId id = new RecurrenceId(date.toDate(), true);
                    id.setLocalTime(false);
                    id.setTimezoneId(TimeZone.getDefault().getID());
                    x.setRecurrenceId(id);
                    x.setDateStart(ics.getDateStart());
                    x.setDateEnd(ics.getDateEnd());
                    x.setLocation(ics.getLocation());
                    x.setStatus(ics.getStatus());
                    events.add(x);
                    i.remove();
                    continue dates;
                }
            }
            // add exception
            exdates.addValue(date.toDate());
        }
        // process remaining meetings
        for (ICalendarMeeting ics : meetings) {
            VEvent x = new VEvent();
            x.setDateStart(ics.getDateStart());
            x.setDateEnd(ics.getDateEnd());
            x.setLocation(ics.getLocation());
            x.setStatus(ics.getStatus());
            // use exception as recurrence if there is one available
            if (!exdates.getValues().isEmpty()) {
                RecurrenceId id = new RecurrenceId(exdates.getValues().get(0), true);
                id.setLocalTime(false);
                id.setTimezoneId(TimeZone.getDefault().getID());
                x.setRecurrenceId(id);
                exdates.getValues().remove(0);
            }
            events.add(x);
        }

        if (!exdates.getValues().isEmpty())
            master.addExceptionDates(exdates);
    }

    for (VEvent vevent : events) {
        vevent.setSequence(event.getSequence());
        vevent.setUid(event.getId().toString());
        vevent.setSummary(event.getName());
        vevent.setDescription(
                event.getInstruction() != null ? event.getInstruction() : event.getType().getName(CONSTANTS));

        if (event.hasTimeStamp()) {
            DateTimeStamp ts = new DateTimeStamp(event.getTimeStamp());
            vevent.setDateTimeStamp(ts);
        }

        if (event.hasInstructors()) {
            int idx = 0;
            for (ContactInterface instructor : event.getInstructors()) {
                if (idx++ == 0) {
                    Organizer organizer = new Organizer(
                            "mailto:" + (instructor.hasEmail() ? instructor.getEmail() : ""));
                    organizer.setCommonName(instructor.getName(MESSAGES));
                    vevent.setOrganizer(organizer);
                } else {
                    Attendee attendee = new Attendee(
                            "mailto:" + (instructor.hasEmail() ? instructor.getEmail() : ""));
                    attendee.setCommonName(instructor.getName(MESSAGES));
                    attendee.setRole(Role.CHAIR);
                    vevent.addAttendee(attendee);
                }
            }
        } else if (event.hasSponsor()) {
            Organizer organizer = new Organizer(
                    "mailto:" + (event.getSponsor().hasEmail() ? event.getSponsor().getEmail() : ""));
            organizer.setCommonName(event.getSponsor().getName());
            vevent.setOrganizer(organizer);
        } else if (event.hasContact()) {
            Organizer organizer = new Organizer(
                    "mailto:" + (event.getContact().hasEmail() ? event.getContact().getEmail() : ""));
            organizer.setCommonName(event.getContact().getName(MESSAGES));
            vevent.setOrganizer(organizer);
        }
        ical.addEvent(vevent);
    }

    return true;
}

From source file:org.vaadin.spring.samples.mvp.ui.component.selector.MarketDayPicker.java

License:Apache License

private void setOffsetDays(int startOffset, int endOffset) {
    setCaption(DEFAULT_CAPTION);//  ww  w .  j a  v  a2 s.c  o  m
    DateTime today = getValue() != null ? new DateTime(getValue().getTime()) : new DateTime();
    Date end = today.plusDays(startOffset).toDate();
    Date start = today.minusDays(endOffset).toDate();
    setValue(today.toDate());
    setDateFormat("yyyy-MM-dd");
    setRangeStart(start);
    setRangeEnd(end);
    setDateOutOfRangeMessage(OUT_OF_RANGE_MESSAGE);
}

From source file:org.vaadin.spring.samples.mvp.ui.mock.MockDsrDAO.java

License:Apache License

@Override
// construct data for any day up to effective date of assetOwner
public List<DSRUpdateDTO> getDSRHourly(DateTime day, String assetOwner) {
    List<DSRUpdateDTO> result = new ArrayList<>();
    DSRUpdateDTO dto = new DSRUpdateDTO();
    List<DSRUpdateHourlyDTO> hourlies = new ArrayList<>();
    DSRUpdateHourlyDTO h;//  w ww  . j av  a  2s  .  co m
    DateTime hour;
    if (data.allParticipants().keySet().contains(assetOwner) && day.isBefore(MockData.TERMINATION_DATE)) {
        dto = new DSRUpdateDTO();
        dto.getId().setDay(SSTimeUtil.dateTimeToIsoDay(day));
        for (DSRUpdateHourlyDTO hourly : data.allDsrHourlyUpdates()) {
            if (assetOwner.equals(hourly.getId().getAssetOwner())) {
                h = new DSRUpdateHourlyDTO();
                h.setCommitStatus(hourly.getCommitStatus());
                h.setEconomicMax(hourly.getEconomicMax());
                h.setEconomicMin(hourly.getEconomicMin());
                h.getId().setAssetOwner(hourly.getId().getAssetOwner());
                h.getId().setLocation(hourly.getId().getLocation());
                int parsedHour = Integer.parseInt(hourly.getId().getHour());
                if (parsedHour >= 0 && parsedHour < 24) {
                    hour = day.plusHours(parsedHour);
                } else {
                    hour = day.plusDays(1);
                }
                h.getId().setHour(SSTimeUtil.dateTimeToIsoNoMillis(hour));
                hourlies.add(h);
            }
        }
        dto.setRecords(hourlies);
        result.add(dto);
    }
    return result;
}

From source file:org.vaadin.spring.samples.mvp.util.SSTimeUtil.java

License:Apache License

/**
 * Calculates the # of hours in a given day (where day is an
 * org.joda.time.DateTime)//from   w ww  .ja v a2  s .  c o  m
 *
 * @param dt
 *            a DateTime instance
 * @return the number of hours in a day respecting time zones that honor
 *         Daylight Savings (e.g., calculation takes into account transition
 *         days)
 */
public static int hoursInDay(final DateTime dt) {
    final DateTime dt0 = dt.withMillisOfDay(0); // Set to start of day
    final DateTime dt1 = dt0.plusDays(1); // Set to end of day
    final Hours hours = Hours.hoursBetween(dt0, dt1);
    return hours.getHours();
}

From source file:org.vaadin.spring.samples.mvp.util.SSTimeUtil.java

License:Apache License

/**
 * <p/>/*  ww w  .j  a  va 2 s. co m*/
 * Gets a <code>day</code> and <code>hour</code> and transforms in to ISO
 * formatted date and time. Considers long and short day offset differences.
 * If it is a short day hour 1 {@link shortDayLabels} is in non DST hours
 * rest are in DST hours if it is a long day hour 1 {@link longDayLabels} is
 * in DST hours rest are in non DST hours, day hour 2 is handled like a
 * repeat of hour 1 except with a standard time offset. If <code>hour</code>
 * is "24" need to advance the day to the next day, i.e 24th hour of today
 * is 00th hour next day.
 *
 * @param day
 *            day in ISO8601 String format (no millis)
 * @param hour
 *            an hour returning from <code>labelsForDay</code> method
 * @return <p/>
 */
public static String getHourInIso(final String day, final String hour) {
    String result = null;
    if (day != null && hour != null) {
        DateTime dateTime = SSTimeUtil.isoDayToDateTime(day);
        String timeZoneOffset = timeZoneOffsetFormat.print(dateTime);
        String adjustedHour = hour;

        if (SSTimeUtil.hoursInDay(dateTime) < 24) { // short day
            // hour 1 should be in -06:00, rest should be in -05:00
            if (hour.equals(shortDayLabels[0])) {
                timeZoneOffset = STANDARD_OFFSET;
            } else {
                timeZoneOffset = DST_OFFSET;
            }
        } else if (SSTimeUtil.hoursInDay(dateTime) > 24) { // long day
            // hour 1 should be in -05:00, hour 2 should be converted to
            // "01"
            // with -06:00 time zone offset, and rest should be in -06:00
            if (hour.equals(longDayLabels[0])) {
                timeZoneOffset = DST_OFFSET;
            } else if (hour.equals(longDayLabels[1])) {
                timeZoneOffset = STANDARD_OFFSET;
                adjustedHour = "01";
            } else {
                timeZoneOffset = STANDARD_OFFSET;
            }
            if (hour.contains("*")) {
                adjustedHour = hour.substring(0, 2);// remove "*02"
                timeZoneOffset = STANDARD_OFFSET;
            }
        }
        if (hour == "24") {
            adjustedHour = "00";
            dateTime = dateTime.plusDays(1);
        }

        dateTime = dateTime.withHourOfDay(Integer.valueOf(adjustedHour))
                .withZoneRetainFields(DateTimeZone.forID(timeZoneOffset));
        result = isoFormat.print(dateTime);
    }
    return result;
}