Example usage for org.joda.time Duration isShorterThan

List of usage examples for org.joda.time Duration isShorterThan

Introduction

In this page you can find the example usage for org.joda.time Duration isShorterThan.

Prototype

public boolean isShorterThan(ReadableDuration duration) 

Source Link

Document

Is the length of this duration shorter than the duration passed in.

Usage

From source file:com.github.dbourdette.otto.data.DataTableUtils.java

License:Apache License

/**
 * Finds best Duration of rows for a {@link SimpleDataTable} based on given table interval
 *//*from  w w  w.  ja v a 2 s . c  o m*/
public static Duration findBest(Interval interval) {
    Duration duration = new Duration(interval.getStart(), interval.getEnd());

    if (duration.isShorterThan(ONE_DAY) || duration.equals(ONE_DAY)) {
        return Duration.standardMinutes(5);
    } else if (duration.isShorterThan(FIVE_DAYS) || duration.equals(FIVE_DAYS)) {
        return Duration.standardMinutes(30);
    } else {
        return Duration.standardDays(1);
    }
}

From source file:com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows.java

License:Apache License

private FixedWindows(Duration size, Duration offset) {
    if (offset.isShorterThan(Duration.ZERO) || !offset.isShorterThan(size)) {
        throw new IllegalArgumentException("FixedWindows WindowingStrategies must have 0 <= offset < size");
    }// w w w  .jav a 2 s. c om
    this.size = size;
    this.offset = offset;
}

From source file:com.google.cloud.dataflow.sdk.transforms.windowing.SlidingWindows.java

License:Apache License

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");
    }/*w w  w. j ava  2  s.c o  m*/
    this.period = period;
    this.size = size;
    this.offset = offset;
}

From source file:com.thoughtworks.go.server.ui.JobInstanceModel.java

License:Apache License

public int getPercentComplete() {
    Duration eta = eta();
    if (eta.getMillis() == 0) {
        return 0;
    }//from  w ww.  j  a  v a  2 s  . c  om
    if (eta.isShorterThan(getElapsedTime())) {
        return 100;
    }
    return (int) ((getElapsedTime().getMillis() * 100) / eta.getMillis());
}

From source file:com.vaushell.superpipes.nodes.buffer.N_Buffer.java

License:Open Source License

private Duration getTimeToWait(final DateTime from) {
    // Best slot/*  w ww  .j a  va2  s  .c  o m*/
    Duration minDuration;
    if (slots.isEmpty()) {
        minDuration = new Duration(0L);
    } else {
        minDuration = null;
        for (final Slot slot : slots) {
            final Duration duration = slot.getSmallestDiff(from);
            if (minDuration == null || duration.isShorterThan(minDuration)) {
                minDuration = duration;

                if (minDuration.getMillis() <= 0L) {
                    break;
                }
            }
        }
    }

    // Anti burst
    if (getProperties().containsKey("flow-limit") && lastWrite != null) {
        final Duration diff = new Duration(lastWrite, from);

        final Duration toAdd = getProperties().getConfigDuration("flow-limit").minus(diff);
        if (toAdd.isLongerThan(minDuration)) {
            minDuration = toAdd;
        }
    }

    // First message
    if (!messageIDs.isEmpty()) {
        final long firstID = messageIDs.first();
        final DateTime first = new DateTime(firstID);

        if (first.isAfter(from)) {
            final Duration diff = new Duration(from, first);
            if (diff.isLongerThan(minDuration)) {
                minDuration = diff;
            }
        }
    }

    // Result
    return minDuration;
}

From source file:com.vaushell.superpipes.nodes.buffer.Slot.java

License:Open Source License

/**
 * Return the time to wait to be in a slot and not to burst.
 *
 * @param date Actual date//from ww w . j a va  2  s.  c  o m
 * @return the time to wait
 */
public Duration getSmallestDiff(final DateTime date) {
    if (areWeInside(date)) {
        return new Duration(0L);
    }

    Duration smallest = null;
    for (final int dayOfWeek : daysOfWeek) {
        DateTime next = date.withDayOfWeek(dayOfWeek).withMillisOfDay(minMillisOfDay);
        if (next.isBefore(date)) {
            next = next.plusWeeks(1);
        }

        final Duration duration = new Duration(date, next);
        if (smallest == null || duration.isShorterThan(smallest)) {
            smallest = duration;
        }
    }

    return smallest;
}

