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:com.sheepdog.mashmesh.models.VolunteerProfile.java

License:Apache License

private List<Interval> getAvailableIntervals(DateTime aroundDateTime) {
    List<Interval> intervals = new ArrayList<Interval>();
    Map<Integer, DateTime> adjacentDays = new HashMap<Integer, DateTime>(3);

    // Construct a map from days of the week to DateTimes representing adjacent days.
    for (int i = -1; i <= 1; i++) {
        DateTime dateTime = aroundDateTime.plusDays(i);
        int day = dateTime.getDayOfWeek();
        adjacentDays.put(day, dateTime);
    }//from   w w  w.  jav a 2s . com

    // Construct Intervals from time periods in adjacent days.
    for (AvailableTimePeriod availableTimePeriod : availableTimePeriods) {
        if (adjacentDays.containsKey(availableTimePeriod.getDay())) {
            LocalDate date = adjacentDays.get(availableTimePeriod.getDay()).toLocalDate();
            DateTime start = date.toDateTime(availableTimePeriod.getStartTime(), aroundDateTime.getZone());
            DateTime end = date.toDateTime(availableTimePeriod.getEndTime(), aroundDateTime.getZone());

            // Allow 00:00 - 00:00 to express 00:00 - 24:00 as we can't serialize a
            //  LocalTime representing 24:00.
            if (end.compareTo(start) <= 0) {
                end = end.plusDays(1);
            }

            intervals.add(new Interval(start, end));
        }
    }

    // Sort the Intervals so that adjacent time periods abut. Assumes that intervals don't overlap.
    Collections.sort(intervals, new Comparator<Interval>() {
        @Override
        public int compare(Interval i1, Interval i2) {
            return new Long(i1.getStartMillis()).compareTo(i2.getStartMillis());
        }
    });

    // Merge abutting intervals together
    List<Interval> mergedIntervals = new ArrayList<Interval>();
    Interval lastInterval = null;

    for (Interval interval : intervals) {
        if (lastInterval != null && lastInterval.abuts(interval)) {
            mergedIntervals.remove(mergedIntervals.size() - 1);
            interval = lastInterval.withEnd(interval.getEnd());
        }

        lastInterval = interval;
        mergedIntervals.add(interval);
    }

    return mergedIntervals;
}

From source file:com.soen.smbank.utils.DateUtil.java

public static DateTime addDays(DateTime aDate, int days) {
    DateTime newDate = null;/*from w  w w. jav  a2s .c om*/
    try {
        newDate = aDate.plusDays(days);
    } catch (Exception e) {
        return null;
    }
    return newDate;

}

From source file:com.sonicle.webtop.calendar.CalendarManager.java

License:Open Source License

