Example usage for org.joda.time LocalDate plusDays

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

Introduction

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

Prototype

public LocalDate plusDays(int days) 

Source Link

Document

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

Usage

From source file:energy.usef.dso.repository.ConnectionMeterEventRepository.java

License:Apache License

/**
 * Finds connections not related to ConnectionMeterEvents.
 * /*from w  ww.  j av  a2 s  .  c o m*/
 * @param date date
 * @param connectionIncludeList connection include list
 * @return connection list
 */
public List<Connection> findConnectionsNotRelatedToConnectionMeterEvents(LocalDate date,
        List<String> connectionIncludeList) {
    StringBuilder sql = new StringBuilder();
    sql.append("SELECT distinct cgs.connection FROM ConnectionGroupState cgs");
    sql.append(" WHERE cgs.validFrom <= :startDate");
    sql.append(" AND cgs.validUntil >= :startDate");
    sql.append(" AND cgs.connection NOT IN ");
    sql.append(
            "  (SELECT cme.connection FROM ConnectionMeterEvent cme WHERE cme.dateTime >= :startTime AND cme.dateTime < :endTime)");
    sql.append(" AND cgs.connection.entityAddress IN :connectionIncludeList");

    TypedQuery<Connection> query = entityManager.createQuery(sql.toString(), Connection.class);
    query.setParameter("startDate", date.toDateMidnight().toDate());
    query.setParameter("startTime", date.toDateMidnight().toDateTime().toDate(), TemporalType.TIMESTAMP);
    query.setParameter("endTime", date.plusDays(1).toDateMidnight().toDateTime().toDate(),
            TemporalType.TIMESTAMP);
    query.setParameter("connectionIncludeList", connectionIncludeList);
    return query.getResultList();
}

From source file:energy.usef.dso.repository.ConnectionMeterEventRepository.java

License:Apache License

/**
 * This method finds a Connection for a given connection entity address and a certain period.
 *
 * @param entityAddress connection entity address
 * @param date date/*from   w  ww .  j  av a2 s  . co m*/
 * 
 * @return connection if exists, null otherwise
 */
@SuppressWarnings("unchecked")
public Connection findConnectionForConnectionMeterEventsPeriod(String entityAddress, LocalDate date) {
    StringBuilder queryString = new StringBuilder();
    queryString.append("SELECT cme.connection FROM ConnectionMeterEvent cme ");
    queryString.append(" WHERE cme.dateTime >= :fromTime ");
    queryString.append("  AND cme.dateTime < :endTime ");
    queryString.append("  AND cme.connection.entityAddress = :entityAddress ");

    Query query = getEntityManager().createQuery(queryString.toString());
    query.setParameter("fromTime", date.toDateMidnight().toDateTime().toDate(), TemporalType.TIMESTAMP);
    query.setParameter("endTime", date.plusDays(1).toDateMidnight().toDateTime().toDate(),
            TemporalType.TIMESTAMP);
    query.setParameter("entityAddress", entityAddress);

    List<Connection> connections = query.getResultList();
    if (connections.isEmpty()) {
        return null;
    }
    return connections.get(0);
}

From source file:energy.usef.dso.service.business.DsoPlanboardBusinessService.java

License:Apache License

/**
 * Updates the aggregaters linked to the congestionPoint.
 *
 * @param xmlCongestionPoint {@link CongestionPoint} for which the aggregator count will be updated.
 * @param initializationDate {@link LocalDate} date of the initializtion of the aggregator count.
 * @param initializationDuration {@link Integer} duration of the initalization.
 *///from   w w  w  .j  a  v a  2  s.c o  m
