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.addthis.hydra.data.util.DateUtil.java

License:Apache License

public static DateTime getDateTime(DateTimeFormatter formatter, String date) {
    if (date.startsWith(NOW_PREFIX) && date.endsWith(NOW_POSTFIX)) {
        if (date.equals(NOW)) {
            return new DateTime();
        }/*from   ww  w.j  a  va 2s  .  c o m*/
        DateTime time = new DateTime();
        int pos;
        if ((pos = date.indexOf("+")) > 0) {
            time = time
                    .plusDays(Integer.parseInt(date.substring(pos + 1, date.length() - NOW_POSTFIX.length())));
        } else if ((pos = date.indexOf("-")) > 0) {
            time = time
                    .minusDays(Integer.parseInt(date.substring(pos + 1, date.length() - NOW_POSTFIX.length())));
        }
        return time;
    }
    return formatter.parseDateTime(date);
}

From source file:com.addthis.hydra.task.map.DataPurgeServiceImpl.java

License:Apache License

@Override
public boolean purgeData(DataPurgeConfig dataPurgeConfig, DateTime currentTime) {
    if (!validatePurgeParameters(dataPurgeConfig, currentTime)) {
        return false;
    }/*from   w  w  w .j a  v  a  2 s  . com*/
    DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(dataPurgeConfig.getDatePathFormat());
    DateTime oldestDataAllowed;
    if (dataPurgeConfig.getMaxAgeInDays() > 0) {
        oldestDataAllowed = currentTime.plusDays(-dataPurgeConfig.getMaxAgeInDays());
    } else {
        oldestDataAllowed = currentTime.plusHours(-dataPurgeConfig.getMaxAgeInHours());
    }
    logger.debug("Oldest data allowed {} , current time is {}",
            new Object[] { oldestDataAllowed, currentTime });
    for (String directoryPrefix : dataPurgeConfig.getDirectoryPrefix()) {
        for (File prefixDirectory : expandPrefix(directoryPrefix)) {
            List<File> subdirectories = getSubdirectoryList(prefixDirectory, null);
            for (File subdirectory : subdirectories) {
                logger.trace("Considering directory {} for purge", subdirectory);
                safeDelete(prefixDirectory.getPath(), dateTimeFormatter, oldestDataAllowed, subdirectory,
                        dataPurgeConfig.isFileBasedPurge(), dataPurgeConfig.getDateStartIndex(),
                        dataPurgeConfig.getDateStringLength());
            }
            if (dataPurgeConfig.getCleanEmptyParents()) {
                for (File directory : subdirectories) {
                    if (directory.list() != null && directory.list().length == 0) {
                        try {
                            FileUtils.deleteDirectory(directory);
                        } catch (IOException e) {
                            logger.warn("Failed to delete empty directory {}", directory);
                        }
                    }
                }
            }
        }
    }

    return true;

}

From source file:com.addthis.hydra.task.source.AbstractPersistentStreamSource.java

License:Apache License

/**
 * @return a list of dates given the start/end range from the config
 *//* www . ja  v  a2s.  c om*/
private void fillDateList(DateTime start, DateTime end) {
    DateTime mark = start;
    while (mark.isBefore(end) || mark.isEqual(end)) {
        if (reverse) {
            dates.addFirst(mark);
        } else {
            dates.addLast(mark);
        }
        if ((dateIncrements != null && dateIncrements.equals("DAYS")) || dateFormat.length() == 6) {
            mark = mark.plusDays(1);
        } else if ((dateIncrements != null && dateIncrements.equals("HOURS")) || dateFormat.length() == 8) {
            mark = mark.plusHours(1);
        } else if ((dateIncrements != null && dateIncrements.equals("MONTHS"))) {
            mark = mark.plusMonths(1);
        } else if (dateIncrements == null) {
            log.warn("Non-Standard dateFormat: " + dateFormat + " defaulting to daily time increments\n"
                    + "This can be modified to hourly time increments by setting dateIncrements to 'HOURS'");
            mark = mark.plusDays(1);
        }
    }
}

From source file:com.addthis.hydra.task.source.AbstractPersistentStreamSource.java

License:Apache License

/** */
private DateTime parseDateTime(String dateString) {
    DateTime time;
    if (dateString.contains(NOW_PREFIX)) {
        // TODO: be better to get this time from a service
        time = new DateTime();
        time = time.plusDays(findDaysOffset(dateString));
    } else {//from w w w  .ja v  a  2 s  .  c o  m
        time = formatter.parseDateTime(dateString);
    }
    return time;
}

From source file:com.aionemu.gameserver.dataholders.InstanceCooltimeData.java

License:Open Source License

