Example usage for org.joda.time Duration millis

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

Introduction

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

Prototype

public static Duration millis(long millis) 

Source Link

Document

Create a duration with the specified number of milliseconds.

Usage

From source file:com.solidfire.core.serialization.DurationAdapter.java

License:Open Source License

/**
 * Reads a Duration object.//from w w  w.ja  v a  2  s . c  om
 *
 * @param reader the JSON reader to read from.
 * @return The Duration object that was read.
 * @throws IOException if the Duration can not be parsed.
 */
@Override
public Duration read(JsonReader reader) throws IOException {
    String input = reader.nextString();
    Matcher m = inputRegex.matcher(input);
    while (m.matches()) {
        long hours = m.group(2) != null ? Long.parseLong(m.group(2)) : 0;
        long minutes = m.group(3) != null ? Long.parseLong(m.group(3)) : 0;
        long seconds = m.group(4) != null ? Long.parseLong(m.group(4)) : 0;

        // Milliseconds are trickier because if the input string is not properly formatted (e.g. ".1") we need to
        // right pad the input string with zeros -- ".1" is really 100 milliseconds. Likewise, if the string is
        // larger than 3 characters, we need to cut off extra characters.
        StringBuffer millisecondsSource = new StringBuffer(m.group(5) != null ? m.group(5) : "000");
        while (millisecondsSource.length() < 3)
            millisecondsSource.append('0');
        String millisecondsSourceResult = millisecondsSource.toString().substring(0, 3);
        long millis = Long.parseLong(millisecondsSourceResult);

        long millisTotal = ((hours * 60 + minutes) * 60 + seconds) * 1000 + millis;

        // Negate final output if '-' was on original input
        if (m.group(1).equals("-"))
            millisTotal = -millisTotal;

        return Duration.millis(millisTotal);
    }
    throw new RuntimeException("Could not extract duration from \"" + input + "\"");
}

From source file:com.solidfire.jsvcgen.serialization.DurationAdapter.java

License:Open Source License

/**
 * Reads a Duration object./* w ww.j av  a  2  s .  co m*/
 *
 * @param reader the JSON reader to read from.
 * @return The Duration object that was read.
 * @throws IOException if the Duration can not be parsed.
 */
@Override
public Duration read(JsonReader reader) throws IOException {
    String input = reader.nextString();
    Matcher m = inputRegex.matcher(input);
    while (m.matches()) {
        long hours = m.group(2) != null ? Long.parseLong(m.group(2)) : 0;
        long minutes = m.group(3) != null ? Long.parseLong(m.group(3)) : 0;
        long seconds = m.group(4) != null ? Long.parseLong(m.group(4)) : 0;

        // Milliseconds are trickier because if the input string is not properly formatted (e.g. ".1") we need to
        // right pad the input string with zeros -- ".1" is really 100 milliseconds. Likewise, if the string is
        // larger than 3 characters, we need to cut off extra characters.
        String millisecondsSource = m.group(5) != null ? m.group(5) : "000";
        while (millisecondsSource.length() < 3)
            millisecondsSource += '0';
        millisecondsSource = millisecondsSource.substring(0, 3);
        long millis = Long.parseLong(millisecondsSource);

        long millisTotal = ((hours * 60 + minutes) * 60 + seconds) * 1000 + millis;

        // Negate final output if '-' was on original input
        if (m.group(1).equals("-"))
            millisTotal = -millisTotal;

        return Duration.millis(millisTotal);
    }
    throw new RuntimeException("Could not extract duration from \"" + input + "\"");
}

From source file:com.spotify.helios.cli.Output.java

License:Apache License

public static String humanDuration(final long millis) {
    return humanDuration(Duration.millis(millis));
}

From source file:com.tomtom.speedtools.metrics.MetricsCollector.java

License:Apache License

public MetricsCollector(@Nonnull final Duration totalMetricDuration, final int maxEntries) {
    assert totalMetricDuration != null;
    assert totalMetricDuration.isLongerThan(Duration.millis(1));
    assert maxEntries > 0;
    this.totalMetricDuration = totalMetricDuration;
    this.timeSlotDuration = Duration.millis(totalMetricDuration.getMillis() / maxEntries);
    this.values = new ArrayDeque<>();
}

From source file:debop4k.data.orm.hibernate.usertypes.jodatime.DurationUserType.java

License:Apache License

@Override
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner)
        throws HibernateException, SQLException {
    Long millis = (Long) StandardBasicTypes.LONG.nullSafeGet(rs, names[0], session, owner);
    return (millis != null) ? Duration.millis(millis) : null;
}

From source file:domains.donuts.config.DonutsRegistryConfig.java

License:Open Source License