public void updateAggregatorsOnCongestionPointConnectionGroup(CongestionPoint xmlCongestionPoint,
        LocalDate initializationDate, Integer initializationDuration) {

    CongestionPointConnectionGroup congestionPoint = congestionPointConnectionGroupRepository
            .findOrCreate(xmlCongestionPoint.getEntityAddress(), config.getProperty(ConfigParam.HOST_DOMAIN));

    List<AggregatorOnConnectionGroupState> endingAtDate = aggregatorOnConnectionGroupStateRepository
            .findEndingAggregatorOnConnectionGroupStates(congestionPoint.getUsefIdentifier(),
                    initializationDate);

    // for each ending aggregator/connection group state for which nothing is updated, extend the valid until date.
    endingAtDate.stream()
            .filter(aocgs -> xmlCongestionPoint.getAggregator().stream()
                    .anyMatch(aggregator -> aocgs.getConnectionCount().equals(aggregator.getConnectionCount())
                            && aocgs.getAggregator().getDomain().equals(aggregator.getDomain())
                            && aocgs.getCongestionPointConnectionGroup().getUsefIdentifier()
                                    .equals(xmlCongestionPoint.getEntityAddress())))
            .forEach(aocgs -> aocgs.setValidUntil(aocgs.getValidUntil().plusDays(initializationDuration)));

    // create new records if anything changed
    xmlCongestionPoint.getAggregator().stream()
            .filter(aggregator -> endingAtDate.stream()
                    .noneMatch(aocgs -> aocgs.getConnectionCount().equals(aggregator.getConnectionCount())
                            && aocgs.getAggregator().getDomain().equals(aggregator.getDomain())
                            && aocgs.getCongestionPointConnectionGroup().getUsefIdentifier()
                                    .equals(xmlCongestionPoint.getEntityAddress())))
            .filter(xmlAggregator -> StringUtils.isNotEmpty(xmlAggregator.getDomain()))
            .forEach(xmlAggregator -> {
                Aggregator dbAggregator = aggregatorRepository.findOrCreate(xmlAggregator.getDomain());
                AggregatorOnConnectionGroupState newState = new AggregatorOnConnectionGroupState();
                newState.setAggregator(dbAggregator);
                newState.setConnectionCount(xmlAggregator.getConnectionCount() == null ? BigInteger.ZERO
                        : xmlAggregator.getConnectionCount());
                newState.setValidFrom(initializationDate);
                newState.setValidUntil(initializationDate.plusDays(initializationDuration));
                newState.setCongestionPointConnectionGroup(congestionPoint);
                aggregatorOnConnectionGroupStateRepository.persist(newState);
            });
}

From source file:energy.usef.dso.workflow.plan.connection.forecast.DsoConnectionForecastPlanboardCoordinator.java

License:Apache License

/**
 * {@inheritDoc}//from  w  w  w.  ja  va 2 s  .co m
 */
@Asynchronous
@Lock(LockType.WRITE)
public void handleEvent(
        @Observes(during = TransactionPhase.AFTER_COMPLETION) CreateConnectionForecastEvent event) {
    LOGGER.info(LOG_COORDINATOR_START_HANDLING_EVENT, event);
    int interval = configDso.getIntegerProperty(ConfigDsoParam.DSO_CONNECTION_FORECAST_DAYS_INTERVAL);
    Map<ConnectionGroup, List<Connection>> connectionGroups;
    LocalDate forecastDay;
    for (int dayShift = 1; dayShift <= interval; dayShift++) {
        forecastDay = DateTimeUtil.getCurrentDate().plusDays(dayShift);
        LOGGER.debug("Creating connection forecasts for period [{}]", forecastDay);
        connectionGroups = corePlanboardBusinessService.findActiveConnectionGroupsWithConnections(forecastDay);
        for (Map.Entry<ConnectionGroup, List<Connection>> entry : connectionGroups.entrySet()) {
            LOGGER.trace("Handling connection forecast for ConnectionGroup [{}].",
                    entry.getKey().getUsefIdentifier());
            processForecastPeriod(forecastDay, entry);
        }

        // Move to validate phase
        moveToValidateEventManager.fire(new RequestMoveToValidateEvent(forecastDay));

        // Next day
        forecastDay = forecastDay.plusDays(1);
    }
    LOGGER.info(LOG_COORDINATOR_FINISHED_HANDLING_EVENT, event);
}

From source file:energy.usef.pbcfeeder.PbcFeeder.java

License:Apache License

/**
 * @param date/*from  w w w.jav a  2  s.  c  o  m*/
 * @param startPtuIndex of the list starting from 1 till 96 (PTU_PER_DAY).
 * @param amount
 * @return
 */