public List<BaseReminder> getRemindersToBeNotified(DateTime now) {
    EventDAO evtDao = EventDAO.getInstance();
    Connection con = null;/*  w w  w .jav a2 s  .  c o m*/

    ensureSysAdmin();
    ArrayList<VExpEventInstance> evtInstCandidates = new ArrayList<>();

    logger.trace("Analyzing event instances...");
    try {
        final DateTime from = now.withTimeAtStartOfDay();
        con = WT.getConnection(SERVICE_ID, false);

        for (VExpEventInstance evtInst : doEventGetExpiredForUpdate(con, from, from.plusDays(7 * 2 + 1))) {
            final DateTime remindOn = evtInst.getStartDate().withZone(DateTimeZone.UTC)
                    .minusMinutes(evtInst.getReminder());
            if (now.compareTo(remindOn) < 0)
                continue;
            // If instance should have been reminded in past...
            if (evtInst.getRemindedOn() != null) {
                // Only recurring event instances should pass here, classic events are already excluded by the db query
                if (evtInst.getRecurrenceId() == null)
                    throw new WTException("This should never happen (famous last words)");
                final DateTime lastRemindedOn = evtInst.getRemindedOn().withZone(DateTimeZone.UTC);
                if (remindOn.compareTo(lastRemindedOn) <= 0)
                    continue;
                // If instance should have been reminded after last remind...
            }

            int ret = evtDao.updateRemindedOn(con, evtInst.getEventId(), now);
            evtInstCandidates.add(evtInst);
        }
        DbUtils.commitQuietly(con);

    } catch (SQLException | DAOException | WTException ex) {
        DbUtils.rollbackQuietly(con);
        logger.error("Error collecting instances", ex);
    } finally {
        DbUtils.closeQuietly(con);
    }

    logger.debug("Found {} instances to be reminded", evtInstCandidates.size());

    ArrayList<BaseReminder> alerts = new ArrayList<>();
    HashMap<UserProfileId, Boolean> byEmailCache = new HashMap<>();

    logger.trace("Preparing alerts...");
    for (VExpEventInstance evtInst : evtInstCandidates) {
        logger.debug("Working on instance [{}, {}]", evtInst.getEventId(), evtInst.getStartDate());
        if (!byEmailCache.containsKey(evtInst.getCalendarProfileId())) {
            CalendarUserSettings cus = new CalendarUserSettings(SERVICE_ID, evtInst.getCalendarProfileId());
            boolean bool = cus.getEventReminderDelivery()
                    .equals(CalendarSettings.EVENT_REMINDER_DELIVERY_EMAIL);
            byEmailCache.put(evtInst.getCalendarProfileId(), bool);
        }

        if (byEmailCache.get(evtInst.getCalendarProfileId())) {
            UserProfile.Data ud = WT.getUserData(evtInst.getCalendarProfileId());
            CoreUserSettings cus = new CoreUserSettings(evtInst.getCalendarProfileId());

            try {
                EventInstance eventInstance = getEventInstance(evtInst.getKey());
                alerts.add(createEventReminderAlertEmail(ud.getLocale(), cus.getShortDateFormat(),
                        cus.getShortTimeFormat(), ud.getPersonalEmailAddress(), evtInst.getCalendarProfileId(),
                        eventInstance));
            } catch (WTException ex) {
                logger.error("Error preparing email", ex);
            }
        } else {
            alerts.add(createEventReminderAlertWeb(evtInst));
        }
    }

    //FIXME: remove this when zpush is using manager methods
    sendInvitationForZPushEvents();
    // ----------------------------

    return alerts;
}

From source file:com.sonicle.webtop.calendar.CalendarManager.java

License:Open Source License

