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.lastpass.saml.SAMLClient.java

License:Apache License

private void validate(Response response) throws ValidationException {
    // response signature must match IdP's key, if present
    Signature sig = response.getSignature();
    if (sig != null)
        sigValidator.validate(sig);//from  w w w. j a v a2s . c o m

    // response must be successful
    if (response.getStatus() == null || response.getStatus().getStatusCode() == null
            || !(StatusCode.SUCCESS_URI.equals(response.getStatus().getStatusCode().getValue()))) {
        throw new ValidationException("Response has an unsuccessful status code");
    }

    // response destination must match ACS
    if (!spConfig.getAcs().equals(response.getDestination()))
        throw new ValidationException("Response is destined for a different endpoint");

    DateTime now = DateTime.now();

    // issue instant must be within a day
    DateTime issueInstant = response.getIssueInstant();

    if (issueInstant != null) {
        if (issueInstant.isBefore(now.minusDays(1).minusSeconds(slack)))
            throw new ValidationException("Response IssueInstant is in the past");

        if (issueInstant.isAfter(now.plusDays(1).plusSeconds(slack)))
            throw new ValidationException("Response IssueInstant is in the future");
    }

    List<Assertion> assertions;
    try {
        assertions = parseAllAssertions(response);
    } catch (SAMLException ex) {
        throw new ValidationException("no assertions found.");
    }

    for (Assertion assertion : assertions) {
        // Assertion must be signed correctly
        if (!assertion.isSigned())
            throw new ValidationException("Assertion must be signed");

        sig = assertion.getSignature();
        sigValidator.validate(sig);

        // Assertion must contain an authnstatement
        // with an unexpired session
        if (assertion.getAuthnStatements().isEmpty()) {
            throw new ValidationException("Assertion should contain an AuthnStatement");
        }
        for (AuthnStatement as : assertion.getAuthnStatements()) {
            DateTime sessionTime = as.getSessionNotOnOrAfter();
            if (sessionTime != null) {
                DateTime exp = sessionTime.plusSeconds(slack);
                if (exp != null && (now.isEqual(exp) || now.isAfter(exp)))
                    throw new ValidationException("AuthnStatement has expired");
            }
        }

        if (assertion.getConditions() == null) {
            throw new ValidationException("Assertion should contain conditions");
        }

        // Assertion IssueInstant must be within a day
        DateTime instant = assertion.getIssueInstant();
        if (instant != null) {
            if (instant.isBefore(now.minusDays(1).minusSeconds(slack)))
                throw new ValidationException("Response IssueInstant is in the past");

            if (instant.isAfter(now.plusDays(1).plusSeconds(slack)))
                throw new ValidationException("Response IssueInstant is in the future");
        }

        // Conditions must be met by current time
        Conditions conditions = assertion.getConditions();
        DateTime notBefore = conditions.getNotBefore();
        DateTime notOnOrAfter = conditions.getNotOnOrAfter();

        if (notBefore == null || notOnOrAfter == null)
            throw new ValidationException("Assertion conditions must have limits");

        notBefore = notBefore.minusSeconds(slack);
        notOnOrAfter = notOnOrAfter.plusSeconds(slack);

        if (now.isBefore(notBefore))
            throw new ValidationException("Assertion conditions is in the future");

        if (now.isEqual(notOnOrAfter) || now.isAfter(notOnOrAfter))
            throw new ValidationException("Assertion conditions is in the past");

        // If subjectConfirmationData is included, it must
        // have a recipient that matches ACS, with a valid
        // NotOnOrAfter
        Subject subject = assertion.getSubject();
        if (subject != null && !subject.getSubjectConfirmations().isEmpty()) {
            boolean foundRecipient = false;
            for (SubjectConfirmation sc : subject.getSubjectConfirmations()) {
                if (sc.getSubjectConfirmationData() == null)
                    continue;

                SubjectConfirmationData scd = sc.getSubjectConfirmationData();
                if (scd.getNotOnOrAfter() != null) {
                    DateTime chkdate = scd.getNotOnOrAfter().plusSeconds(slack);
                    if (now.isEqual(chkdate) || now.isAfter(chkdate)) {
                        throw new ValidationException("SubjectConfirmationData is in the past");
                    }
                }

                if (spConfig.getAcs().equals(scd.getRecipient()))
                    foundRecipient = true;
            }

            if (!foundRecipient)
                throw new ValidationException("No SubjectConfirmationData found for ACS");
        }

        // audience must include intended SP issuer
        if (conditions.getAudienceRestrictions().isEmpty())
            throw new ValidationException("Assertion conditions must have audience restrictions");

        // only one audience restriction supported: we can only
        // check against the single SP.
        if (conditions.getAudienceRestrictions().size() > 1)
            throw new ValidationException("Assertion contains multiple audience restrictions");

        AudienceRestriction ar = conditions.getAudienceRestrictions().get(0);

        // at least one of the audiences must match our SP
        boolean foundSP = false;
        for (Audience a : ar.getAudiences()) {
            if (spConfig.getEntityId().equals(a.getAudienceURI()))
                foundSP = true;
        }
        if (!foundSP)
            throw new ValidationException("Assertion audience does not include issuer");
    }
}

