Example usage for org.joda.time Duration getMillis

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

Introduction

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

Prototype

public long getMillis() 

Source Link

Document

Gets the length of this duration in milliseconds.

Usage

From source file:com.facebook.stats.DecayCounter.java

License:Apache License

/**
 * @return counter value after computing exponential decay of the counter
 *         value/*from   ww  w  .j ava  2  s  .  co  m*/
 */
@Override
public long getValue() {
    DateTime now = getNow();

    // don't start decay unless it's at least 1s after the decayStart
    if (now.isAfter(decayStart.toDateTime().plusSeconds(1))) {
        Duration elapsed = new Duration(decayStart, now);
        long millis = elapsed.getMillis();

        // compute total decay for millis / 1000 seconds
        double thisDecay = Math.pow(1.0 - decayRatePerSecond, (double) (millis / (double) 1000));

        return (long) (count.get() * thisDecay);
    } else {
        return count.get();
    }
}

From source file:com.facebook.stats.mx.StatsUtil.java

License:Apache License

public static void main(String[] args) {
    DateTime start = new DateTime("2012-01-01T01:01:00.000Z");
    DateTime end = new DateTime("2012-01-01T01:02:00.000Z");
    Duration x = new Duration(start, end);
    System.err.println(x.getMillis());
}

From source file:com.facebook.util.TimeUtil.java

License:Apache License

public static void advanceNow(Duration duration) {
    long now = DateTimeUtils.currentTimeMillis();

    DateTimeUtils.setCurrentMillisFixed(now + duration.getMillis());
}

From source file:com.funambol.common.pim.utility.TimeUtils.java

License:Open Source License

/**
 * Returns the given Iso 8601 duration in minutes
 * @param iso8601Duration String//from www  .j  av  a 2  s .  c o m
 * @return int
 */
public static int getMinutes(String iso8601Duration) {
    if (iso8601Duration == null || iso8601Duration.equals("") || iso8601Duration.equalsIgnoreCase("null")) {
        return -1;
    }

    PeriodFormatter formatter = ISOPeriodFormat.standard();
    Period p = formatter.parsePeriod(iso8601Duration);
    Duration d = p.toDurationFrom(new Instant(0));
    long mills = d.getMillis();
    int minutes = (int) (mills / 60L / 1000L);
    return minutes;
}

From source file:com.funambol.common.pim.utility.TimeUtils.java

License:Open Source License

/**
 * Calculate the minutes into int format in the case in which the input
 * is into ISO 8601 format; else return the interval
 *
 * @param interval the interval in which the reminder has to be repeated
 *
 * @return int the interval in minutes format
 *//*w ww .j  av a 2s. co m*/
public static int getAlarmInterval(String interval) {
    if (interval == null) {
        return 0;
    }
    interval = interval.trim();
    if ("".equals(interval)) {
        return 0;
    }

    int sign;
    if (interval.startsWith("-")) {
        interval = interval.substring(1);
        sign = -1;
    } else {
        sign = +1;
    }

    Period period;
    try {
        period = INTERVAL_FORMATTER.parsePeriod(interval);
    } catch (Exception e) {
        return Integer.parseInt(interval.replaceAll("^[0-9]", "")); // best guess
    }

    //@TODO Replace it with new methods in Joda 1.5 when the dependency is
    //      updated to the latest version
    Duration d = period.toDurationFrom(new Instant(0));
    long millis = d.getMillis();
    int minutes = (int) (millis / 60000L);
    return sign * minutes;
}

From source file:com.google.api.codegen.config.MethodConfig.java

License:Apache License

/**
 * Creates an instance of MethodConfig based on MethodConfigProto, linking it up with the provided
 * method. On errors, null will be returned, and diagnostics are reported to the diag collector.
 */// w w  w  . j av a 2 s . c  o m
