Example usage for org.joda.time Period toStandardDuration

List of usage examples for org.joda.time Period toStandardDuration

Introduction

In this page you can find the example usage for org.joda.time Period toStandardDuration.

Prototype

public Duration toStandardDuration() 

Source Link

Document

Converts this period to a duration assuming a 7 day week, 24 hour day, 60 minute hour and 60 second minute.

Usage

From source file:ch.eitchnet.android.mabea.model.Today.java

License:Open Source License

private void updateWorkToday() {
    Iterator<Booking> iter = bookings.iterator();
    while (iter.hasNext()) {
        Booking booking = iter.next();//from   w  w w .ja va 2s  .c  o  m
        if (booking.getState() != State.LOGGED_IN || !iter.hasNext())
            continue;

        Booking next = iter.next();
        if (next.getState() != State.LOGGED_OUT)
            throw new IllegalArgumentException(
                    "logging mismatch, expected LOGGED_OUT, but was " + next.getState());

        LocalDateTime lastStateChange = booking.getTimestamp();
        LocalDateTime newStateChange = next.getTimestamp();
        Period period = new Period(lastStateChange, newStateChange);
        this.workToday = period.toStandardDuration().plus(workToday);
    }
}

From source file:ch.eitchnet.android.mabea.model.Today.java

License:Open Source License

public Duration getWorkToday() {
    Booking latestBooking = getLatestBooking();
    if (latestBooking.getState() == State.LOGGED_OUT)
        return workToday;

    Period period = new Period(latestBooking.getTimestamp(), LocalDateTime.now());
    return workToday.plus(period.toStandardDuration());
}

From source file:com.almende.timecontrol.time.TimeSpan.java

License:Apache License

/**
 * Parse duration as {@link DecimalMeasure JSR-275} measure (e.g.
 * {@code "123 ms"}) or as ISO Period with
 * {@link org.threeten.bp.Duration#parse(CharSequence) JSR-310} or
 * {@link Period#parse(String) Joda}./*  w  ww. j av  a 2 s.co m*/
 * 
 * Examples of ISO period:
 * 
 * <pre>
 *    "PT20.345S" -> parses as "20.345 seconds"
 *    "PT15M"     -> parses as "15 minutes" (where a minute is 60 seconds)
 *    "PT10H"     -> parses as "10 hours" (where an hour is 3600 seconds)
 *    "P2D"       -> parses as "2 days" (where a day is 24 hours or 86400 seconds)
 *    "P2DT3H4M"  -> parses as "2 days, 3 hours and 4 minutes"
 *    "P-6H3M"    -> parses as "-6 hours and +3 minutes"
 *    "-P6H3M"    -> parses as "-6 hours and -3 minutes"
 *    "-P-6H+3M"  -> parses as "+6 hours and -3 minutes"
 * </pre>
 * 
 * @param measure the {@link String} representation of a duration
 * @return
 * 
 * @see org.threeten.bp.Duration#parse(String)
 * @see org.joda.time.format.ISOPeriodFormat#standard()
 * @see DecimalMeasure
 */
public static final Measure<BigDecimal, Duration> parsePeriodOrMeasure(final String measure) {
    if (measure == null)
        throw new NullPointerException();
    DecimalMeasure<Duration> result;
    try {
        result = DecimalMeasure.valueOf(measure);
        // LOG.trace("Parsed '{}' as JSR-275 measure/unit: {}", measure,
        // result);
        return result;
    } catch (final Exception a) {
        // LOG.trace("JSR-275 failed, try JSR-310", e);
        try {
            // final long millis = Period.parse(measure).getMillis();
            // return DecimalMeasure.valueOf(BigDecimal.valueOf(millis),
            // SI.MILLI(SI.SECOND));
            final org.threeten.bp.Duration temp = org.threeten.bp.Duration.parse(measure);
            result = temp.getNano() == 0
                    ? DecimalMeasure.valueOf(BigDecimal.valueOf(temp.getSeconds()), SI.SECOND)
                    : DecimalMeasure.valueOf(BigDecimal.valueOf(temp.getSeconds())
                            .multiply(BigDecimal.TEN.pow(9)).add(BigDecimal.valueOf(temp.getNano())),
                            TimeControl.NANOS);
            // LOG.trace(
            // "Parsed '{}' using JSR-310 to JSR-275 measure/unit: {}",
            // measure, result);
            return result;
        } catch (final Exception e) {
            // LOG.trace("JSR-275 and JSR-310 failed, try Joda", e);
            final Period joda = Period.parse(measure);
            result = DecimalMeasure.valueOf(BigDecimal.valueOf(joda.toStandardDuration().getMillis()),
                    TimeControl.MILLIS);
            // LOG.trace(
            // "Parsed '{}' using Joda to JSR-275 measure/unit: {}",
            // measure, result);
            return result;
        }
    }
}

From source file:com.arpnetworking.clusteraggregator.JvmMetricsCollector.java

License:Apache License

private JvmMetricsCollector(final Period interval, final MetricsFactory metricsFactory) {
    this(FiniteDuration.create(interval.toStandardDuration().getMillis(), TimeUnit.MILLISECONDS),
            new JvmMetricsRunnable.Builder().setMetricsFactory(metricsFactory).setSwallowException(false) // Relying on the default akka supervisor strategy here.
                    .build(),/*  www  . ja v  a 2 s  .  com*/
            null);
}

From source file:com.arpnetworking.metrics.generator.schedule.ConstantTimeScheduler.java

License:Apache License