private long getUpdateHours(String[] days, int hour) {
    DateTime now = DateTime.now();/*from   w ww.  j av a2 s .co m*/
    DateTime repeatDate = new DateTime(now.getYear(), now.getMonthOfYear(), now.getDayOfMonth(), hour, 0, 0);
    int curentDay = now.getDayOfWeek();
    for (String name : days) {
        int day = getDay(name);
        if (day < curentDay) {
            continue;
        }
        if (day == curentDay) {
            if (now.isBefore(repeatDate)) {
                return repeatDate.getMillis();
            }
        } else {
            repeatDate = repeatDate.plusDays(day - curentDay);
            return repeatDate.getMillis();
        }
    }
    return repeatDate.plusDays((7 - curentDay) + getDay(days[0])).getMillis();
}

From source file:com.aionemu.gameserver.model.house.MaintenanceTask.java

License:Open Source License

@Override
protected void executeTask() {
    if (!HousingConfig.ENABLE_HOUSE_PAY) {
        return;//from w  w  w  .j a v a 2 s.  c om
    }

    // Get times based on configuration values
    DateTime now = new DateTime();
    DateTime previousRun = now.minus(getPeriod()); // usually week ago
    DateTime beforePreviousRun = previousRun.minus(getPeriod()); // usually two weeks ago

    for (House house : maintainedHouses) {
        if (house.isFeePaid()) {
            continue; // player already paid, don't check
        }
        long payTime = house.getNextPay().getTime();
        long impoundTime = 0;
        int warnCount = 0;

        PlayerCommonData pcd = null;
        Player player = World.getInstance().findPlayer(house.getOwnerId());
        if (player == null) {
            pcd = DAOManager.getDAO(PlayerDAO.class).loadPlayerCommonData(house.getOwnerId());
        } else {
            pcd = player.getCommonData();
        }

        if (pcd == null) {
            // player doesn't exist already for some reasons
            log.warn("House " + house.getAddress().getId()
                    + " had player assigned but no player exists. Auctioned.");
            putHouseToAuction(house, null);
            continue;
        }

        if (payTime <= beforePreviousRun.getMillis()) {
            DateTime plusDay = beforePreviousRun.minusDays(1);
            if (payTime <= plusDay.getMillis()) {
                // player didn't pay after the second warning and one day passed
                impoundTime = now.getMillis();
                warnCount = 3;
                putHouseToAuction(house, pcd);
            } else {
                impoundTime = now.plusDays(1).getMillis();
                warnCount = 2;
            }
        } else if (payTime <= previousRun.getMillis()) {
            // player did't pay 1 period
            impoundTime = now.plus(getPeriod()).plusDays(1).getMillis();
            warnCount = 1;
        } else {
            continue; // should not happen
        }

        if (pcd.isOnline()) {
            if (warnCount == 3) {
                PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_MSG_HOUSING_SEQUESTRATE);
            } else {
                PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_MSG_HOUSING_OVERDUE);
            }
        }
        MailFormatter.sendHouseMaintenanceMail(house, warnCount, impoundTime);
    }
}

From source file:com.aionemu.gameserver.services.QuestService.java

License:Open Source License

private static Timestamp countNextRepeatTime(Player player, QuestTemplate template) {
    DateTime now = DateTime.now();//from  w w  w. j a v  a 2s .  c o  m
    DateTime repeatDate = new DateTime(now.getYear(), now.getMonthOfYear(), now.getDayOfMonth(), 9, 0, 0);
    if (template.isDaily()) {
        if (now.isAfter(repeatDate)) {
            repeatDate = repeatDate.plusHours(24);
        }
        PacketSendUtility.sendPacket(player, new SM_SYSTEM_MESSAGE(1400855, "9"));
    } else {
        int daysToAdd = 7;
        int startDay = 7;
        for (QuestRepeatCycle weekDay : template.getRepeatCycle()) {
            int diff = weekDay.getDay() - repeatDate.getDayOfWeek();
            if (diff > 0 && diff < daysToAdd) {
                daysToAdd = diff;
            }
            if (startDay > weekDay.getDay()) {
                startDay = weekDay.getDay();
            }
        }
        if (startDay == daysToAdd) {
            daysToAdd = 7;
        } else if (daysToAdd == 7 && startDay < 7) {
            daysToAdd = 7 - repeatDate.getDayOfWeek() + startDay;
        }
        repeatDate = repeatDate.plusDays(daysToAdd);
        PacketSendUtility.sendPacket(player, new SM_SYSTEM_MESSAGE(1400857, new DescriptionId(1800667), "9"));
    }
    return new Timestamp(repeatDate.getMillis());
}

From source file:com.almende.eve.agent.google.GoogleCalendarAgent.java

License:Apache License

/**
 * Get todays events. A convenience method for easy testing
 * //from ww w.ja va  2s .  c  o  m
 * @param calendarId
 *            the calendar id
 * @return the events today
 * @throws Exception
 *             the exception
 */