From source file:com.vaushell.superpipes.tools.retry.A_Retry.java

License:Open Source License

/**
 * Execute.//  w ww.j av  a  2  s . c o  m
 *
 * @return Function returns if necessary.
 * @throws RetryException
 */
public T execute() throws RetryException {
    start = new DateTime();

    while (true) {
        try {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("try " + tryCount + "/" + retry);
            }

            return executeContent();
        } catch (final Throwable ex) {
            // Error
            if (tryCount >= retry) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("try count reached");
                }

                throw new RetryException(ex);
            }

            if (maxDuration.getMillis() > 0L) {
                final Duration actualDuration = new Duration(start, null);

                if (!actualDuration.isShorterThan(maxDuration)) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("try delay reached");
                    }

                    throw new RetryException(ex);
                }
            }
        }

        if (waitTime.getMillis() > 0L) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(
                        "try " + tryCount + "/" + retry + " failed. Wait " + waitTime + " before next retry");
            }

            try {
                Thread.sleep(waitTime.getMillis());
            } catch (final InterruptedException ex) {
                // Ignore
            }
        } else {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("try " + tryCount + "/" + retry + " failed. Don't wait");
            }
        }

        // First, multiply time
        waitTime = new Duration((long) ((double) waitTime.getMillis() * waitTimeMultiplier));

        // Second, add jitter
        if (jitterRange > 0) {
            final int jitter = random.nextInt(jitterRange);
            if (random.nextBoolean()) {
                waitTime = waitTime.plus((long) jitter);
            } else {
                if ((long) jitter < waitTime.getMillis()) {
                    waitTime = waitTime.minus((long) jitter);
                }
            }
        }

        ++tryCount;
    }
}

From source file:google.registry.export.CheckSnapshotAction.java

License:Open Source License

private void checkAndLoadSnapshotIfComplete() {
    Set<String> kindsToLoad = ImmutableSet.copyOf(Splitter.on(',').split(kindsToLoadParam));
    DatastoreBackupInfo backup = getBackup();
    // Stop now if the backup is not complete.
    if (!backup.getStatus().equals(BackupStatus.COMPLETE)) {
        Duration runningTime = backup.getRunningTime();
        if (runningTime.isShorterThan(MAXIMUM_BACKUP_RUNNING_TIME)) {
            // Backup might still be running, so send a 304 to have the task retry.
            throw new NotModifiedException(String.format("Datastore backup %s still pending", snapshotName));
        } else {//w  w w .  j  a va 2 s  .c  om
            // Declare the backup a lost cause, and send 204 No Content so the task will
            // not be retried.
            String message = String.format("Datastore backup %s abandoned - not complete after %s",
                    snapshotName, PeriodFormat.getDefault().print(runningTime.toPeriod()
                            .normalizedStandard(PeriodType.dayTime().withMillisRemoved())));
            throw new NoContentException(message);
        }
    }
    // Get a compact string to identify this snapshot in BigQuery by trying to parse the unique
    // suffix out of the snapshot name and falling back to the start time as a string.
    String snapshotId = snapshotName.startsWith(ExportSnapshotAction.SNAPSHOT_PREFIX)
            ? snapshotName.substring(ExportSnapshotAction.SNAPSHOT_PREFIX.length())
            : backup.getStartTime().toString("YYYYMMdd_HHmmss");
    // Log a warning if kindsToLoad is not a subset of the exported snapshot kinds.
    if (!backup.getKinds().containsAll(kindsToLoad)) {
        logger.warningfmt("Kinds to load included non-exported kinds: %s",
                Sets.difference(kindsToLoad, backup.getKinds()));
    }
    // Load kinds from the snapshot, limited to those also in kindsToLoad (if it's present).
    ImmutableSet<String> exportedKindsToLoad = ImmutableSet
            .copyOf(intersection(backup.getKinds(), kindsToLoad));
    String message = String.format("Datastore backup %s complete - ", snapshotName);
    if (exportedKindsToLoad.isEmpty()) {
        message += "no kinds to load into BigQuery";
    } else {
        enqueueLoadSnapshotTask(snapshotId, backup.getGcsFilename().get(), exportedKindsToLoad);
        message += "BigQuery load task enqueued";
    }
    logger.info(message);
    response.setPayload(message);
}

