Example usage for java.time LocalDate minusDays

List of usage examples for java.time LocalDate minusDays

Introduction

In this page you can find the example usage for java.time LocalDate minusDays.

Prototype

public LocalDate minusDays(long daysToSubtract) 

Source Link

Document

Returns a copy of this LocalDate with the specified number of days subtracted.

Usage

From source file:org.silverpeas.core.calendar.CalendarEventOccurrence.java

/**
 * Gets optionally an event occurrence by its identifier.
 * <p>If the occurrence exists into the persistence, it is returned. Otherwise it is generated.
 * <p>Otherwise and if start date is valid, the occurrence is generated.
 * @param id the identifier of the aimed occurrence.
 * @return an optional calendar event occurrence.
 *//*from   ww w  .j  ava 2s  .  c om*/
public static Optional<CalendarEventOccurrence> getById(final String id) {
    final CalendarEventOccurrenceRepository repository = CalendarEventOccurrenceRepository.get();
    final Mutable<CalendarEventOccurrence> occurrence = Mutable.ofNullable(repository.getById(id));
    if (!occurrence.isPresent()) {
        final Pair<String, Temporal> explodedId = explodeId(id);
        final String eventId = explodedId.getLeft();
        final Temporal startDate = explodedId.getRight();
        final Optional<CalendarEvent> event = Optional.ofNullable(CalendarEvent.getById(eventId));
        event.ifPresent(e -> {
            if (e.isRecurrent()) {
                final LocalDate occStartDate;
                final LocalDate occEndDate;
                if (startDate instanceof LocalDate) {
                    final LocalDate date = (LocalDate) startDate;
                    occStartDate = date.minusDays(1);
                    occEndDate = date.plusDays(1);
                } else {
                    final OffsetDateTime dateTime = (OffsetDateTime) startDate;
                    occStartDate = dateTime.minusDays(1).toLocalDate();
                    occEndDate = dateTime.plusDays(1).toLocalDate();
                }
                final List<CalendarEventOccurrence> occurrences = e.getCalendar()
                        .between(occStartDate, occEndDate).getEventOccurrences();
                occurrences.removeIf(o -> !o.getCalendarEvent().getId().equals(eventId)
                        || (!o.getStartDate().equals(startDate)));
                if (occurrences.size() == 1) {
                    occurrence.set(occurrences.get(0));
                }
            } else {
                occurrence.set(new CalendarEventOccurrence(e, e.getStartDate(), e.getEndDate()));
            }
        });
    }
    return Optional.ofNullable(occurrence.orElse(null));
}

From source file:serposcope.controllers.google.GoogleSearchController.java

