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:es.usc.citius.servando.calendula.scheduling.DailyAgenda.java

License:Open Source License

public void setupForToday(Context ctx, final boolean force) {

    final SharedPreferences settings = ctx.getSharedPreferences(PREFERENCES_NAME, 0);
    final Long lastDate = settings.getLong(PREF_LAST_DATE, 0);
    final DateTime now = DateTime.now();

    Log.d(TAG, "Setup daily agenda. Last updated: " + new DateTime(lastDate).toString("dd/MM - kk:mm"));

    Interval today = new Interval(now.withTimeAtStartOfDay(), now.withTimeAtStartOfDay().plusDays(1));

    // we need to update daily agenda
    if (!today.contains(lastDate) || force) {
        // Start transaction
        try {//from  w  w w. jav a  2  s .c om
            TransactionManager.callInTransaction(DB.helper().getConnectionSource(), new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    if (!force) {
                        LocalDate yesterday = now.minusDays(1).toLocalDate();
                        LocalDate tomorrow = now.plusDays(1).toLocalDate();

                        // delete items older than yesterday
                        DB.dailyScheduleItems().removeOlderThan(yesterday);
                        // delete items beyond tomorrow (only possible when changing date)
                        DB.dailyScheduleItems().removeBeyond(tomorrow);
                    } else {
                        DB.dailyScheduleItems().removeAll();
                    }
                    // and add new ones
                    createDailySchedule(now);
                    // Save last date to prefs
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putLong(PREF_LAST_DATE, now.getMillis());
                    editor.commit();
                    return null;
                }
            });
        } catch (SQLException e) {
            if (!force) {
                Log.e(TAG, "Error setting up daily agenda. Retrying with force = true", e);
                // setup with force, destroy current daily agenda but continues working
                setupForToday(ctx, true);
            } else {
                Log.e(TAG, "Error setting up daily agenda", e);
            }
        }
        // Update alarms
        AlarmScheduler.instance().updateAllAlarms(ctx);
        CalendulaApp.eventBus().post(new AgendaUpdatedEvent());
    } else {
        Log.d(TAG, "No need to update daily schedule (" + DailyScheduleItem.findAll().size()
                + " items found for today)");
    }
}

From source file:es.usc.citius.servando.calendula.scheduling.DailyAgenda.java

License:Open Source License

public void createDailySchedule(DateTime d) {

    boolean todayCreated = DB.dailyScheduleItems().isDatePresent(d.toLocalDate());

    if (!todayCreated) {
        createScheduleForDate(d.toLocalDate());
    }//from  ww  w.  j av  a 2  s  .  c o  m

    for (int i = 1; i <= NEXT_DAYS_TO_SHOW; i++) {
        LocalDate date = d.plusDays(i).toLocalDate();
        if (!DB.dailyScheduleItems().isDatePresent(date)) {
            createScheduleForDate(date);
        }
    }
}

From source file:es.usc.citius.servando.calendula.util.ScheduleHelper.java

License:Open Source License

public static boolean cycleEnabledForDate(LocalDate date, LocalDate s, int activeDays, int restDays) {
    DateTime start = s.toDateTimeAtStartOfDay();
    DateTime day = date.toDateTimeAtStartOfDay().plusDays(1);

    if (day.isBefore(start))
        return false;

    int activePeriod = activeDays;
    int restPeriod = restDays;
    int cycleLength = activePeriod + restPeriod;
    int days = (int) new Interval(start, day).toDuration().getStandardDays();
    int cyclesUntilNow = days / cycleLength;

    Log.d("ScheduleHelper", "start: " + start.toString("dd/MM/YYYY") + ", day: " + day.toString("dd/MM/YYYY"));
    Log.d("ScheduleHelper", "Active: " + activePeriod + ", rest: " + restPeriod + ", cycle: " + cycleLength
            + ", days: " + days + ", cyclesUntilNow: " + cyclesUntilNow);

    // get start of current cycle

    DateTime cycleStart = start.plusDays(cyclesUntilNow * cycleLength);

    return new Interval(cycleStart, cycleStart.plusDays(activePeriod)).contains(date.toDateTimeAtStartOfDay());

}

From source file:eu.cassandra.training.consumption.ConsumptionEventRepo.java

License:Apache License

/**
 * This function is used to fill the event per date map of the repository.
 * Each available consumption event is parsed and added to the appropriate
 * date./* w  w  w  . j  a  v a 2s  . c  o m*/
 */