public List<PbcStubDataDto> getStubRowInputList(LocalDate date, int startPtuIndex, int amount) {
    if (startPtuIndex > PTU_PER_DAY) {
        date = date.plusDays((int) Math.floor(startPtuIndex / PTU_PER_DAY));
        startPtuIndex = startPtuIndex % PTU_PER_DAY;
    }

    // Match PTU-index with requested startIndex and date from ExcelSheet.
    LocalDate epochDate = new LocalDate("1970-01-01");
    int daysDif = Days.daysBetween(epochDate, date).getDays();
    int ptuOffset = (daysDif % DAYS_IN_SPREADSHEET) * PTU_PER_DAY + startPtuIndex - 1;
    List<PbcStubDataDto> pbcStubDataDtoList = new ArrayList<>();

    // Loop over stubRowInputList, if necessary, to get requested amount of ptus.
    do {
        int toIndex = 0;
        if (ptuOffset + amount > stubRowInputList.size()) {
            toIndex = stubRowInputList.size();
        } else {
            toIndex = ptuOffset + amount;
        }
        amount -= (toIndex - ptuOffset);

        pbcStubDataDtoList.addAll(stubRowInputList.subList(ptuOffset, toIndex));
        ptuOffset = 0;
    } while (amount > 0);

    // Create and set PtuContainer for pbcStubDataDto.

    int lastPtuIndex = 0;
    for (PbcStubDataDto pbcStubDataDto : pbcStubDataDtoList) {
        int ptuIndex = pbcStubDataDto.getIndex() % PTU_PER_DAY;
        if (ptuIndex == 0) {
            ptuIndex = PTU_PER_DAY;
        }
        if (ptuIndex < lastPtuIndex) {
            date = date.plusDays(1);
        }
        PbcPtuContainerDto ptuContainerDto = new PbcPtuContainerDto(date.toDateMidnight().toDate(), ptuIndex);
        pbcStubDataDto.setPtuContainer(ptuContainerDto);
        lastPtuIndex = ptuIndex;
    }
    return pbcStubDataDtoList;
}

From source file:es.usc.citius.servando.calendula.activities.CalendarActivity.java

License:Open Source License

public CharSequence getBestDayText() {

    final List<PickupInfo> urgent = pickupUtils.urgentMeds();
    Pair<LocalDate, List<PickupInfo>> best = pickupUtils.getBestDay();

    final List<PickupInfo> next = (best == null || best.first == null) ? new ArrayList<PickupInfo>()
            : best.second;/*from   ww  w.  j a  v  a  2s . co  m*/

    CharSequence msg = new SpannableString("No hai medicinas que recoger");
    LocalDate today = LocalDate.now();

    // there are not urgent meds, but there are others to pickup
    if (urgent.isEmpty() && best != null) {

        //            Log.d("Calendar", "Urgent: " + urgent.size());
        //            Log.d("Calendar", "Next: " + next.size());

        Log.d("Calendar", "there are not urgent meds, but there are others to pickup");
        if (next.size() > 1) {
            msg = new SpannableString(getString(R.string.best_single_day_messge,
                    best.first.toString(getString(R.string.best_date_format)), next.size()) + "\n\n");
        } else {
            msg = new SpannableString(getString(R.string.best_single_day_messge_one_med,
                    best.first.toString(getString(R.string.best_date_format))) + "\n\n");
        }
        msg = addPickupList(msg, next);
    }

    // there are urgent meds
    Log.d("Calendar", "there are urgent meds");
    if (!urgent.isEmpty()) {
        // and others
        Log.d("Calendar", "and others");
        if (best != null) {

            String bestStr = best.equals(LocalDate.now().plusDays(1))
                    ? getString(R.string.calendar_date_tomorrow)
                    : best.first.toString(getString(R.string.best_date_format));

            // and the others date is near
            Log.d("Calendar", "and the others date is near");
            if (today.plusDays(3).isAfter(best.first)) {
                List<PickupInfo> all = new ArrayList<>();
                all.addAll(urgent);
                all.addAll(next);
                msg = new SpannableString(
                        getString(R.string.best_single_day_messge, bestStr, all.size()) + "\n\n");
                msg = addPickupList(msg, all);
            }
            // and the others date is not near
            else {

                Log.d("Calendar", "and the others date is not near");
                msg = addPickupList(new SpannableString(getString(R.string.pending_meds_msg) + "\n\n"), urgent);

                msg = TextUtils.concat(msg, new SpannableString("\n"));
                if (next.size() > 1) {
                    Log.d("Calendar", " size > 1");
                    msg = TextUtils.concat(msg,
                            getString(R.string.best_single_day_messge_after_pending, bestStr, next.size())
                                    + "\n\n");
                } else {
                    Log.d("Calendar", " size <= 1");
                    msg = TextUtils.concat(msg,
                            getString(R.string.best_single_day_messge_after_pending_one_med, bestStr) + "\n\n");
                }
                msg = addPickupList(msg, next);
            }
        } else {
            Log.d("Calendar", " there are only urgent meds");
            // there are only urgent meds
            msg = addPickupList(getString(R.string.pending_meds_msg) + "\n\n", urgent);
        }
    }

    Log.d("BEST_DAY", msg.toString());
    return msg;
}

From source file:es.usc.citius.servando.calendula.activities.SummaryCalendarActivity.java

License:Open Source License