private <T> List<T> calculateRecurringInstances_OLD(Connection con, RecurringInstanceMapper<T> instanceMapper,
        DateTime fromDate, DateTime toDate, DateTimeZone userTimezone, int limit) throws WTException {
    RecurrenceDAO recDao = RecurrenceDAO.getInstance();
    RecurrenceBrokenDAO recbDao = RecurrenceBrokenDAO.getInstance();
    ArrayList<T> instances = new ArrayList<>();

    int eventId = instanceMapper.getEventId();
    DateTime eventStartDate = instanceMapper.getEventStartDate();
    DateTime eventEndDate = instanceMapper.getEventEndDate();

    // Retrieves reccurence and broken dates (if any)
    ORecurrence orec = recDao.selectByEvent(con, eventId);
    if (orec == null) {
        logger.warn("Unable to retrieve recurrence for event [{}]", eventId);

    } else {/*from   w ww. j a v a  2  s  . co m*/
        if (fromDate == null)
            fromDate = orec.getStartDate();
        if (toDate == null)
            toDate = orec.getStartDate().plusYears(1);

        /*
        List<ORecurrenceBroken> obrecs = recbDao.selectByEventRecurrence(con, eventId, orec.getRecurrenceId());
        //TODO: ritornare direttamente l'hashmap da jooq
        // Builds a hashset of broken dates for increasing performances
        HashMap<String, ORecurrenceBroken> brokenDates = new HashMap<>();
        for (ORecurrenceBroken obrec : obrecs) {
           brokenDates.put(obrec.getEventDate().toString(), obrec);
        }
        */

        Map<LocalDate, ORecurrenceBroken> obrecs = recbDao.selectByEventRecurrence(con, eventId,
                orec.getRecurrenceId());
        HashSet<String> brokenDates = new HashSet<>();
        for (LocalDate ld : obrecs.keySet()) {
            brokenDates.add(ld.toString());
        }

        try {
            // Calculate event length in order to generate events like original one
            int eventDays = CalendarUtils.calculateLengthInDays(eventStartDate, eventEndDate);
            RRule rr = new RRule(orec.getRule());

            // Calcutate recurrence set for required dates range
            PeriodList periods = ICal4jUtils.calculateRecurrenceSet(eventStartDate, eventEndDate,
                    orec.getStartDate(), rr, fromDate, toDate, userTimezone);

            // Recurrence start is useful to skip undesired dates at beginning.
            // If event does not starts at recurrence real beginning (eg. event
            // start on MO but first recurrence begin on WE), ical4j lib includes 
            // those dates in calculated recurrence set, as stated in RFC 
            // (http://tools.ietf.org/search/rfc5545#section-3.8.5.3).
            LocalDate rrStart = ICal4jUtils
                    .calculateRecurrenceStart(orec.getStartDate(), rr.getRecur(), userTimezone).toLocalDate();
            //LocalDate rrStart = ICal4jUtils.calculateRecurrenceStart(eventStartDate, rr.getRecur(), userTimezone).toLocalDate(); //TODO: valutare se salvare la data gi aggiornata
            LocalDate rrEnd = orec.getUntilDate().toLocalDate();

            // Iterates returned recurring periods and builds cloned events...
            int count = -1;
            for (net.fortuna.ical4j.model.Period per : (Iterable<net.fortuna.ical4j.model.Period>) periods) {
                count++;
                if ((limit != -1) && (count > limit))
                    break;
                final LocalDate perStart = ICal4jUtils.toJodaDateTime(per.getStart()).toLocalDate();
                final LocalDate perEnd = ICal4jUtils.toJodaDateTime(per.getEnd()).toLocalDate();

                if (brokenDates.contains(perStart.toString()))
                    continue; // Skip broken dates...
                if ((perStart.compareTo(rrStart) >= 0) && (perEnd.compareTo(rrEnd) <= 0)) { // Skip unwanted dates at beginning
                    final DateTime newStart = eventStartDate.withDate(perStart);
                    final DateTime newEnd = eventEndDate.withDate(newStart.plusDays(eventDays).toLocalDate());
                    final String key = EventKey.buildKey(eventId, eventId, perStart);

                    instances.add(instanceMapper.createInstance(key, newStart, newEnd));
                }
            }

        } catch (DAOException ex) {
            throw wrapException(ex);
        } catch (ParseException ex) {
            throw new WTException(ex, "Unable to parse rrule");
        }
    }
    return instances;
}

From source file:com.sonicle.webtop.calendar.rpt.AbstractAgenda.java

License:Open Source License