@Nullable
public static MethodConfig createMethodConfig(DiagCollector diagCollector, String language,
        MethodConfigProto methodConfigProto, Method method, ResourceNameMessageConfigs messageConfigs,
        ImmutableMap<String, ResourceNameConfig> resourceNameConfigs,
        ImmutableSet<String> retryCodesConfigNames, ImmutableSet<String> retryParamsConfigNames) {

    boolean error = false;

    PageStreamingConfig pageStreaming = null;
    if (!PageStreamingConfigProto.getDefaultInstance().equals(methodConfigProto.getPageStreaming())) {
        pageStreaming = PageStreamingConfig.createPageStreaming(diagCollector, messageConfigs,
                resourceNameConfigs, methodConfigProto, method);
        if (pageStreaming == null) {
            error = true;
        }
    }

    GrpcStreamingConfig grpcStreaming = null;
    if (isGrpcStreamingMethod(method)) {
        if (PageStreamingConfigProto.getDefaultInstance().equals(methodConfigProto.getGrpcStreaming())) {
            grpcStreaming = GrpcStreamingConfig.createGrpcStreaming(diagCollector, method);
        } else {
            grpcStreaming = GrpcStreamingConfig.createGrpcStreaming(diagCollector,
                    methodConfigProto.getGrpcStreaming(), method);
            if (grpcStreaming == null) {
                error = true;
            }
        }
    }

    ImmutableList<FlatteningConfig> flattening = null;
    if (!FlatteningConfigProto.getDefaultInstance().equals(methodConfigProto.getFlattening())) {
        flattening = createFlattening(diagCollector, messageConfigs, resourceNameConfigs, methodConfigProto,
                method);
        if (flattening == null) {
            error = true;
        }
    }

    BundlingConfig bundling = null;
    if (!BundlingConfigProto.getDefaultInstance().equals(methodConfigProto.getBundling())) {
        bundling = BundlingConfig.createBundling(diagCollector, methodConfigProto.getBundling(), method);
        if (bundling == null) {
            error = true;
        }
    }

    String retryCodesName = methodConfigProto.getRetryCodesName();
    if (!retryCodesName.isEmpty() && !retryCodesConfigNames.contains(retryCodesName)) {
        diagCollector.addDiag(Diag.error(SimpleLocation.TOPLEVEL,
                "Retry codes config used but not defined: '%s' (in method %s)", retryCodesName,
                method.getFullName()));
        error = true;
    }

    String retryParamsName = methodConfigProto.getRetryParamsName();
    if (!retryParamsConfigNames.isEmpty() && !retryParamsConfigNames.contains(retryParamsName)) {
        diagCollector.addDiag(Diag.error(SimpleLocation.TOPLEVEL,
                "Retry parameters config used but not defined: %s (in method %s)", retryParamsName,
                method.getFullName()));
        error = true;
    }

    Duration timeout = Duration.millis(methodConfigProto.getTimeoutMillis());
    if (timeout.getMillis() <= 0) {
        diagCollector.addDiag(Diag.error(SimpleLocation.TOPLEVEL,
                "Default timeout not found or has invalid value (in method %s)", method.getFullName()));
        error = true;
    }

    boolean hasRequestObjectMethod = methodConfigProto.getRequestObjectMethod();

    ImmutableMap<String, String> fieldNamePatterns = ImmutableMap
            .copyOf(methodConfigProto.getFieldNamePatterns());

    ResourceNameTreatment defaultResourceNameTreatment = methodConfigProto.getResourceNameTreatment();
    if (defaultResourceNameTreatment == null
            || defaultResourceNameTreatment.equals(ResourceNameTreatment.UNSET_TREATMENT)) {
        defaultResourceNameTreatment = ResourceNameTreatment.NONE;
    }

    Iterable<FieldConfig> requiredFieldConfigs = createFieldNameConfigs(diagCollector, messageConfigs,
            defaultResourceNameTreatment, fieldNamePatterns, resourceNameConfigs,
            getRequiredFields(diagCollector, method, methodConfigProto.getRequiredFieldsList()));

    Iterable<FieldConfig> optionalFieldConfigs = createFieldNameConfigs(diagCollector, messageConfigs,
            defaultResourceNameTreatment, fieldNamePatterns, resourceNameConfigs,
            getOptionalFields(method, methodConfigProto.getRequiredFieldsList()));

    List<String> sampleCodeInitFields = new ArrayList<>();
    sampleCodeInitFields.addAll(methodConfigProto.getRequiredFieldsList());
    sampleCodeInitFields.addAll(methodConfigProto.getSampleCodeInitFieldsList());

    String rerouteToGrpcInterface = Strings.emptyToNull(methodConfigProto.getRerouteToGrpcInterface());

    VisibilityConfig visibility = VisibilityConfig.PUBLIC;
    for (SurfaceTreatmentProto treatment : methodConfigProto.getSurfaceTreatmentsList()) {
        if (!treatment.getIncludeLanguagesList().contains(language)) {
            continue;
        }
        if (treatment.getVisibility() != VisibilityProto.UNSET) {
            visibility = VisibilityConfig.fromProto(treatment.getVisibility());
        }
    }

    LongRunningConfig longRunningConfig = null;
    if (!LongRunningConfigProto.getDefaultInstance().equals(methodConfigProto.getLongRunning())) {
        longRunningConfig = LongRunningConfig.createLongRunningConfig(method.getModel(), diagCollector,
                methodConfigProto.getLongRunning());
        if (longRunningConfig == null) {
            error = true;
        }
    }

    if (error) {
        return null;
    } else {
        return new AutoValue_MethodConfig(method, pageStreaming, grpcStreaming, flattening, retryCodesName,
                retryParamsName, timeout, requiredFieldConfigs, optionalFieldConfigs,
                defaultResourceNameTreatment, bundling, hasRequestObjectMethod, fieldNamePatterns,
                sampleCodeInitFields, rerouteToGrpcInterface, visibility, longRunningConfig);
    }
}

