Java Code Examples for org.joda.time.Duration#isLongerThan()

The following examples show how to use org.joda.time.Duration#isLongerThan() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InstantValidator.java    From verify-service-provider with MIT License 6 votes vote down vote up
public void validate(DateTime instant, String instantName) {
    Duration age = new Duration(instant, DateTime.now());
    if (age.isLongerThan(MAXIMUM_INSTANT_AGE)) {
        throw new SamlResponseValidationException(String.format("%s is too far in the past %s",
            instantName,
            PeriodFormat.getDefault().print(age.toPeriod()))
        );
    }

    if (dateTimeComparator.isAfterNow(instant)) {
        throw new SamlResponseValidationException(String.format("%s is in the future %s",
            instantName,
            instant.withZone(UTC).toString(dateHourMinuteSecond()))
        );
    }
}
 
Example 2
Source File: WatchTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Override
public PollResult<OutputT> apply(InputT element, Context c) throws Exception {
  Instant now = Instant.now();
  Duration elapsed = new Duration(baseTime, Instant.now());
  if (elapsed.isLongerThan(timeToFail)) {
    fail(
        String.format(
            "Poll called %s after base time, which is longer than the threshold of %s",
            elapsed, timeToFail));
  }

  double fractionElapsed = 1.0 * elapsed.getMillis() / timeToOutputEverything.getMillis();
  int numToEmit = (int) Math.min(outputs.size(), fractionElapsed * outputs.size());
  List<TimestampedValue<OutputT>> toEmit = Lists.newArrayList();
  for (int i = 0; i < numToEmit; ++i) {
    toEmit.add(TimestampedValue.of(outputs.get(i), now));
  }
  return elapsed.isLongerThan(timeToDeclareOutputFinal)
      ? PollResult.complete(toEmit)
      : PollResult.incomplete(toEmit).withWatermark(now);
}
 
Example 3
Source File: DataflowPipelineJob.java    From beam with Apache License 2.0 6 votes vote down vote up
/**
 * Reset backoff. If duration is limited, calculate time remaining, otherwise just reset retry
 * count.
 *
 * <p>If a total duration for all backoff has been set, update the new cumulative sleep time to be
 * the remaining total backoff duration, stopping if we have already exceeded the allotted time.
 */
private static BackOff resetBackoff(Duration duration, NanoClock nanoClock, long startNanos) {
  BackOff backoff;
  if (duration.isLongerThan(Duration.ZERO)) {
    long nanosConsumed = nanoClock.nanoTime() - startNanos;
    Duration consumed = Duration.millis((nanosConsumed + 999999) / 1000000);
    Duration remaining = duration.minus(consumed);
    if (remaining.isLongerThan(Duration.ZERO)) {
      backoff = getMessagesBackoff(remaining);
    } else {
      backoff = BackOff.STOP_BACKOFF;
    }
  } else {
    backoff = getMessagesBackoff(duration);
  }
  return backoff;
}
 
Example 4
Source File: PeriodicStaleCheckingCacheStrategy.java    From alchemy with MIT License 6 votes vote down vote up
private void invalidateAllIfStale(CachingContext context) {
    if (!lock.compareAndSet(false, true)) {
        return;
    }

    try {
        final Duration elapsed = new Duration(lastSync, DateTime.now());
        if (!elapsed.isLongerThan(period)) {
            return;
        }

        lastSync = DateTime.now();
    } finally {
        lock.set(false);
    }

    if (context.checkIfAnyStale()) {
        context.invalidateAll(true);
    }
}
 
Example 5
Source File: TranscriptionResultFormatter.java    From live-transcribe-speech-engine with Apache License 2.0 5 votes vote down vote up
private String obtainLineBreaksBetweenTwoResults(
    CachedResult previous, TranscriptionResult current) {
  boolean languageSwitched = !previous.result.getLanguageCode().equals(current.getLanguageCode());
  if (options.getNumExtendedSilenceLineBreaks() > 0) { // Previous element is not whitespace.
    Duration timestampDifference =
        new Duration(
            TimeUtil.toInstant(previous.result.getEndTimestamp()),
            TimeUtil.toInstant(current.getStartTimestamp()));
    if (timestampDifference.isLongerThan(extendedSilenceDurationForLineBreaks)) {
      // If language switch and silence both happened, return the longer line break.
      return languageSwitched ? getLineBreaksWhenSilenceAndLanguageSwitch() : silenceLineBreak;
    }
  }
  return languageSwitched ? languageSwitchLineBreak : "";
}
 
Example 6
Source File: SlidingWindows.java    From beam with Apache License 2.0 5 votes vote down vote up
private SlidingWindows(Duration period, Duration size, Duration offset) {
  if (offset.isShorterThan(Duration.ZERO)
      || !offset.isShorterThan(period)
      || !size.isLongerThan(Duration.ZERO)) {
    throw new IllegalArgumentException(
        "SlidingWindows WindowingStrategies must have 0 <= offset < period and 0 < size");
  }
  this.period = period;
  this.size = size;
  this.offset = offset;
}
 