public void setDataSource(CalendarManager manager, DateTime fromDate, DateTime toDate, DateTimeZone utz,
        Map<Integer, Calendar> calendars, Collection<SchedEventInstance> instances) throws WTException {
    int days = -1;
    if (DateTimeUtils.isEndOfDay(toDate, true)) {
        days = Days.daysBetween(fromDate, toDate).getDays() + 1;
    } else if (DateTimeUtils.isMidnight(toDate)) {
        days = Days.daysBetween(fromDate, toDate).getDays();
    }/*from  www .  ja va  2s.com*/

    DateTime dayDateFrom = null;
    ArrayList<Date> dayDates = new ArrayList<>();
    ArrayList<ArrayList<RBAgendaEvent>> daysSpanningEvents = new ArrayList<>();
    ArrayList<ArrayList<RBAgendaEvent>> daysEvents = new ArrayList<>();

    // Prepare structures...
    for (int i = 0; i < days; i++) {
        dayDateFrom = fromDate.plusDays(i);
        dayDates.add(dayDateFrom.toDate());
        daysSpanningEvents.add(new ArrayList<RBAgendaEvent>());
        daysEvents.add(new ArrayList<RBAgendaEvent>());
    }

    // Arranges events by day...
    for (SchedEventInstance sei : instances) {
        for (int i = 0; i < days; i++) {
            dayDateFrom = fromDate.plusDays(i);
            if (isInDay(utz, dayDateFrom, sei.getStartDate(), sei.getEndDate())) {
                Calendar calendar = calendars.get(sei.getCalendarId());
                boolean spanning = true;
                Integer spanLeft = null, spanRight = null;
                if (!sei.getAllDay() && startsInDay(utz, dayDateFrom, sei.getStartDate())
                        && endsInDay(utz, dayDateFrom, sei.getEndDate())) {
                    spanning = false;
                } else {
                    if (startsInDay(utz, dayDateFrom, sei.getStartDate())) {
                        spanRight = DateTimeUtils.datesBetween(dayDateFrom, sei.getEndDate().withZone(utz));
                    }
                    if (endsInDay(utz, dayDateFrom, sei.getEndDate())) {
                        spanLeft = DateTimeUtils.datesBetween(sei.getStartDate().withZone(utz), dayDateFrom);
                    }
                    if (!startsInDay(utz, dayDateFrom, sei.getStartDate())
                            && !endsInDay(utz, dayDateFrom, sei.getEndDate())) {
                        spanLeft = DateTimeUtils.datesBetween(sei.getStartDate().withZone(utz), dayDateFrom);
                        spanRight = DateTimeUtils.datesBetween(dayDateFrom, sei.getEndDate().withZone(utz));
                    }
                }
                if (spanning) {
                    daysSpanningEvents.get(i).add(new RBAgendaEvent(calendar, sei, spanLeft, spanRight));
                } else {
                    daysEvents.get(i).add(new RBAgendaEvent(calendar, sei, spanLeft, spanRight));
                }
            }
        }
    }

    setDataSource(createBeanCollection(new Data(utz, fromDate.toLocalDate(), toDate.minusDays(1).toLocalDate(),
            dayDates, daysSpanningEvents, daysEvents)));
}

From source file:com.sonicle.webtop.calendar.rpt.AbstractAgenda.java

License:Open Source License

private boolean isInDay(DateTimeZone utz, DateTime dayDate, DateTime eventStartDate, DateTime eventEndDate) {
    // NB: dayDate must be at midnight!!
    DateTime dayDateTo = dayDate.plusDays(1);
    DateTime start = eventStartDate.withZone(utz);
    DateTime end = eventEndDate.withZone(utz);

    if (startsInDay(utz, dayDate, eventStartDate))
        return true;
    if (endsInDay(utz, dayDate, eventEndDate))
        return true;
    if ((start.compareTo(dayDate) <= 0) && (end.compareTo(dayDateTo) >= 0))
        return true;
    return false;
}

From source file:com.sonicle.webtop.calendar.Service.java

License:Open Source License