From source file:com.linagora.obm.ui.scenario.event.EventStepdefs.java

License:Open Source License

@And("^event \"([^\"]*)\" appears every day, first is (\\d+)/(\\d+)/(\\d+) from (\\d+):(\\d+) to (\\d+):(\\d+)$")
public void eventAppearsEveryDay(String title, int day, int month, int year, int beginHour, int beginMin,
        int endHour, int endMin) {

    DateTime dateTime = dateTime(day, month, year, beginHour, beginMin);
    String expectedEventDatesTitle = expectedEventDatesTitle(beginHour, beginMin, endHour, endMin);

    List<WebElement> divElements = sortedEvents(title);
    assertThat(divElements).isNotEmpty();
    for (WebElement divElement : divElements) {
        assertThat(divElement.getAttribute("id")).endsWith(String.valueOf(dateTime.getMillis() / 1000));

        WebElement hrefElement = divElement.findElement(new ByCssSelector("a"));
        assertThat(hrefElement.getText()).isEqualTo(expectedEventDatesTitle);

        dateTime = dateTime.plusDays(1);
    }//from w  w  w.j  a va2 s.c om
}

From source file:com.linkedin.cubert.analyzer.physical.AggregateRewriter.java

License:Open Source License

private void calculateIncrementalFactLoadDates() throws AggregateRewriteException {
    if (!this.mvExists)
        return;//  w  w w  .j  a v a 2 s  .c om

    DateTime dt = null;
    /*
     * difference between factStartDate and mvHorizonDate determines #of bit shifts.
     * the new horizon date is always determined by the factStartDate.
     */
    if (this.factStartDate > mvHorizonDate)
        throw new AggregateRewriteException(String.format(
                "Fact start date(%d) in the future of mv horizon date(%d) ", factStartDate, mvHorizonDate));

    dt = DateTimeUtilities.getDateTime(Integer.toString(mvRefreshDate));
    incLoadDate = dt.plusDays(1);

    // Handle over-ride case.
    if (mvRefreshDateOverride != -1) {
        // if over-ridden time is before the physical MV refresh time
        if (mvRefreshDateOverride != 0 && mvRefreshDateOverride < mvRefreshDate)
            incLoadDate = DateTimeUtilities.getDateTime(Integer.toString(mvRefreshDateOverride)).plusDays(1);

        /*
         * mvRefreshDateOverride of 0 is treated as a hint to turn off
         * incrementalization.
         */
        else if (mvRefreshDateOverride == 0)
            incLoadDate = null;
    }

    if (mvRefreshDate != 0 && incLoadDate != null) {
        if (!(DateTimeUtilities.getDateTime(factStartDate).isBefore(incLoadDate)
                && DateTimeUtilities.getDateTime(factEndDate).isAfter(incLoadDate)))
            throw new AggregateRewriteException(
                    String.format("MV date range mis-matches load range[%s, %s] mvRefreshDate=%s ",
                            factStartDate, factEndDate, mvRefreshDate));
    }

}