/**
 * Public constructor.//  ww  w  .  ja va  2s  .  co  m
 *
 * @param time The time interval for scheduling.
 */
public ConstantTimeScheduler(final Period time) {
    _time = TimeUnit.NANOSECONDS.convert(time.toStandardDuration().getMillis(), TimeUnit.MILLISECONDS);
}

From source file:com.arpnetworking.metrics.mad.PeriodWorker.java

License:Apache License

static Duration getPeriodTimeout(final Period period) {
    // TODO(vkoskela): Support separate configurable timeouts per period. [MAI-499]
    final Duration timeoutDuration = period.toStandardDuration().dividedBy(2);
    if (MINIMUM_PERIOD_TIMEOUT.isLongerThan(timeoutDuration)) {
        return MINIMUM_PERIOD_TIMEOUT;
    }/*ww w. j av  a2 s.c o  m*/
    if (MAXIMUM_PERIOD_TIMEOUT.isShorterThan(timeoutDuration)) {
        return MAXIMUM_PERIOD_TIMEOUT;
    }
    return timeoutDuration;
}

From source file:com.arpnetworking.metrics.mad.PeriodWorker.java

License:Apache License

static DateTime getStartTime(final DateTime dateTime, final Period period) {
    // This effectively uses Jan 1, 1970 at 00:00:00 as the anchor point
    // for non-standard bucket sizes (e.g. 18 min) that do not divide
    // equally into an hour or day. Such use cases are rather uncommon.
    final long periodMillis = period.toStandardDuration().getMillis();
    final long dateTimeMillis = dateTime.getMillis();
    return new DateTime(dateTimeMillis - (dateTimeMillis % periodMillis), DateTimeZone.UTC);
}

From source file:com.arpnetworking.tsdcore.sinks.circonus.CirconusSinkActor.java

License:Apache License

/**
 * Public constructor./*from  w  ww  .j  a  v a 2s . co  m*/
 *
 * @param client Circonus client
 * @param broker Circonus broker to push to
 * @param maximumConcurrency the maximum number of parallel metric submissions
 * @param maximumQueueSize the maximum size of the pending metrics queue
 * @param spreadPeriod the maximum wait time before starting to send metrics
 * @param enableHistograms true to turn on histogram publication
 * @param partitionSet the partition set to partition the check bundles with
 */
public CirconusSinkActor(final CirconusClient client, final String broker, final int maximumConcurrency,
        final int maximumQueueSize, final Period spreadPeriod, final boolean enableHistograms,
        final PartitionSet partitionSet) {
    _client = client;
    _brokerName = broker;
    _maximumConcurrency = maximumConcurrency;
    _enableHistograms = enableHistograms;
    _partitionSet = partitionSet;
    _pendingRequests = EvictingQueue.create(maximumQueueSize);
    if (Period.ZERO.equals(spreadPeriod)) {
        _spreadingDelayMillis = 0;
    } else {
        _spreadingDelayMillis = new Random().nextInt((int) spreadPeriod.toStandardDuration().getMillis());
    }
    _dispatcher = getContext().system().dispatcher();
    context().actorOf(BrokerRefresher.props(_client), "broker-refresher");
    _checkBundleRefresher = context().actorOf(CheckBundleActivator.props(_client), "check-bundle-refresher");
}

From source file:com.arpnetworking.tsdcore.sinks.HttpSinkActor.java

License:Apache License

/**
 * Public constructor.//from  w w w. j  av  a2s .com
 *
 * @param client Http client to create requests from.
 * @param sink Sink that controls request creation and data serialization.
 * @param maximumConcurrency Maximum number of concurrent requests.
 * @param maximumQueueSize Maximum number of pending requests.
 * @param spreadPeriod Maximum time to delay sending new aggregates to spread load.
 */
public HttpSinkActor(final AsyncHttpClient client, final HttpPostSink sink, final int maximumConcurrency,
        final int maximumQueueSize, final Period spreadPeriod) {
    _client = client;
    _sink = sink;
    _maximumConcurrency = maximumConcurrency;
    _pendingRequests = EvictingQueue.create(maximumQueueSize);
    if (Period.ZERO.equals(spreadPeriod)) {
        _spreadingDelayMillis = 0;
    } else {
        _spreadingDelayMillis = new Random().nextInt((int) spreadPeriod.toStandardDuration().getMillis());
    }
}

From source file:com.arpnetworking.tsdcore.sinks.PeriodFilteringSink.java

License:Apache License

private PeriodFilteringSink(final Builder builder) {
    super(builder);
    _cachedFilterResult = CacheBuilder.newBuilder().maximumSize(10).build(new CacheLoader<Period, Boolean>() {
        @Override/*from   w  w w  .j a va2 s  .  co m*/
        public Boolean load(final Period key) throws Exception {
            if (_include.contains(key)) {
                return true;
            }
            if (_exclude.contains(key)) {
                return false;
            }
            if (_excludeLessThan.isPresent()
                    && key.toStandardDuration().isShorterThan(_excludeLessThan.get().toStandardDuration())) {
                return false;
            }
            if (_excludeGreaterThan.isPresent()
                    && key.toStandardDuration().isLongerThan(_excludeGreaterThan.get().toStandardDuration())) {
                return false;
            }
            return true;
        }
    });
    _exclude = Sets.newConcurrentHashSet(builder._exclude);
    _include = Sets.newConcurrentHashSet(builder._include);
    _excludeLessThan = Optional.fromNullable(builder._excludeLessThan);
    _excludeGreaterThan = Optional.fromNullable(builder._excludeGreaterThan);
    _sink = builder._sink;
}