Example 7
Source File: SlidingWindows.java    From beam with Apache License 2.0 5 votes vote down vote up
static Duration getDefaultPeriod(Duration size) {
  if (size.isLongerThan(Duration.standardHours(1))) {
    return Duration.standardHours(1);
  }
  if (size.isLongerThan(Duration.standardMinutes(1))) {
    return Duration.standardMinutes(1);
  }
  if (size.isLongerThan(Duration.standardSeconds(1))) {
    return Duration.standardSeconds(1);
  }
  return Duration.millis(1);
}
 
Example 8
Source File: SourceDStream.java    From beam with Apache License 2.0 5 votes vote down vote up
private Duration boundReadDuration(double readTimePercentage, long minReadTimeMillis) {
  long batchDurationMillis = ssc().graph().batchDuration().milliseconds();
  Duration proportionalDuration =
      new Duration(Math.round(batchDurationMillis * readTimePercentage));
  Duration lowerBoundDuration = new Duration(minReadTimeMillis);
  Duration readDuration =
      proportionalDuration.isLongerThan(lowerBoundDuration)
          ? proportionalDuration
          : lowerBoundDuration;
  LOG.info("Read duration set to: " + readDuration);
  return readDuration;
}
 
Example 9
Source File: AsyncTaskEnqueuer.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Enqueues a task to asynchronously re-save an entity at some point(s) in the future.
 *
 * <p>Multiple re-save times are chained one after the other, i.e. any given run will re-enqueue
 * itself to run at the next time if there are remaining re-saves scheduled.
 */
public void enqueueAsyncResave(
    ImmutableObject entityToResave, DateTime now, ImmutableSortedSet<DateTime> whenToResave) {
  DateTime firstResave = whenToResave.first();
  checkArgument(isBeforeOrAt(now, firstResave), "Can't enqueue a resave to run in the past");
  Key<ImmutableObject> entityKey = Key.create(entityToResave);
  Duration etaDuration = new Duration(now, firstResave);
  if (etaDuration.isLongerThan(MAX_ASYNC_ETA)) {
    logger.atInfo().log(
        "Ignoring async re-save of %s; %s is past the ETA threshold of %s.",
        entityKey, firstResave, MAX_ASYNC_ETA);
    return;
  }
  logger.atInfo().log("Enqueuing async re-save of %s to run at %s.", entityKey, whenToResave);
  String backendHostname = appEngineServiceUtils.getServiceHostname("backend");
  TaskOptions task =
      TaskOptions.Builder.withUrl(PATH_RESAVE_ENTITY)
          .method(Method.POST)
          .header("Host", backendHostname)
          .countdownMillis(etaDuration.getMillis())
          .param(PARAM_RESOURCE_KEY, entityKey.getString())
          .param(PARAM_REQUESTED_TIME, now.toString());
  if (whenToResave.size() > 1) {
    task.param(PARAM_RESAVE_TIMES, Joiner.on(',').join(whenToResave.tailSet(firstResave, false)));
  }
  addTaskToQueueWithRetry(asyncActionsPushQueue, task);
}
 