@Override
public Duration getBaseOfyRetryDuration() {
    return Duration.millis(100);
}

From source file:eu.itesla_project.offline.tools.ListOfflineWorkflowsTool.java

License:Mozilla Public License

@Override
public void run(CommandLine line) throws Exception {
    try (OfflineApplication app = new RemoteOfflineApplicationImpl()) {
        Map<String, OfflineWorkflowStatus> statuses = app.listWorkflows();
        Table table = new Table(4, BorderStyle.CLASSIC_WIDE);
        table.addCell("ID");
        table.addCell("Running");
        table.addCell("Step");
        table.addCell("Time");
        for (Map.Entry<String, OfflineWorkflowStatus> entry : statuses.entrySet()) {
            String workflowId = entry.getKey();
            OfflineWorkflowStatus status = entry.getValue();
            Duration remaining = null;
            if (status.getStartTime() != null) {
                remaining = Duration.millis(status.getStartParameters().getDuration() * 60 * 1000)
                        .minus(new Duration(status.getStartTime(), DateTime.now()));
            }/*ww w  . j  a  v  a  2 s. c  o m*/
            table.addCell(workflowId);
            table.addCell(Boolean.toString(status.isRunning()));
            table.addCell(status.getStep() != null ? status.getStep().toString() : "");
            table.addCell(remaining != null ? PeriodFormat.getDefault().print(remaining.toPeriod()) : "");
        }
        System.out.println(table.render());
    }
}

From source file:google.registry.config.RegistryConfig.java

License:Open Source License

/**
 * Returns the base retry duration that gets doubled after each failure within {@code Ofy}.
 *///w  ww.  j  ava 2 s. c o m
public static Duration getBaseOfyRetryDuration() {
    switch (RegistryEnvironment.get()) {
    case UNITTEST:
        return Duration.ZERO;
    default:
        return Duration.millis(100);
    }
}

From source file:google.registry.model.ofy.Ofy.java

License:Open Source License

/**
 * Transact with commit logs and retry with exponential backoff.
 *
 * <p>This method is broken out from {@link #transactNew(Work)} for testing purposes.
 *///www .ja  va 2  s . c o m
@VisibleForTesting
<R> R transactCommitLoggedWork(CommitLoggedWork<R> work) {
    long baseRetryMillis = getBaseOfyRetryDuration().getMillis();
    for (long attempt = 0, sleepMillis = baseRetryMillis; true; attempt++, sleepMillis *= 2) {
        try {
            ofy().transactNew(work);
            return work.getResult();
        } catch (TransientFailureException | TimestampInversionException | DatastoreTimeoutException
                | DatastoreFailureException e) {
            // TransientFailureExceptions come from task queues and always mean nothing committed.
            // TimestampInversionExceptions are thrown by our code and are always retryable as well.
            // However, datastore exceptions might get thrown even if the transaction succeeded.
            if ((e instanceof DatastoreTimeoutException || e instanceof DatastoreFailureException)
                    && checkIfAlreadySucceeded(work)) {
                return work.getResult();
            }
            if (attempt == NUM_RETRIES) {
                throw e; // Give up.
            }
            sleeper.sleepUninterruptibly(Duration.millis(sleepMillis));
            logger.infofmt(e, "Retrying %s, attempt %s", e.getClass().getSimpleName(), attempt);
        }
    }
}

From source file:google.registry.util.Retrier.java

License:Open Source License

/**
 * Retries a unit of work in the face of transient errors.
 *
 * <p>Retrying is done a fixed number of times, with exponential backoff, if the exception that is
 * thrown is deemed retryable by the predicate. If the error is not considered retryable, or if
 * the thread is interrupted, or if the allowable number of attempts has been exhausted, the
 * original exception is propagated through to the caller.
 *
 * @return <V> the value returned by the {@link Callable}.
 *///ww  w .  j a v a  2s  .co m
public final <V> V callWithRetry(Callable<V> callable, Predicate<Throwable> isRetryable) {
    int failures = 0;
    while (true) {
        try {
            return callable.call();
        } catch (Throwable e) {
            if (++failures == attempts || !isRetryable.apply(e)) {
                throwIfUnchecked(e);
                throw new RuntimeException(e);
            }
            logger.info(e, "Retrying transient error, attempt " + failures);
            try {
                // Wait 100ms on the first attempt, doubling on each subsequent attempt.
                sleeper.sleep(Duration.millis(pow(2, failures) * 100));
            } catch (InterruptedException e2) {
                // Since we're not rethrowing InterruptedException, set the interrupt state on the thread
                // so the next blocking operation will know to abort the thread.
                Thread.currentThread().interrupt();
                throwIfUnchecked(e);
                throw new RuntimeException(e);
            }
        }
    }
}