From source file:com.lostrealm.lembretes.DownloadJob.java

License:Open Source License

static void scheduleExact() {
    DateTime time = DateTime.now();

    if (time.getHourOfDay() > 20)
        time.plusDays(1);

    if (time.getDayOfWeek() == DateTimeConstants.SATURDAY)
        time.plusDays(2);//from w  ww  .  j ava 2  s.  c  om
    else if (time.getDayOfWeek() == DateTimeConstants.SUNDAY)
        time.plusDays(1);

    scheduleExact(time.toString("yyyy-MM?dd"));
}

From source file:com.marand.thinkmed.medications.administration.impl.AdministrationTaskCreatorImpl.java

License:Open Source License

private List<NewTaskRequestDto> createTasksForVariableDaysTherapy(final String patientId,
        final VariableSimpleTherapyDto therapy, final Interval taskCreationInterval,
        final AdministrationTaskCreateActionEnum action) {
    final Map<DateTime, TherapyDoseDto> timesWithDosesMap = new HashMap<>();

    for (final TimedSimpleDoseElementDto timedDoseElement : therapy.getTimedDoseElements()) {
        getTimedDoseForVariableDaysTherapy(therapy, taskCreationInterval, action, timedDoseElement,
                timedDoseElement.getDate()).forEach(e -> timesWithDosesMap.put(e.getFirst(), e.getSecond()));
    }// w ww .  jav  a2 s  .  c  o  m

    final DateTime lastAdministrationDateTime = timesWithDosesMap.entrySet().stream().map(Map.Entry::getKey)
            .max(Comparator.naturalOrder()).orElse(null);

    final boolean therapyContinuesAfterLastDefinedDose = lastAdministrationDateTime != null
            && lastAdministrationDateTime.isBefore(taskCreationInterval.getEnd());
    if (therapyContinuesAfterLastDefinedDose) {
        //repeat last day
        final DateTime lastDayStart = lastAdministrationDateTime.withTimeAtStartOfDay();
        final List<TimedSimpleDoseElementDto> lastDayDoses = therapy.getTimedDoseElements().stream()
                .filter(t -> t.getDate().withTimeAtStartOfDay().equals(lastDayStart))
                .collect(Collectors.toList());

        DateTime nextDay = lastDayStart.plusDays(1);
        while (taskCreationInterval.contains(nextDay)) {
            for (final TimedSimpleDoseElementDto timedDoseElement : lastDayDoses) {
                getTimedDoseForVariableDaysTherapy(therapy, taskCreationInterval, action, timedDoseElement,
                        nextDay).forEach(e -> timesWithDosesMap.put(e.getFirst(), e.getSecond()));
            }
            nextDay = nextDay.plusDays(1);
        }
    }

    return timesWithDosesMap.keySet().stream().sorted(Comparator.naturalOrder())
            .filter(administrationTime -> !administrationTime.isAfter(taskCreationInterval.getEnd()))
            .map(administrationTime -> createMedicationTaskRequest(patientId, therapy,
                    AdministrationTypeEnum.START, administrationTime,
                    timesWithDosesMap.get(administrationTime)))
            .collect(Collectors.toList());
}

From source file:com.marand.thinkmed.medications.administration.impl.AdministrationTaskCreatorImpl.java

License:Open Source License