From source file:com.google.api.codegen.MethodConfig.java

License:Apache License

/**
 * Creates an instance of MethodConfig based on MethodConfigProto, linking it up with the provided
 * method. On errors, null will be returned, and diagnostics are reported to the diag collector.
 *///from w w w  .  ja v  a 2 s.co  m
@Nullable
public static MethodConfig createMethodConfig(DiagCollector diagCollector,
        final MethodConfigProto methodConfigProto, Method method, ImmutableSet<String> retryCodesConfigNames,
        ImmutableSet<String> retryParamsConfigNames) {

    boolean error = false;

    PageStreamingConfig pageStreaming;
    if (PageStreamingConfigProto.getDefaultInstance().equals(methodConfigProto.getPageStreaming())) {
        pageStreaming = null;
    } else {
        pageStreaming = PageStreamingConfig.createPageStreaming(diagCollector,
                methodConfigProto.getPageStreaming(), method);
        if (pageStreaming == null) {
            error = true;
        }
    }

    FlatteningConfig flattening;
    if (FlatteningConfigProto.getDefaultInstance().equals(methodConfigProto.getFlattening())) {
        flattening = null;
    } else {
        flattening = FlatteningConfig.createFlattening(diagCollector, methodConfigProto.getFlattening(),
                method);
        if (flattening == null) {
            error = true;
        }
    }

    BundlingConfig bundling;
    if (BundlingConfigProto.getDefaultInstance().equals(methodConfigProto.getBundling())) {
        bundling = null;
    } else {
        bundling = BundlingConfig.createBundling(diagCollector, methodConfigProto.getBundling(), method);
        if (bundling == null) {
            error = true;
        }
    }

    String retryCodesName = methodConfigProto.getRetryCodesName();
    if (!retryCodesName.isEmpty() && !retryCodesConfigNames.contains(retryCodesName)) {
        diagCollector.addDiag(Diag.error(SimpleLocation.TOPLEVEL,
                "Retry codes config used but not defined: '%s' (in method %s)", retryCodesName,
                method.getFullName()));
        error = true;
    }

    String retryParamsName = methodConfigProto.getRetryParamsName();
    if (!retryParamsConfigNames.isEmpty() && !retryParamsConfigNames.contains(retryParamsName)) {
        diagCollector.addDiag(Diag.error(SimpleLocation.TOPLEVEL,
                "Retry parameters config used but not defined: %s (in method %s)", retryParamsName,
                method.getFullName()));
        error = true;
    }

    Duration timeout = Duration.millis(methodConfigProto.getTimeoutMillis());
    if (timeout.getMillis() <= 0) {
        diagCollector.addDiag(Diag.error(SimpleLocation.TOPLEVEL,
                "Default timeout not found or has invalid value (in method %s)", method.getFullName()));
        error = true;
    }

    boolean hasRequestObjectMethod = methodConfigProto.getRequestObjectMethod();

    List<String> requiredFieldNames = methodConfigProto.getRequiredFieldsList();
    ImmutableSet.Builder<Field> builder = ImmutableSet.builder();
    for (String fieldName : requiredFieldNames) {
        Field requiredField = method.getInputMessage().lookupField(fieldName);
        if (requiredField != null) {
            builder.add(requiredField);
        } else {
            Diag.error(SimpleLocation.TOPLEVEL, "Required field '%s' not found (in method %s)", fieldName,
                    method.getFullName());
            error = true;
        }
    }
    Set<Field> requiredFields = builder.build();

    Iterable<Field> optionalFields = Iterables.filter(method.getInputType().getMessageType().getFields(),
            new Predicate<Field>() {
                @Override
                public boolean apply(Field input) {
                    return !(methodConfigProto.getRequiredFieldsList().contains(input.getSimpleName()));
                }
            });

    ImmutableMap<String, String> fieldNamePatterns = ImmutableMap
            .copyOf(methodConfigProto.getFieldNamePatterns());

    List<String> sampleCodeInitFields = new ArrayList<>();
    sampleCodeInitFields.addAll(methodConfigProto.getRequiredFieldsList());
    sampleCodeInitFields.addAll(methodConfigProto.getSampleCodeInitFieldsList());

    String rerouteToGrpcInterface = methodConfigProto.getRerouteToGrpcInterface();
    if (Strings.isNullOrEmpty(rerouteToGrpcInterface)) {
        rerouteToGrpcInterface = null;
    }

    if (error) {
        return null;
    } else {
        return new MethodConfig(method, pageStreaming, flattening, retryCodesName, retryParamsName, timeout,
                bundling, hasRequestObjectMethod, requiredFields, optionalFields, fieldNamePatterns,
                sampleCodeInitFields, rerouteToGrpcInterface);
    }
}