public void processPrintScheduler(HttpServletRequest request, HttpServletResponse response) {
    ByteArrayOutputStream baos = null;
    UserProfile up = getEnv().getProfile();

    try {//from   w ww. j a  v  a 2  s  .  c  o  m
        String filename = ServletUtils.getStringParameter(request, "filename", "print");
        String view = ServletUtils.getStringParameter(request, "view", "w5");
        String from = ServletUtils.getStringParameter(request, "startDate", true);

        DateTime startDate = DateTimeUtils.parseYmdHmsWithZone(from, "00:00:00", up.getTimeZone());

        ReportConfig.Builder builder = reportConfigBuilder();
        DateTime fromDate = null, toDate = null;
        AbstractAgenda rpt = null;
        if (view.equals("d")) {
            fromDate = startDate.withTimeAtStartOfDay();
            toDate = startDate.plusDays(1).withTimeAtStartOfDay();
            rpt = new RptAgendaSummary(builder.build(), 1);

        } else if (view.equals("w5")) {
            fromDate = startDate.withTimeAtStartOfDay();
            toDate = startDate.plusDays(5).withTimeAtStartOfDay();
            rpt = new RptAgendaWeek5(builder.build());

        } else if (view.equals("w")) {
            fromDate = startDate.withTimeAtStartOfDay();
            toDate = startDate.plusDays(7).withTimeAtStartOfDay();
            rpt = new RptAgendaWeek7(builder.build());

        } else if (view.equals("dw")) {
            fromDate = startDate.withTimeAtStartOfDay();
            toDate = startDate.plusDays(14).withTimeAtStartOfDay();
            rpt = new RptAgendaSummary(builder.build(), 14);

        } else if (view.equals("m")) {
            if (startDate.getDayOfMonth() == 1) {
                fromDate = startDate.withTimeAtStartOfDay();
            } else {
                fromDate = startDate.plusMonths(1).withDayOfMonth(1).withTimeAtStartOfDay();
            }
            int days = fromDate.dayOfMonth().getMaximumValue();
            toDate = fromDate.plusMonths(1).withDayOfMonth(1).withTimeAtStartOfDay();
            rpt = new RptAgendaSummary(builder.build(), days);

        } else {
            throw new WTException("View not supported [{0}]", view);
        }

        Set<Integer> activeCalIds = getActiveFolderIds();
        Map<Integer, Calendar> calendars = folders.entrySet().stream()
                .filter(map -> activeCalIds.contains(map.getKey()))
                .collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue().getCalendar()));

        List<SchedEventInstance> instances = manager.listEventInstances(activeCalIds,
                new DateTimeRange(fromDate, toDate), up.getTimeZone(), true);
        rpt.setDataSource(manager, fromDate, toDate, up.getTimeZone(), calendars, instances);

        baos = new ByteArrayOutputStream();
        WT.generateReportToStream(rpt, AbstractReport.OutputType.PDF, baos);
        ServletUtils.setContentDispositionHeader(response, "inline", filename + ".pdf");
        ServletUtils.writeContent(response, baos, "application/pdf");

    } catch (Exception ex) {
        logger.error("Error in PrintScheduler", ex);
        ServletUtils.writeErrorHandlingJs(response, ex.getMessage());
    } finally {
        IOUtils.closeQuietly(baos);
    }
}

From source file:com.sonicle.webtop.core.dal.IMMessageDAO.java

License:Open Source License

public List<OIMMessage> selectByProfileChatDate(Connection con, UserProfileId profile, String chatJid,
        LocalDate date, DateTimeZone timezone, boolean byDelivery) throws DAOException {
    DSLContext dsl = getDSL(con);/*from   www.ja v a  2 s.com*/
    final DateTime ts1 = date.toDateTime(LocalTime.MIDNIGHT, timezone);
    final DateTime ts2 = ts1.plusDays(1);

    return dsl
            .select(IM_MESSAGES.ID, IM_MESSAGES.DOMAIN_ID, IM_MESSAGES.CHAT_JID, IM_MESSAGES.SENDER_JID,
                    IM_MESSAGES.SENDER_RESOURCE, IM_MESSAGES.TIMESTAMP, IM_MESSAGES.DELIVERY_TIMESTAMP,
                    IM_MESSAGES.ACTION, IM_MESSAGES.TEXT, IM_MESSAGES.DATA, IM_MESSAGES.MESSAGE_UID,
                    IM_MESSAGES.STANZA_ID)
            .from(IM_MESSAGES)
            .where(IM_MESSAGES.DOMAIN_ID.equal(profile.getDomainId())
                    .and(IM_MESSAGES.USER_ID.equal(profile.getUserId()))
                    .and(IM_MESSAGES.CHAT_JID.equal(chatJid)).and(timestampCondition(byDelivery, ts1, ts2)))
            .orderBy(IM_MESSAGES.TIMESTAMP.asc(), IM_MESSAGES.ID.asc()).fetchInto(OIMMessage.class);
}

From source file:com.sos.jobnet.creator.FrequencyChecker.java

License:Apache License