public void createEventPerDateHashmap(DateTime startDate, DateTime endDate) {
    // Initialize the auxiliary variables
    Map<DateTime, ArrayList<ConsumptionEvent>> tempMap = new TreeMap<DateTime, ArrayList<ConsumptionEvent>>(
            Constants.comp);
    ArrayList<ConsumptionEvent> events = getEvents();

    // Find the starting dates of all the events.
    DateTime temp = startDate;
    DateTime temp2 = endDate;

    // Fill the map with all the dates
    while (!temp.isAfter(temp2)) {

        tempMap.put(temp, new ArrayList<ConsumptionEvent>());
        temp = temp.plusDays(1);

    }

    // System.out.println(tempMap.toString());

    // Add each and every event to the appropriate date.
    for (int i = 0; i < events.size(); i++) {
        // System.out.println(events.get(i).getStartDate());
        DateTime loop = events.get(i).getStartDate();
        ArrayList<ConsumptionEvent> tempList = tempMap.get(loop);
        tempList.add(events.get(i));
        tempMap.put(loop, tempList);
    }

    // Sort the map based on dates
    eventsPerDate = new TreeMap<DateTime, ArrayList<ConsumptionEvent>>(tempMap);

    // Fill the number of events per date map also.
    for (DateTime date : eventsPerDate.keySet())
        numberEventsPerDate.put(date, eventsPerDate.get(date).size());

    // System.out.println(eventsPerDate.toString());
    // System.out.println(numberEventsPerDate.toString());
}

From source file:eu.finwest.dao.MockDataBuilder.java

private Listing prepareListing(LangVersion lang, String campaign, UserVO owner, String name,
        Listing.State state, String category, int amount, int percentage, String mantra, String summary,
        String companyUrl, DateTime createdAt, DateTime modifiedAt, String logo_url, String address,
        boolean hasBMC, boolean hasIP, String valuation, String cashflow) {
    Listing bp = new Listing();
    bp.id = id();//w  w w  .ja v a  2 s  . co m
    bp.lang = lang;
    bp.currency = lang == LangVersion.PL ? Currency.PLN : Currency.EUR;
    bp.campaign = campaign != null ? campaign : (lang == LangVersion.PL ? "pl" : "en");
    bp.name = name;
    bp.summary = summary;
    bp.mantra = mantra;
    bp.owner = new Key<SBUser>(SBUser.class, owner.toKeyId());
    bp.contactEmail = owner.getEmail();
    bp.founders = getFounders(owner.getName());
    bp.type = Listing.Type.COMPANY;
    bp.notes = "Mock listing.\n";

    bp.askedForFunding = amount > 0;
    bp.suggestedAmount = amount;
    bp.suggestedPercentage = percentage;

    bp.category = category;
    bp.state = state;

    int hours = new Random().nextInt(500) + 80;
    DateTime createdTime = createdAt != null ? createdAt : new DateTime().minusHours(hours);
    if (modifiedAt != null) {
        bp.modified = modifiedAt.toDate();
    }

    bp.created = createdTime.toDate();
    switch (state) {
    case NEW:
        break;
    case POSTED:
        bp.posted = createdTime.plusHours(hours * 5 / 10).toDate();
        break;
    case ACTIVE:
    case FROZEN:
        bp.posted = createdTime.plusHours(hours * 7 / 10).toDate();
        bp.listedOn = createdTime.plusHours(hours * 4 / 10).toDate();
        if (bp.askedForFunding) {
            bp.closingOn = createdTime.plusHours(hours * 4 / 10).plusDays(30).toDate();
        }
        break;
    case WITHDRAWN:
        bp.posted = createdTime.plusHours(hours * 8 / 10).toDate();
        bp.listedOn = createdTime.plusHours(hours * 6 / 10).toDate();
        bp.closingOn = createdTime.plusHours(hours * 6 / 10).plusDays(30).toDate();
        break;
    case CLOSED:
        hours = new Random().nextInt(500) + 33 * 24;
        createdTime = new DateTime().minusHours(hours);
        bp.created = createdTime.toDate();
        bp.posted = createdTime.plusHours(24).toDate();
        bp.listedOn = createdTime.plusHours(48).toDate();
        bp.closingOn = createdTime.plusDays(32).toDate();
        break;
    }

    GeocodeLocation location = null;
    if (address != null) {
        location = getGeocodedLocation(address);
        location.randomize(0.1);
    }
    if (location == null) {
        location = getRandomLocation(lang);
        location.randomize(0.001);
    }

    bp.address = location.address;
    bp.city = location.city;
    bp.usState = "USA".equals(location.country) ? location.state : null;
    bp.country = location.country;
    DtoToVoConverter.updateBriefAddress(bp);
    bp.latitude = location.latitude;
    bp.longitude = location.longitude;

    bp.videoUrl = getVideo();

    bp.website = !StringUtils.isEmpty(companyUrl) ? companyUrl : getWebsite();

    bp.answer1 = hasBMC ? getQuote() : getQuoteWithNulls();
    bp.answer2 = hasBMC ? getQuote() : getQuoteWithNulls();
    bp.answer3 = hasBMC ? getQuote() : getQuoteWithNulls();
    bp.answer4 = hasBMC ? getQuote() : getQuoteWithNulls();
    bp.answer5 = hasBMC ? getQuote() : getQuoteWithNulls();
    bp.answer6 = hasBMC ? getQuote() : getQuoteWithNulls();
    bp.answer7 = hasBMC ? getQuote() : getQuoteWithNulls();
    bp.answer8 = hasBMC ? getQuote() : getQuoteWithNulls();
    bp.answer9 = hasBMC ? getQuote() : getQuoteWithNulls();
    bp.answer10 = hasIP ? getQuote() : getQuoteWithNulls();
    bp.answer11 = hasIP ? getQuote() : getQuoteWithNulls();
    bp.answer12 = hasIP ? getQuote() : getQuoteWithNulls();
    bp.answer13 = hasIP ? getQuote() : getQuoteWithNulls();
    bp.answer14 = hasIP ? getQuote() : getQuoteWithNulls();
    bp.answer15 = hasIP ? getQuote() : getQuoteWithNulls();
    bp.answer16 = hasIP ? getQuote() : getQuoteWithNulls();
    bp.answer17 = hasIP ? getQuote() : getQuoteWithNulls();
    bp.answer18 = hasIP ? getQuote() : getQuoteWithNulls();
    bp.answer19 = hasIP ? getQuote() : getQuoteWithNulls();
    bp.answer20 = hasIP ? getQuote() : getQuoteWithNulls();
    bp.answer21 = hasIP ? getQuote() : getQuoteWithNulls();
    bp.answer22 = hasIP ? getQuote() : getQuoteWithNulls();
    bp.answer23 = hasIP ? getQuote() : getQuoteWithNulls();
    bp.answer24 = hasIP ? getQuote() : getQuoteWithNulls();
    bp.answer25 = hasIP ? getQuote() : getQuoteWithNulls();
    bp.answer26 = hasIP ? getQuote() : getQuoteWithNulls();

    bp.hasBmc = hasBMC;
    bp.hasIp = hasIP;

    bp.valuationData = valuation;
    bp.cashflowData = cashflow;

    if (!StringUtils.isEmpty(logo_url)) {
        logo_url = logo_url.replaceAll("^https://", "http://");
        logoUrls.put(bp.id, logo_url);
    }

    return bp;
}