From source file:com.google.cloud.dataflow.sdk.runners.inprocess.MockClock.java

License:Apache License

public void advance(Duration duration) {
    checkArgument(duration.getMillis() > 0, "Cannot move MockClock backwards in time by duration %s", duration);
    set(now.plus(duration));//from   w w  w  .j  a v a 2s.c  o  m
}

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

License:Apache License

@VisibleForTesting
static Instant alignedTo(Instant point, Duration size, Instant offset) {
    long millisSinceStart = new Duration(offset, point).getMillis() % size.getMillis();
    return millisSinceStart == 0 ? point : point.plus(size).minus(millisSinceStart);
}

From source file:com.google.cloud.dataflow.sdk.util.FluentBackoff.java

License:Apache License

/**
 * Returns a copy of this {@link FluentBackoff} that limits the maximum backoff of an individual
 * attempt to the specified duration./*from   ww w.  j a va  2  s  .c  o m*/
 *
 * <p>Does not modify this object.
 *
 * @see FluentBackoff
 */
public FluentBackoff withMaxBackoff(Duration maxBackoff) {
    checkArgument(maxBackoff.getMillis() > 0, "maxBackoff %s must be at least 1 millisecond", maxBackoff);
    return new FluentBackoff(exponent, initialBackoff, maxBackoff, maxCumulativeBackoff, maxRetries);
}