public Result search(Context context, @PathParam("searchId") Integer searchId,
        @Param("startDate") String startDateStr, @Param("endDate") String endDateStr) {
    GoogleSearch search = getSearch(context, searchId);
    Group group = context.getAttribute("group", Group.class);

    if (search == null) {
        context.getFlashScope().error("error.invalidSearch");
        return Results.redirect(
                router.getReverseRoute(GoogleGroupController.class, "view", "groupId", group.getId()));
    }//from w  ww  . ja v a 2s  .c  o m

    Run minRun = baseDB.run.findFirst(Module.GOOGLE, STATUSES_DONE, null);
    Run maxRun = baseDB.run.findLast(Module.GOOGLE, STATUSES_DONE, null);
    if (maxRun == null || minRun == null) {
        return Results.ok().render("search", search);
    }

    LocalDate minDay = minRun.getDay();
    LocalDate maxDay = maxRun.getDay();

    LocalDate startDate = null;
    if (startDateStr != null) {
        try {
            startDate = LocalDate.parse(startDateStr);
        } catch (Exception ex) {
        }
    }
    LocalDate endDate = null;
    if (endDateStr != null) {
        try {
            endDate = LocalDate.parse(endDateStr);
        } catch (Exception ex) {
        }
    }

    if (startDate == null || endDate == null || endDate.isBefore(startDate)) {
        startDate = maxDay.minusDays(30);
        endDate = maxDay;
    }

    Run firstRun = baseDB.run.findFirst(Module.GOOGLE, STATUSES_DONE, startDate);
    Run lastRun = baseDB.run.findLast(Module.GOOGLE, STATUSES_DONE, endDate);

    if (firstRun == null || lastRun == null || firstRun.getDay().isAfter(lastRun.getDay())) {
        return Results.ok()
                .render("f_warning", msg.get("error.noDataForThisPeriod", context, Optional.absent()).or(""))
                .render("startDate", startDate).render("endDate", endDate).render("minDate", minDay)
                .render("maxDate", maxDay).render("search", search);
    }

    startDate = firstRun.getDay();
    endDate = lastRun.getDay();

    String jsonEvents = null;
    try {
        jsonEvents = objectMapper.writeValueAsString(baseDB.event.list(group, startDate, endDate));
    } catch (JsonProcessingException ex) {
        jsonEvents = "[]";
    }

    GoogleSerp lastSerp = googleDB.serp.get(lastRun.getId(), search.getId());

    List<GoogleTarget> targets = getTargets(context);

    Map<Integer, GoogleBest> bestRankings = new HashMap<>();
    for (GoogleTarget target : targets) {
        GoogleBest best = googleDB.rank.getBest(target.getGroupId(), target.getId(), search.getId());
        if (best != null) {
            bestRankings.put(best.getGoogleTargetId(), best);
        }
    }

    String jsonRanks = getJsonRanks(group, targets, firstRun, lastRun, searchId);
    Config config = baseDB.config.getConfig();

    return Results.ok().render("displayMode", config.getDisplayGoogleSearch()).render("events", jsonEvents)
            .render("targets", targets).render("chart", jsonRanks).render("search", search)
            .render("serp", lastSerp).render("startDate", startDate).render("endDate", endDate)
            .render("minDate", minDay).render("maxDate", maxDay).render("bestRankings", bestRankings);
}

From source file:serposcope.controllers.google.GoogleTargetController.java

public Result target(Context context, @PathParam("targetId") Integer targetId,
        @Param("startDate") String startDateStr, @Param("endDate") String endDateStr) {
    GoogleTarget target = getTarget(context, targetId);
    List<GoogleSearch> searches = context.getAttribute("searches", List.class);
    Group group = context.getAttribute("group", Group.class);
    Config config = baseDB.config.getConfig();

    String display = context.getParameter("display", config.getDisplayGoogleTarget());
    if (!Config.VALID_DISPLAY_GOOGLE_TARGET.contains(display) && !"export".equals(display)) {
        display = Config.DEFAULT_DISPLAY_GOOGLE_TARGET;
    }//from w w w .  j  av  a 2  s.  c  om

    if (target == null) {
        context.getFlashScope().error("error.invalidTarget");
        return Results.redirect(
                router.getReverseRoute(GoogleGroupController.class, "view", "groupId", group.getId()));
    }

    Run minRun = baseDB.run.findFirst(group.getModule(), RunDB.STATUSES_DONE, null);
    Run maxRun = baseDB.run.findLast(group.getModule(), RunDB.STATUSES_DONE, null);

    if (maxRun == null || minRun == null || searches.isEmpty()) {
        String fallbackDisplay = "export".equals(display) ? "table" : display;
        return Results.ok()
                .template("/serposcope/views/google/GoogleTargetController/" + fallbackDisplay + ".ftl.html")
                .render("startDate", "").render("endDate", "").render("display", fallbackDisplay)
                .render("target", target);
    }

    LocalDate minDay = minRun.getDay();
    LocalDate maxDay = maxRun.getDay();

    LocalDate startDate = null;
    if (startDateStr != null) {
        try {
            startDate = LocalDate.parse(startDateStr);
        } catch (Exception ex) {
        }
    }
    LocalDate endDate = null;
    if (endDateStr != null) {
        try {
            endDate = LocalDate.parse(endDateStr);
        } catch (Exception ex) {
        }
    }

    if (startDate == null || endDate == null || endDate.isBefore(startDate)) {
        startDate = maxDay.minusDays(30);
        endDate = maxDay;
    }

    Run firstRun = baseDB.run.findFirst(group.getModule(), RunDB.STATUSES_DONE, startDate);
    Run lastRun = baseDB.run.findLast(group.getModule(), RunDB.STATUSES_DONE, endDate);

    List<Run> runs = baseDB.run.listDone(firstRun.getId(), lastRun.getId());

    startDate = firstRun.getDay();
    endDate = lastRun.getDay();

    switch (display) {
    case "table":
    case "variation":
        return Results.ok().template("/serposcope/views/google/GoogleTargetController/" + display + ".ftl.html")
                .render("target", target).render("searches", searches).render("startDate", startDate.toString())
                .render("endDate", endDate.toString()).render("minDate", minDay).render("maxDate", maxDay)
                .render("display", display);
    case "chart":
        return renderChart(group, target, searches, runs, minDay, maxDay, startDate, endDate);
    case "export":
        return renderExport(group, target, searches, runs, minDay, maxDay, startDate, endDate);
    default:
        throw new IllegalStateException();
    }

}