private void setupCalendar() {

    calendar = (CalendarPickerView) findViewById(R.id.calendar_view);
    calendar.setVerticalScrollBarEnabled(false);

    RepetitionRule r;//from  w  ww .  j ava2s.  co m
    String rule = getIntent().getStringExtra("rule");
    String date = getIntent().getStringExtra("start");

    int activeDays = getIntent().getIntExtra("active_days", -1);
    int restDays = getIntent().getIntExtra("rest_days", -1);

    LocalDate from = date != null ? LocalDate.parse(date, fmt) : LocalDate.now();
    LocalDate to = from.plusMonths(6);

    if (rule != null) {
        r = new RepetitionRule(rule);
        List<DateTime> dates = r.occurrencesBetween(from.toDateTimeAtStartOfDay(), to.toDateTimeAtStartOfDay(),
                from.toDateTimeAtStartOfDay());
        Set<Date> hdates = new HashSet<>();
        for (DateTime d : dates)
            hdates.add(d.toDate());

        List<CalendarCellDecorator> decorators = new ArrayList<>();

        DateValue v = r.iCalRule().getUntil();
        Date start = date != null ? from.toDate() : null;
        Date end = v != null ? new LocalDate(v.year(), v.month(), v.day()).toDate() : null;

        decorators.add(new HighlightDecorator(new ArrayList<>(hdates), start, end, color));
        calendar.setDecorators(decorators);
    } else if (activeDays > 0 && restDays > 0) {

        List<Date> hdates = new ArrayList<>();

        LocalDate d = from.plusDays(0); // copy

        while (d.isBefore(to)) {
            if (ScheduleHelper.cycleEnabledForDate(d, from, activeDays, restDays)) {
                hdates.add(d.toDate());
            }
            d = d.plusDays(1);
        }

        List<CalendarCellDecorator> decorators = new ArrayList<>();
        //DateValue v = r.iCalRule().getUntil();
        //Date start = date != null ? from.toDate() : null;
        //Date end = v != null ? new LocalDate(v.year(), v.month(), v.day()).toDate() : null;
        decorators.add(new HighlightDecorator(hdates, from.toDate(), to.toDate(), color));
        calendar.setDecorators(decorators);
    }

    calendar.init(from.toDate(), to.toDate())
            .setShortWeekdays(getResources().getStringArray(R.array.calendar_weekday_names));
}

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

License:Open Source License

public Pair<LocalDate, List<PickupInfo>> getBestDay() {

    if (this.bestDay != null) {
        return this.bestDay;
    }/*from   ww w .j  ava2 s  .  co  m*/

    HashMap<LocalDate, List<PickupInfo>> bestDays = new HashMap<>();
    if (pickups.size() > 0) {
        LocalDate today = LocalDate.now();
        LocalDate first = LocalDate.now();
        LocalDate now = LocalDate.now().minusDays(MAX_DAYS);

        if (now.getDayOfWeek() == DateTimeConstants.SUNDAY) {
            now = now.plusDays(1);
        }

        // get the date of the first med we can take from 10 days ago
        for (PickupInfo p : pickups) {
            if (p.from().isAfter(now) && !p.taken()) {
                first = p.from();
                break;
            }
        }

        for (int i = 0; i < 10; i++) {
            LocalDate d = first.plusDays(i);
            if (!d.isAfter(today) && d.getDayOfWeek() != DateTimeConstants.SUNDAY) {
                // only take care of days after today that are not sundays
                continue;
            }

            // compute the number of meds we cant take for each day
            for (PickupInfo p : pickups) {
                // get the pickup take secure interval
                DateTime iStart = p.from().toDateTimeAtStartOfDay();
                DateTime iEnd = p.from().plusDays(MAX_DAYS - 1).toDateTimeAtStartOfDay();
                Interval interval = new Interval(iStart, iEnd);
                // add the pickup to the daily list if we can take it
                if (!p.taken() && interval.contains(d.toDateTimeAtStartOfDay())) {
                    if (!bestDays.containsKey(d)) {
                        bestDays.put(d, new ArrayList<PickupInfo>());
                    }
                    bestDays.get(d).add(p);
                }
            }
        }

        // select the day with the highest number of meds
        int bestDayCount = 0;
        LocalDate bestOption = null;
        Set<LocalDate> localDates = bestDays.keySet();
        ArrayList<LocalDate> sorted = new ArrayList<>(localDates);
        Collections.sort(sorted);
        for (LocalDate day : sorted) {
            List<PickupInfo> pks = bestDays.get(day);
            Log.d("PickupUtils", day.toString("dd/MM/YYYY") + ": " + pks.size());
            if (pks.size() >= bestDayCount) {
                bestDayCount = pks.size();
                bestOption = day;
                if (bestOption.getDayOfWeek() == DateTimeConstants.SUNDAY) {
                    bestOption = bestOption.minusDays(1);
                }
            }
        }
        if (bestOption != null) {
            this.bestDay = new Pair<>(bestOption, bestDays.get(bestOption));
            return this.bestDay;
        }
    }

    return null;
}