List<Interval> calculateAdministrationTasksInterval(final TherapyDto therapy, final DateTime actionTimestamp,
        final AdministrationTaskCreateActionEnum action, final int daysFromAction,
        final DateTime lastTaskTimestamp) {
    final DateTime start;
    if (action == AdministrationTaskCreateActionEnum.AUTO_CREATE) {
        if (lastTaskTimestamp != null) {
            start = lastTaskTimestamp;/*www  .  ja  va  2 s . c o m*/
        } else if (actionTimestamp.isAfter(therapy.getStart())) {
            start = actionTimestamp;
        } else {
            start = therapy.getStart();
        }
    } else {
        start = action.isCreateTasksFromTherapyStart() && therapy.getStart() != null ? therapy.getStart()
                : actionTimestamp;
    }

    DateTime end;
    //noinspection IfMayBeConditional
    if (action == AdministrationTaskCreateActionEnum.PREVIEW_TIMES_ON_NEW_PRESCRIPTION) {
        end = start.plusDays(daysFromAction);
    } else {
        end = actionTimestamp.plusDays(daysFromAction + 1).withTimeAtStartOfDay();
    }

    final boolean isPresetTimeAction = EnumSet
            .of(AdministrationTaskCreateActionEnum.PRESET_TIME_ON_NEW_PRESCRIPTION,
                    AdministrationTaskCreateActionEnum.PRESET_TIME_ON_MODIFY)
            .contains(action);
    final DateTime therapyEndTime = therapy.getEnd();
    if (!isPresetTimeAction && therapyEndTime != null && therapyEndTime.isBefore(end)) {
        end = therapyEndTime;
    }

    return removeInactiveTherapyDaysFromTasksInterval(therapy, start, end);
}

From source file:com.marand.thinkmed.medications.administration.impl.AdministrationTaskCreatorImpl.java

License:Open Source License

private List<Interval> removeInactiveTherapyDaysFromTasksInterval(final TherapyDto therapy,
        final DateTime start, final DateTime end) {
    final DateTime therapyStart = therapy.getStart();
    final Integer daysFrequency = therapy.getDosingDaysFrequency();

    final List<Interval> intervals = new ArrayList<>();

    DateTime intervalStart = new DateTime(start);
    DateTime intervalEnd = intervalStart.withTimeAtStartOfDay().plusDays(1);

    final DateTime firstDayStart = intervalStart.withTimeAtStartOfDay();

    boolean validDayOfWeek = isInValidDaysOfWeek(intervalStart, therapy.getDaysOfWeek());
    boolean validFrequency = isInValidDaysFrequency(intervalStart, therapyStart, daysFrequency);
    boolean previousDayWasValid = validDayOfWeek && validFrequency;
    if (!previousDayWasValid) {
        intervalStart = firstDayStart.plusDays(1);
    }/*from  w w w.  j a  va 2 s  .  co m*/
    boolean validInFutureDays = false;
    while (intervalEnd.isBefore(end) || intervalEnd.equals(end)) {
        validDayOfWeek = isInValidDaysOfWeek(intervalEnd, therapy.getDaysOfWeek());
        validFrequency = isInValidDaysFrequency(intervalEnd, therapyStart, daysFrequency);
        if (validDayOfWeek && validFrequency) {
            previousDayWasValid = true;
        } else {
            if (previousDayWasValid) {
                intervals.add(new Interval(intervalStart, intervalEnd));
            }
            previousDayWasValid = false;
            intervalStart = intervalEnd.plusDays(1);
        }
        intervalEnd = intervalEnd.plusDays(1);
        validInFutureDays = true;
    }
    if (previousDayWasValid && validInFutureDays || intervalEnd.minusDays(1).isBefore(end)) {
        if (!intervalStart.isAfter(end)) {
            intervals.add(new Interval(intervalStart, end));
        }
    }
    return intervals;
}

From source file:com.marand.thinkmed.medications.administration.impl.AdministrationTaskCreatorImpl.java

License:Open Source License