From source file:tech.tablesaw.filters.TimeDependentFilteringTest.java

public static void main(String[] args) throws Exception {

    int numberOfRecordsInTable = 100_000_000;
    Stopwatch stopwatch = Stopwatch.createStarted();

    Table t = defineSchema();/*from   w w w  .  j  a  v  a2 s  . c o  m*/
    generateTestData(t, numberOfRecordsInTable, stopwatch);

    t.setName("Observations");

    // non temporal constraints
    String conceptA = t.stringColumn("concept").get(RandomUtils.nextInt(0, t.rowCount()));
    String conceptB = t.stringColumn("concept").get(RandomUtils.nextInt(0, t.rowCount()));

    // independent temporal constraints
    String conceptZ = t.stringColumn("concept").get(RandomUtils.nextInt(0, t.rowCount()));
    String conceptD = t.stringColumn("concept").get(RandomUtils.nextInt(0, t.rowCount()));
    DependencyFilter independentConstraintFilter = DependencyFilter.FIRST;

    // temporal dependency range constraint
    Range<Integer> daysConstraint = Range.closed(0, 0);

    StringColumn concept = t.stringColumn("concept");

    //Non-temporal clause
    Table nt = t.where(concept.isEqualTo(conceptA).and(concept.isNotEqualTo(conceptB)));

    DoubleColumn ntPatients = nt.doubleColumn("patient");

    // Group the original table by patient id
    TableSliceGroup patients = StandardTableSliceGroup.create(t, "patient");

    // Create a list of patient sub-tables to work with TODO(lwhite): Build the copy-on-write to ViewGroups to avoid
    CopyOnWriteArrayList<TableSlice> patientTables = new CopyOnWriteArrayList<>(patients.getSlices());

    // Apply the independent temporal event filtering to the patient subtables and remove any that don't pass
    for (TableSlice patientTable : patients) {
        StringColumn concepts = patientTable.stringColumn("concept");
        double patientId = Double.parseDouble(patientTable.name());
        if (!concepts.contains(conceptZ) || concepts.contains(conceptD)) {
            patientTables.remove(patientTable);
        } else if (!ntPatients.contains(patientId)) { // filtering out the non-temporal now constraints for
            // efficiency
            patientTables.remove(patientTable);
        }
    }

    List<IndependentResult> independentResults = new ArrayList<>();

    // Working with the filtered patient tables, calculate the event dates for the independent events
    for (TableSlice patientTable : patientTables) {
        IndependentResult result = new IndependentResult();
        List<LocalDate> eventDates = new ArrayList<>();

        // iterate an individual table and find the rows where concept matches the target concept
        for (int row : patientTable) {
            StringColumn concepts = patientTable.stringColumn("concept");
            DateColumn dates = patientTable.dateColumn("date");
            if (concepts.get(row).equals(conceptZ)) {
                eventDates.add(dates.get(row));
            }
        }

        if (independentConstraintFilter == DependencyFilter.FIRST) {
            if (eventDates.isEmpty()) {
                // this is an error
                fail("There are no event dates");
            } else { //Get the first event for the current patient and createFromCsv a date range around it
                LocalDate date = eventDates.get(0);
                result.addRange(Range.closed(date.minusDays(daysConstraint.lowerEndpoint()),
                        date.plusDays(daysConstraint.upperEndpoint())));
            } //TODO handle last and any cases
        }
        independentResults.add(result);
    }
}