From source file:femr.business.helpers.LogicDoer.java

License:Open Source License

/**
 * I wonder what this method does//from  w w  w. j a v a2s.co m
 *
 * @param patientEncounter patient encounter
 * @return probably returns true if the encounter is closed
 */
public static boolean isEncounterClosed(IPatientEncounter patientEncounter) {
    DateTime dateOfMedicalVisit = patientEncounter.getDateOfMedicalVisit();
    DateTime dateOfPharmacyVisit = patientEncounter.getDateOfPharmacyVisit();
    Boolean isClosed = false;
    DateTime dateNow = dateUtils.getCurrentDateTime();

    if (dateOfPharmacyVisit != null) {
        isClosed = true;

    } else if (dateOfMedicalVisit != null) {
        //give 1 day before closing
        DateTime dayAfterMedicalVisit = dateOfMedicalVisit.plusDays(1);
        if (dateNow.isAfter(dayAfterMedicalVisit)) {
            isClosed = true;
        }

    } else {
        //give 2 days before closing
        DateTime dayAfterAfterEncounter = patientEncounter.getDateOfTriageVisit().plusDays(2);
        if (dateNow.isAfter(dayAfterAfterEncounter)) {
            isClosed = true;
        }
    }
    return isClosed;
}

From source file:femr.business.services.system.EncounterService.java

License:Open Source License

/**
 * {@inheritDoc}/*from   w  w  w  . j a  v  a 2  s  .c o  m*/
 */