Example 10
Source File: DeleteOldCommitLogsAction.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Check if given eppResource has the required revisions.
 *
 * <p>Revisions are used to recreate the state of the resource at a given day in the past
 * "commitLogDatastoreRenention". To do that, we need at least one revision that's older than
 * this duration (is dated before "threshold"), or at least one revision within a day of the
 * resource's creation if it was created after the threshold.
 *
 * <p>Here we check that the given eppResource has the revisions it needs.
 *
 * <p>It's just a sanity check - since we're relying on the revisions to be correct for the
 * deletion to work. We want to alert any problems we find in the revisions.
 *
 * <p>This really checks {@link CommitLogRevisionsTranslatorFactory#transformBeforeSave}.
 * There's nothing we can do at this point to prevent the damage - we only report on it.
 */
private void checkAndLogRevisionCoverageError(EppResource eppResource) {
  // First - check if there even are revisions
  if (eppResource.getRevisions().isEmpty()) {
    getContext().incrementCounter("EPP resources missing all revisions (SEE LOGS)");
    logger.atSevere().log("EPP resource missing all revisions: %s", Key.create(eppResource));
    return;
  }
  // Next, check if there's a revision that's older than "CommitLogDatastoreRetention". There
  // should have been at least one at the time this resource was saved.
  //
  // Alternatively, if the resource is newer than the threshold - there should be at least one
  // revision within a day of the creation time.
  DateTime oldestRevisionDate = eppResource.getRevisions().firstKey();
  if (oldestRevisionDate.isBefore(threshold)
      || oldestRevisionDate.isBefore(eppResource.getCreationTime().plusDays(1))) {
    // We're OK!
    return;
  }
  // The oldest revision date is newer than the threshold! This shouldn't happen.
  getContext().incrementCounter("EPP resources missing pre-threshold revision (SEE LOGS)");
  logger.atSevere().log(
      "EPP resource missing old enough revision: "
          + "%s (created on %s) has %d revisions between %s and %s, while threshold is %s",
      Key.create(eppResource),
      eppResource.getCreationTime(),
      eppResource.getRevisions().size(),
      eppResource.getRevisions().firstKey(),
      eppResource.getRevisions().lastKey(),
      threshold);
  // We want to see how bad it is though: if the difference is less than a day then this might
  // still be OK (we only need logs for the end of the day). But if it's more than a day, then
  // we are 100% sure we can't recreate all the history we need from the revisions.
  Duration interval = new Duration(threshold, oldestRevisionDate);
  if (interval.isLongerThan(Duration.standardDays(1))) {
    getContext()
        .incrementCounter("EPP resources missing pre-(threshold+1d) revision (SEE LOGS)");
  }
}
 
Example 11
Source File: StreamingDataflowWorkerOptions.java    From beam with Apache License 2.0 4 votes vote down vote up
@Override
public Duration create(PipelineOptions options) {
  Duration period =
      Duration.parse(System.getProperty("windmill.harness_update_reporting_period", "PT10S"));
  return period.isLongerThan(Duration.ZERO) ? period : Duration.standardSeconds(10);
}
 
Example 12
Source File: StreamingDataflowWorkerOptions.java    From beam with Apache License 2.0 4 votes vote down vote up
@Override
public Duration create(PipelineOptions options) {
  Duration period =
      Duration.parse(System.getProperty("windmill.global_get_config_refresh_period", "PT120S"));
  return period.isLongerThan(Duration.ZERO) ? period : Duration.standardMinutes(2);
}
 
Example 13
Source File: DateUtils.java    From joda-time-android with Apache License 2.0 4 votes vote down vote up
/**
 * Return string describing the time until/elapsed time since 'time' formatted like
 * "[relative time/date], [time]".
 *
 * See {@link android.text.format.DateUtils#getRelativeDateTimeString} for full docs.
 *
 * @param context the context
 * @param time some time
 * @param transitionResolution the elapsed time (period) at which
 * to stop reporting relative measurements. Periods greater
 * than this resolution will default to normal date formatting.
 * For example, will transition from "6 days ago" to "Dec 12"
 * when using Weeks.ONE.  If null, defaults to Days.ONE.
 * Clamps to min value of Days.ONE, max of Weeks.ONE.
 * @param flags flags for getRelativeTimeSpanString() (if duration is less than transitionResolution)
 */
public static CharSequence getRelativeDateTimeString(Context context, ReadableInstant time,
                                                     ReadablePeriod transitionResolution, int flags) {
    Resources r = context.getResources();

    // We set the millis to 0 so we aren't off by a fraction of a second when counting duration
    DateTime now = DateTime.now(time.getZone()).withMillisOfSecond(0);
    DateTime timeDt = new DateTime(time).withMillisOfSecond(0);
    boolean past = !now.isBefore(timeDt);
    Duration duration = past ? new Duration(timeDt, now) : new Duration(now, timeDt);

    // getRelativeTimeSpanString() doesn't correctly format relative dates
    // above a week or exact dates below a day, so clamp
    // transitionResolution as needed.
    Duration transitionDuration;
    Duration minDuration = Days.ONE.toPeriod().toDurationTo(timeDt);
    if (transitionResolution == null) {
        transitionDuration = minDuration;
    }
    else {
        transitionDuration = past ? transitionResolution.toPeriod().toDurationTo(now) :
            transitionResolution.toPeriod().toDurationFrom(now);
        Duration maxDuration = Weeks.ONE.toPeriod().toDurationTo(timeDt);
        if (transitionDuration.isLongerThan(maxDuration)) {
            transitionDuration = maxDuration;
        }
        else if (transitionDuration.isShorterThan(minDuration)) {
            transitionDuration = minDuration;
        }
    }

    CharSequence timeClause = formatDateRange(context, time, time, FORMAT_SHOW_TIME);

    String result;
    if (!duration.isLongerThan(transitionDuration)) {
        CharSequence relativeClause = getRelativeTimeSpanString(context, time, flags);
        result = r.getString(R.string.joda_time_android_relative_time, relativeClause, timeClause);
    }
    else {
        CharSequence dateClause = getRelativeTimeSpanString(context, time, false);
        result = r.getString(R.string.joda_time_android_date_time, dateClause, timeClause);
    }

    return result;
}