public ArrayNode getEventsToday(@Optional @Name("calendarId") final String calendarId) throws Exception {
    final DateTime now = DateTime.now();
    final DateTime timeMin = now.minusMillis(now.getMillisOfDay());
    final DateTime timeMax = timeMin.plusDays(1);

    return getEvents(timeMin.toString(), timeMax.toString(), calendarId);
}

From source file:com.almende.eve.agent.google.GoogleCalendarAgent.java

License:Apache License

/**
 * Get busy intervals of today. A convenience method for easy testing
 * /* w  w  w . jav a2s . co m*/
 * @param calendarId
 *            optional calendar id. If not provided, the default calendar is
 *            used
 * @param timeZone
 *            Time zone used in the response. Optional. The default is UTC.
 * @return the busy today
 * @throws Exception
 *             the exception
 */
public ArrayNode getBusyToday(@Optional @Name("calendarId") final String calendarId,
        @Optional @Name("timeZone") final String timeZone) throws Exception {
    final DateTime now = DateTime.now();
    final DateTime timeMin = now.minusMillis(now.getMillisOfDay());
    final DateTime timeMax = timeMin.plusDays(1);

    return getBusy(timeMin.toString(), timeMax.toString(), calendarId, timeZone);
}

From source file:com.almende.eve.agent.MeetingAgent.java

License:Apache License

/**
 * Merge the busy intervals of all attendees, and the preferred intervals
 */// w  ww. j  a v  a 2  s.  c o m
private void mergeTimeConstraints() {
    final ArrayList<Interval> infeasibleIntervals = new ArrayList<Interval>();
    final ArrayList<Weight> preferredIntervals = new ArrayList<Weight>();

    final Activity activity = getActivity();
    if (activity != null) {
        // read and merge the stored busy intervals of all attendees
        for (final Attendee attendee : activity.withConstraints().withAttendees()) {
            final String agent = attendee.getAgent();
            if (attendee.getResponseStatus() != RESPONSE_STATUS.declined) {
                if (new Boolean(true).equals(attendee.getOptional())) {
                    // This attendee is optional.
                    // Add its busy intervals to the soft constraints
                    final List<Interval> attendeeBusy = getAgentBusy(agent);
                    if (attendeeBusy != null) {
                        for (final Interval i : attendeeBusy) {
                            final Weight wi = new Weight(i.getStart(), i.getEnd(),
                                    WEIGHT_BUSY_OPTIONAL_ATTENDEE);

                            preferredIntervals.add(wi);
                        }
                    }
                } else {
                    // this attendee is required.
                    // Add its busy intervals to the hard constraints
                    final List<Interval> attendeeBusy = getAgentBusy(agent);
                    if (attendeeBusy != null) {
                        infeasibleIntervals.addAll(attendeeBusy);
                    }
                }
            }
            // else This attendee declined. Ignore this attendees busy
            // interval
        }

        // read the time preferences and add them to the soft constraints
        final List<Preference> preferences = activity.withConstraints().withTime().withPreferences();
        for (final Preference p : preferences) {
            if (p != null) {
                final Weight wi = new Weight(new DateTime(p.getStart()), new DateTime(p.getEnd()),
                        p.getWeight());

                preferredIntervals.add(wi);
            }
        }
    }

    // add office hours profile to the soft constraints
    // TODO: don't include (hardcoded) office hours here, should be handled
    // by a PersonalAgent
    final DateTime timeMin = DateTime.now();
    final DateTime timeMax = timeMin.plusDays(LOOK_AHEAD_DAYS);
    final List<Interval> officeHours = IntervalsUtil.getOfficeHours(timeMin, timeMax);
    for (final Interval i : officeHours) {
        final Weight wi = new Weight(i, WEIGHT_OFFICE_HOURS);
        preferredIntervals.add(wi);
    }

    // add delay penalties to the soft constraints
    final DateTime now = DateTime.now();
    final MutableDateTime d = new MutableDateTime(now.getYear(), now.getMonthOfYear(), now.getDayOfMonth(), 0,
            0, 0, 0);
    for (int i = 0; i <= LOOK_AHEAD_DAYS; i++) {
        final DateTime start = d.toDateTime();
        final DateTime end = start.plusDays(1);
        final Weight wi = new Weight(start, end, WEIGHT_DELAY_PER_DAY * i);
        preferredIntervals.add(wi);
        d.addDays(1);
    }

    // order and store the aggregated lists with intervals
    IntervalsUtil.order(infeasibleIntervals);
    getState().put("infeasible", infeasibleIntervals);
    WeightsUtil.order(preferredIntervals);
    getState().put("preferred", preferredIntervals);
}