private Pair<DateTime, TherapyDoseDto> getNextAdministrationTimeWithDoseFromPattern(final DateTime fromTime,
        final Map<HourMinuteDto, TherapyDoseDto> administrationTimesWithDoses, final boolean fromTimeIncluded) {
    final List<HourMinuteDto> times = administrationTimesWithDoses.keySet().stream()
            .sorted(Comparator.naturalOrder()).collect(Collectors.toList());

    int index = 0;
    DateTime foundTime = times.get(index).combine(fromTime);
    TherapyDoseDto therapyDoseDto = administrationTimesWithDoses.get(times.get(0));

    while (foundTime.isBefore(fromTime) || (foundTime.equals(fromTime) && !fromTimeIncluded)) {
        index++;/*from www.  j  a v  a2s  . c  om*/
        if (index >= administrationTimesWithDoses.size()) {
            index = 0;
            foundTime = foundTime.plusDays(1);
        }
        final HourMinuteDto hourMinute = times.get(index);
        foundTime = hourMinute.combine(foundTime);
        therapyDoseDto = administrationTimesWithDoses.get(hourMinute);
    }
    return Pair.of(foundTime, therapyDoseDto);
}

From source file:com.marand.thinkmed.medications.administration.impl.AdministrationTaskCreatorImpl.java

License:Open Source License

private Pair<DateTime, TherapyDoseDto> getNextAdministrationTimeWithDoseForFrequencyBetweenDoses(
        final AdministrationTaskCreateActionEnum action, final DateTime therapyStart, final DateTime fromTime,
        final HourMinuteDto administrationTime, final TherapyDoseDto dose, final int hoursBetweenDoses,
        final boolean fromTimeIncluded) {
    DateTime foundTime;
    if (action == AdministrationTaskCreateActionEnum.PRESET_TIME_ON_NEW_PRESCRIPTION) {
        foundTime = fromTime.withTimeAtStartOfDay().plusHours(administrationTime.getHour())
                .plusMinutes(administrationTime.getMinute());
        if (hoursBetweenDoses >= 24) {
            while (foundTime.isBefore(fromTime) || (foundTime.equals(fromTime) && !fromTimeIncluded)) {
                foundTime = foundTime.plusDays(1);
            }//from   w  w w.  j  av a 2s  .c  om
            return Pair.of(foundTime, dose);
        }
    } else {
        foundTime = therapyStart;
    }
    while (foundTime.isBefore(fromTime) || (foundTime.equals(fromTime) && !fromTimeIncluded)) {
        foundTime = foundTime.plusHours(hoursBetweenDoses);
    }
    return Pair.of(foundTime, dose);
}

From source file:com.marand.thinkmed.medications.administration.impl.AdministrationTaskCreatorImpl.java

License:Open Source License

private Pair<DateTime, TherapyDoseDto> getPreviousAdministrationTimeWithDose(final DateTime fromTime,
        final Map<HourMinuteDto, TherapyDoseDto> administrationTimesWithDoses, final boolean fromTimeIncluded) {
    int index = administrationTimesWithDoses.size() - 1;
    final List<HourMinuteDto> times = new ArrayList<>(administrationTimesWithDoses.keySet());
    Collections.sort(times);/*from   www .  j  av  a2  s  .  co  m*/
    DateTime foundTime = times.get(index).combine(fromTime.plusDays(1));
    TherapyDoseDto therapyDoseDto = administrationTimesWithDoses.get(times.get(index));
    while (foundTime.isAfter(fromTime) || (foundTime.equals(fromTime) && !fromTimeIncluded)) {
        index--;
        if (index < 0) {
            index = administrationTimesWithDoses.size() - 1;
            foundTime = foundTime.minusDays(1);
        }
        final HourMinuteDto hourMinute = times.get(index);
        foundTime = hourMinute.combine(foundTime);
        therapyDoseDto = administrationTimesWithDoses.get(hourMinute);
    }
    return Pair.of(foundTime, therapyDoseDto);
}