From source file:google.registry.export.CheckSnapshotServlet.java

License:Open Source License

@Override
public void doPost(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
    String snapshotName;/*from w ww  . j  av a  2  s.  c o  m*/
    String kindsToLoadParam;
    // TODO(b/28266757): Remove this try/catch/rethrow block once this servlet is Daggerized.
    try {
        snapshotName = extractRequiredParameter(req, SNAPSHOT_NAME_PARAM);
        kindsToLoadParam = extractRequiredParameter(req, SNAPSHOT_KINDS_TO_LOAD_PARAM);
    } catch (BadRequestException e) {
        throw new IllegalArgumentException(e.getMessage());
    }
    Set<String> kindsToLoad = ImmutableSet.copyOf(Splitter.on(',').split(kindsToLoadParam));

    // Look up the backup by the provided name, stopping if we can't find it.
    DatastoreBackupInfo backup;
    try {
        backup = backupService.findByName(snapshotName);
    } catch (IllegalArgumentException e) {
        String message = String.format("Bad backup name %s: %s", snapshotName, e.getMessage());
        logger.severe(e, message);
        // TODO(b/19081569): Ideally this would return a 2XX error so the task would not be retried,
        //   but we might abandon backups that start late and haven't yet written to datastore.
        //   We could fix that by replacing this with a two-phase polling strategy.
        rsp.sendError(SC_BAD_REQUEST, htmlEscaper().escape(message));
        return;
    }
    // Stop now if the backup is not complete.
    if (!backup.getStatus().equals(BackupStatus.COMPLETE)) {
        Duration runningTime = backup.getRunningTime();
        if (runningTime.isShorterThan(MAXIMUM_BACKUP_RUNNING_TIME)) {
            // Backup might still be running, so send a 304 to have the task retry.
            rsp.sendError(SC_NOT_MODIFIED,
                    htmlEscaper().escape(String.format("Datastore backup %s still pending", snapshotName)));
        } else {
            // Declare the backup a lost cause, and send 202 Accepted so the task will not be retried.
            String message = String.format("Datastore backup %s abandoned - not complete after %s",
                    snapshotName, PeriodFormat.getDefault().print(runningTime.toPeriod()
                            .normalizedStandard(PeriodType.dayTime().withMillisRemoved())));
            logger.severe(message);
            rsp.sendError(SC_ACCEPTED, htmlEscaper().escape(message));
        }
        return;
    }
    // Get a compact string to identify this snapshot in BigQuery by trying to parse the unique
    // suffix out of the snapshot name and falling back to the start time as a string.
    String snapshotId = snapshotName.startsWith(ExportSnapshotServlet.SNAPSHOT_PREFIX)
            ? snapshotName.substring(ExportSnapshotServlet.SNAPSHOT_PREFIX.length())
            : backup.getStartTime().toString("YYYYMMdd_HHmmss");
    // Log a warning if kindsToLoad is not a subset of the exported snapshot kinds.
    if (!backup.getKinds().containsAll(kindsToLoad)) {
        logger.warningfmt("Kinds to load included non-exported kinds: %s",
                Sets.difference(kindsToLoad, backup.getKinds()));
    }
    // Load kinds from the snapshot, limited to those also in kindsToLoad (if it's present).
    ImmutableSet<String> exportedKindsToLoad = ImmutableSet
            .copyOf(intersection(backup.getKinds(), kindsToLoad));
    String message = String.format("Datastore backup %s complete - ", snapshotName);
    if (exportedKindsToLoad.isEmpty()) {
        message += "no kinds to load into BigQuery";
    } else {
        enqueueLoadSnapshotTask(snapshotId, backup.getGcsFilename().get(), exportedKindsToLoad);
        message += "BigQuery load task enqueued";
    }
    logger.info(message);
    rsp.getWriter().write(message);
}

From source file:julian.lylly.model.Prospect.java

public boolean isSucceeded(Duration timespent) {
    return isOver() && !timespent.isShorterThan(min) && !timespent.isLongerThan(max);
}