public void processJobNet(JobNetPlanDBItem bootstrapOrder) {

    String uuid = bootstrapOrder.getUuid();
    logger.info(msg.getMsg(JOBNETCH_I_0001, uuid)); // processing jobnet with id %1$s.
    logger.debug(msg.getMsg(JOBNETCH_D_0002, bootstrapOrder.getNodeId())); // bootstrap order has node id %2$s.

    Date d = bootstrapOrder.getPlannedStartTime();
    if (d == null) {
        String msgText = msg.getMsg(JOBNETCH_E_0001); // bootstrap order has no single_start
        logger.error(msgText);//from w  w w.j  a v a 2  s .c  o  m
        throw new JobNetException(msgText);
    }
    DateTime from = new DateTime(d);
    from = from.minusMillis(from.getMillisOfDay());
    DateTime to = from.plusDays(1);
    Interval baseInterval = new Interval(from, to);
    logger.debug(msg.getMsg(JOBNETCH_D_0001, fmtDateTime.print(from), fmtDateTime.print(to))); // searching for start times of job net nodes from %1$s to %2$s
    LocalDate forDay = new LocalDate(from);

    //      logger.debug(msg.getMsg(JOBNETCH_D_0003,fmtDate.print(baseInterval.getStart()))); // searching for starts at %2$s.
    List<JobNetPlanDBItem> jobnetOrders = getJobnet(uuid);
    if (jobnetOrders == null) {
        String msgText = msg.getMsg(JOBNETCH_E_0002, uuid);
        logger.error(msgText); // no jobnet found for UUID %1$s.
        throw new JobSchedulerException(msgText);
    }

    logger.debug(msg.getMsg(JOBNETCH_D_0004, jobnetOrders.size())); // the jobnet contains %1$s nodes.
    factory.setUseDefaultPeriod(true); // allows the use of runtime elements without or with incomplete periods

    planDbLayer.beginTransaction();
    for (JobNetPlanDBItem currentOrder : jobnetOrders) {
        JobNetNodeDBItem currentNode = getJobNetNode(currentOrder.getNodeId());
        if (!currentOrder.getBootstrap()) { // the properties for the bootstrap order has to be set in JobNetPlanCreator
            if (currentOrder.getIsRunnerSkipped()) {
                logger.info(msg.getMsg(JOBNETCH_I_0002, currentNode.getNode(), currentOrder.getNodeId())); // order %1$s (node id %2$s) is already skipped.
            } else {
                JSObjOrder jsOrder = getJSObjOrder(currentOrder.getOrderXml());
                JSObjRunTime runTime = jsOrder.getJSObjRunTime();
                if (runTime.hasSubsequentRunTimes()) {
                    LocalDate startDay = getNextStartDayInIntervalOrNull(runTime, baseInterval);
                    if (startDay == null) {
                        currentOrder.setIsRunnerSkipped(true);
                        // order %1$s (node id %2$s) has no start time for %3$s and will be skipped.
                        logger.info(msg.getMsg(JOBNETCH_I_0003, currentNode.getNode(), currentOrder.getNodeId(),
                                fmtDate.print(forDay)));
                    } else {
                        // order %1$s (node id %2$s) has a start time for %3$s and will NOT skipped.
                        logger.debug(msg.getMsg(JOBNETCH_I_0005, currentNode.getNode(),
                                currentOrder.getNodeId(), fmtDate.print(forDay)));
                        if (currentOrder.getIsRunnerOnDemand()) {
                            // order %1$s (node id %2$s) has to be started on demand.
                            logger.info(msg.getMsg(JOBNETCH_I_0006, currentNode.getNode(),
                                    currentOrder.getNodeId()));
                            currentOrder.setIsRunnerOnDemand(true);
                        }
                    }
                } else {
                    if (currentOrder.getIsRunnerOnDemand()) {
                        // order %1$s (node id %2$s) has no start time and will be NOT skipped.
                        currentOrder.setIsRunnerOnDemand(true);
                        logger.info(
                                msg.getMsg(JOBNETCH_I_0004, currentNode.getNode(), currentOrder.getNodeId()));
                    } else {
                        logger.debug(
                                "nothing to do - order has neither a start_time nor the parameter on_demand.");
                    }
                }
                logger.debug(currentOrder.getOrderXml().replace("\n", ""));
                planDbLayer.update(currentOrder);

            }
        }
        logRecord(currentNode, currentOrder);
    }
    planDbLayer.commit();
}

From source file:com.sos.jobnet.db.EventsDBLayer.java

License:Apache License

public void createEvent(EventsDBItem record) {
    DateTime now = new DateTime();
    DateTime expired = now.plusDays(60);
    beginTransaction();//from  w  w  w .j a  v a  2s. c om
    record.setCreated(new DateTime());
    record.setExpires(expired);
    saveOrUpdate(record);
    commit();
}