From source file:eu.ggnet.dwoss.uniqueunit.op.UniqueUnitReporterOperation.java

License:Open Source License

@Override
public FileJacket quality(Date start, Date end, TradeName contractor) {

    SubMonitor m = monitorFactory.newSubMonitor("Gertequalittsreport", 10);
    m.start();//from  w w  w . j  av  a  2 s. c  om
    m.message("Loading reciepted Units");

    LocalDate current = new LocalDate(start.getTime());
    LocalDate endDate = new LocalDate(end.getTime());

    List<UniqueUnit> units = new UniqueUnitEao(em).findBetweenInputDatesAndContractor(start, end, contractor);
    m.worked(5, "Sorting Data");

    Set<String> months = new HashSet<>();

    //prepare set of months
    while (current.isBefore(endDate)) {
        months.add(current.toString(MONTH_PATTERN));
        current = current.plusDays(1);
    }

    //prepare Map sorted by months that contains a map sorted by condition
    SortedMap<String, UnitQualityContainer> unitMap = new TreeMap<>();
    for (String month : months) {
        unitMap.put(month, new UnitQualityContainer());
    }
    m.worked(1);

    //count monthly receipted units sorted by condition
    for (UniqueUnit uniqueUnit : units) {
        current = new LocalDate(uniqueUnit.getInputDate().getTime());
        switch (uniqueUnit.getCondition()) {
        case AS_NEW:
            unitMap.get(current.toString(MONTH_PATTERN)).incrementAsNew();
            break;
        case ALMOST_NEW:
            unitMap.get(current.toString(MONTH_PATTERN)).incrementAlmostNew();
            break;
        case USED:
            unitMap.get(current.toString(MONTH_PATTERN)).incrementUsed();
            break;
        }
    }
    m.worked(2, "Creating Document");

    List<Object[]> rows = new ArrayList<>();
    for (String month : unitMap.keySet()) {
        rows.add(new Object[] { month, unitMap.get(month).getAsNew(), unitMap.get(month).getAlmostNew(),
                unitMap.get(month).getUsed() });
        m.worked(5);
    }

    STable table = new STable();
    table.setTableFormat(new CFormat(BLACK, WHITE, new CBorder(BLACK)));
    table.setHeadlineFormat(
            new CFormat(CFormat.FontStyle.BOLD, Color.BLACK, Color.YELLOW, CFormat.HorizontalAlignment.LEFT,
                    CFormat.VerticalAlignment.BOTTOM, CFormat.Representation.DEFAULT));
    table.add(new STableColumn("Monat", 15)).add(new STableColumn("neuwertig", 15))
            .add(new STableColumn("nahezu neuwerig", 15)).add(new STableColumn("gebraucht", 15));
    table.setModel(new STableModelList(rows));

    CCalcDocument cdoc = new TempCalcDocument("Qualitaet_");
    cdoc.add(new CSheet("Sheet1", table));

    File file = LucidCalc.createWriter(LucidCalc.Backend.XLS).write(cdoc);
    m.finish();
    return new FileJacket("Aufnahme_nach_Qualitt_" + contractor + "_" + DateFormats.ISO.format(start) + "_"
            + DateFormats.ISO.format(end), ".xls", file);
}

From source file:facades.WatchFacade.java

public SamaritOccupied getWatchesForDateUser(String date, String userName) {
    EntityManager em = EntityConnector.getEntityManager();
    SamaritOccupied watch = null;//from w w  w  .j a  v  a  2 s  .  com
    List<SamaritOccupied> watches;
    LocalDate dstart = dtf.parseLocalDate(date);
    LocalDate dstart1 = dstart.plusDays(1);

    Date d1 = dstart.toDate();
    Date d2 = dstart1.toDate();

    try {
        Query q = em.createQuery(
                "SELECT w FROM SamaritOccupied AS w WHERE w.samarit.userName = ?1 AND w.start >= ?2 AND w.start < ?3"); // AND w.start = :date

        q.setParameter(1, userName);
        q.setParameter(2, d1);
        q.setParameter(3, d2);
        watches = q.getResultList();

        for (SamaritOccupied watche : watches) {

            if (watche.isAllDay()) {
                deleteWatch(watche.getId());
                watch = watche;
            }
        }
    } catch (Exception e) {
        log.Log.writeErrorMessageToLog("Error in getwatches for User: " + e.getMessage());
        throw e;
    } finally {
        em.close();
    }
    return watch;
}