@Override
public ServiceResponse<List<PatientEncounterItem>> retrieveCurrentDayPatientEncounters(int tripID) {
    ServiceResponse<List<PatientEncounterItem>> response = new ServiceResponse<>();
    List<PatientEncounterItem> patientEncounterItems = new ArrayList<>();
    //gets dates for today and tommorrow
    DateTime today = DateTime.now();
    today = today.withTimeAtStartOfDay();
    DateTime tommorrow = today;
    tommorrow = tommorrow.plusDays(1);
    //query todays patients
    ExpressionList<PatientEncounter> query = QueryProvider.getPatientEncounterQuery().where()
            .ge("date_of_triage_visit", today).le("date_of_triage_visit", tommorrow)
            .eq("mission_trip_id", tripID);

    try {
        List<PatientItem> patientItems = null;
        List<? extends IPatientEncounter> patient = patientEncounterRepository.find(query);
        for (IPatientEncounter patient1 : patient) {

            patientEncounterItems.add(itemModelMapper.createPatientEncounterItem(patient1));

        }
        response.setResponseObject(patientEncounterItems);
    } catch (Exception ex) {
        response.addError("", ex.getMessage());
    }
    return response;

}

From source file:fi.craplab.roameo.ui.StatisticsWeekFragment.java

License:Open Source License

private void setupData() {
    DateTime dateTime = getFirstDayOfWeek();
    DebugLog.d(TAG, String.format(Locale.US, "Setting up data for week %2d %d starting %s", mWeekNumber,
            mWeekYear, dateTime));/* w w  w.j a  v  a2 s  .com*/

    for (int day = 0; day < DateTimeConstants.DAYS_PER_WEEK; day++) {
        DateTime dt = dateTime.plusDays(day);

        long steps = CallSession.getStepsForDay(dt.getMillis());
        float duration = CallSession.getDurationsForDay(dt.getMillis()) / 1000;
        float pace = (duration > 0) ? (steps / (duration / 60f)) : 0.0f;

        mStepValues.add(new PointValue(day, steps));
        mDurationValues.add(new PointValue(day, duration));
        mPaceValues.add(new PointValue(day, pace));

        mDayNameValues.add(day, new AxisValue(day).setLabel(dt.dayOfWeek().getAsShortText()));
        mDateValues.add(day, new AxisValue(day)
                .setLabel(String.format(Locale.US, "%02d/%02d", dt.getDayOfMonth(), dt.getMonthOfYear())));
    }
}

From source file:fr.gael.dhus.service.EvictionService.java

License:Open Source License

@PreAuthorize("isAuthenticated ()")
@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
@Cacheable(value = "product_eviction_date", key = "#pid")
public Date getEvictionDate(Long pid) {
    Eviction eviction = evictionDao.getEviction();
    if (eviction.getStrategy() == EvictionStrategy.NONE) {
        return null;
    }/*from  w w w.  ja  v  a 2s.  co  m*/
    Product p = productDao.read(pid);
    DateTime dt = new DateTime(p.getIngestionDate());
    DateTime res = dt.plusDays(eviction.getKeepPeriod());
    return res.toDate();
}

From source file:galileonews.filter.AuthenticateAuthorize.java

License:Apache License

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    final HttpServletRequest req = (HttpServletRequest) request;
    final HttpServletResponse res = (HttpServletResponse) response;
    if ((visit != null) && (visit.getUsers() == null)) {
        visit.setSecurePath(req.getContextPath() + req.getServletPath() + req.getPathInfo());
        res.sendRedirect(req.getContextPath() + "/faces/index.xhtml");
    } else {/*from w  w  w .ja v a 2  s  . c om*/
        if ((visit == null) || (visit.getUsers() == null)) {
            if (visit == null) {
                visit = new VisitBean();
                req.getSession().setAttribute("visit", visit);
            }
            visit.setSecurePath(req.getContextPath() + req.getServletPath() + req.getPathInfo());
            res.sendRedirect(req.getContextPath() + "/faces/index.xhtml");
            return;
        }

        Map<String, Object> param = new HashMap<>();
        param.put("userId", visit.getUsers().getUserId());
        param.put("urlRole", req.getRequestURI());
        List userList;
        try {
            userList = usersDaoBean.selectByUserIdUrl(param);
        } catch (Exception ex) {
            log.severe(ex.toString());
            return;
        }
        if (userList.size() <= 0) {
            res.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
        if (!req.getRequestURI().equals(req.getContextPath() + "/faces/secure/change_password.xhtml")) {
            Configs configs = configsServiceBean.getByKey(ConfigsServiceBean.PASSWORD_EXPIRE_DAYS);
            Integer expireDays = new Integer(configs.getConfigValue());

            DateTime now = new DateTime();
            DateTime lastPwdChange = new DateTime(visit.getUsers().getUserLastPwdChange().getTime());
            DateTime expired = lastPwdChange.plusDays(expireDays);
            if (now.isAfter(expired)) {
                res.sendRedirect(req.getContextPath() + "/faces/secure/change_password.xhtml");
            }
        }
    }
    chain.doFilter(request, response);
}