Example usage for org.joda.time DateTime plus

List of usage examples for org.joda.time DateTime plus

Introduction

In this page you can find the example usage for org.joda.time DateTime plus.

Prototype

public DateTime plus(ReadablePeriod period) 

Source Link

Document

Returns a copy of this datetime with the specified period added.

Usage

From source file:com.arpnetworking.clusteraggregator.client.AggClientConnection.java

License:Apache License

private Optional<AggregatedData> getAggData(final Messages.LegacyAggRecord aggRecord) {
    try {/*from   w  w  w . j  a v  a  2  s  . com*/
        long sampleCount = 1;
        if (aggRecord.hasRawSampleCount()) {
            sampleCount = aggRecord.getRawSampleCount();
        } else if (aggRecord.getStatisticSamplesCount() > 0) {
            sampleCount = aggRecord.getStatisticSamplesCount();
        }

        final Period period = Period.parse(aggRecord.getPeriod());
        DateTime periodStart;
        if (aggRecord.hasPeriodStart()) {
            periodStart = DateTime.parse(aggRecord.getPeriodStart());
        } else {
            periodStart = DateTime.now().withTime(DateTime.now().getHourOfDay(), 0, 0, 0);
            while (periodStart.plus(period).isBeforeNow()) {
                periodStart = periodStart.plus(period);
            }
        }

        final Optional<Statistic> statisticOptional = _statisticFactory
                .createStatistic(aggRecord.getStatistic());
        if (!statisticOptional.isPresent()) {
            _log.error(String.format("Unsupported statistic %s", aggRecord.getStatistic()));
            return Optional.absent();
        }

        return Optional.of(new AggregatedData.Builder().setHost(_hostName.get())
                .setFQDSN(new FQDSN.Builder().setCluster(_clusterName.get()).setService(aggRecord.getService())
                        .setMetric(aggRecord.getMetric()).setStatistic(statisticOptional.get()).build())
                .setPeriod(Period.parse(aggRecord.getPeriod())).setStart(periodStart)
                .setPopulationSize(sampleCount)
                .setSamples(sampleizeDoubles(aggRecord.getStatisticSamplesList(), Optional.<Unit>absent()))
                .setValue(new Quantity(aggRecord.getStatisticValue(), Optional.<Unit>absent())).build());
        // CHECKSTYLE.OFF: IllegalCatch - The legacy parsing can throw a variety of runtime exceptions
    } catch (final RuntimeException e) {
        // CHECKSTYLE.ON: IllegalCatch
        _log.error("Caught an error parsing legacy agg record", e);
        return Optional.absent();
    }
}

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

License:Apache License

void process(final Record record) {
    // Find an existing bucket for the record
    final Duration timeout = getPeriodTimeout(_period);
    final DateTime start = getStartTime(record.getTime(), _period);
    final DateTime expiration = max(DateTime.now().plus(timeout), start.plus(_period).plus(timeout));
    Bucket bucket = _bucketsByStart.get(start);

    // Create a new bucket if one does not exist
    if (bucket == null) {
        // Pre-emptively add the record to the _new_ bucket. This avoids
        // the race condition after indexing by expiration between adding
        // the record and closing the bucket.
        final Bucket newBucket = _bucketBuilder.setStart(start).build();
        newBucket.add(record);/*from w ww . j  ava2s .  c om*/

        // Resolve bucket creation race condition; either:
        // 1) We won and can proceed to index the new bucket
        // 2) We lost and can proceed to add data to the existing bucket
        bucket = _bucketsByStart.putIfAbsent(start, newBucket);
        if (bucket == null) {
            LOGGER.debug().setMessage("Created new bucket").addData("bucket", newBucket)
                    .addData("expiration", expiration).addData("trigger", record.getId()).log();

            // Index the bucket by its expiration date; the expiration date is always in the future
            _bucketsByExpiration.compute(expiration, (dateTime, buckets) -> {
                if (buckets == null) {
                    buckets = Lists.newArrayList();
                }
                buckets.add(newBucket);
                return buckets;
            });

            // New bucket created and indexed with record
            return;
        }
    }

    // Add the record to the _existing_ bucket
    bucket.add(record);
}

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

License:Apache License

DateTime getRotateAt(final DateTime now) {
    final Map.Entry<DateTime, List<Bucket>> firstEntry = _bucketsByExpiration.firstEntry();
    final DateTime periodFirstExpiration = firstEntry == null ? null : firstEntry.getKey();
    if (periodFirstExpiration != null && periodFirstExpiration.isAfter(now)) {
        return periodFirstExpiration;
    }//  w w w.j av  a2 s  .c  o  m
    return now.plus(_rotationCheck);
}

From source file:com.arpnetworking.utility.RateLimitLogger.java

License:Apache License

/**
 * Triggers logging of the message.//from ww w.ja  v  a  2  s  .  c om
 */
public void log() {
    if (_lastWrite.isPresent()) {
        final DateTime last = _lastWrite.get();
        if (last.plus(_period).isBeforeNow()) {
            if (_suppressed == 0) {
                _loggingAdapter.log(_level.asInt(), _message);
            } else {
                _loggingAdapter.log(_level.asInt(), String.format("%s (suppressed=%d, lastLogged=%s)", _message,
                        _suppressed, new PrettyTime().format(_lastWrite.get().toDate())));
            }
            _lastWrite = Optional.of(DateTime.now());
        } else {
            _suppressed++;
        }
    } else {
        _loggingAdapter.log(_level.asInt(), _message);
        _lastWrite = Optional.of(DateTime.now());
    }

}

From source file:com.catify.processengine.core.util.TimerUtil.java

License:Apache License

/**
 * Calculates a list of time stamps in millis. For each
 * repetition a value will be calculated based on the time
 * to fire time of the previous repetition. If the 'R' is 
 * empty (e.g. R/PT1M), which means an unbounded number of repetitions,
 * the next time to fire is calculated.<br/><br/>
 * /*  w ww  .  j a  v  a2s .com*/
 * You can have the following scenarios:<br/>
 * Cycle with duration and bounded repetitions: R5/PT1M<br/>
 * Cycle with duration and unbounded repetitions: R/PT1M<br/>
 * Cycle with duration, bounded repetitions and start date: R3/2013-04-09T16:34:08Z/P1D<br/> 
 * Cycle with duration, unbounded repetitions and start date: R/2013-04-09T16:34:08Z/P1D<br/>
 * Cycle with duration, bounded repetitions and end date: R3/PT1H/2013-01-30T23:01:00Z<br/> 
 * Cycle with duration, unbounded repetitions and end date: R/PT1H/2013-01-30T23:01:00Z<br/>
 * 
 * @param now actual time stamp in millis
 * @param isoDate as {@link String} e.g. R7/2013-04-09T16:34:08Z/P1D
 * @return {@link List} of time stamps in millis
 */
public static List<Long> calculateTimeToFireForCycle(long now, String isoDate) {
    List<Long> result = new ArrayList<Long>();

    String[] split = isoDate.split("/");
    if (split.length < 2 || split.length > 3) {
        throw new IllegalArgumentException("A ISO 8601 date for a cylce shout have a repeat and duration "
                + "section, or a repeat, date and duration section separated by a slash (e.g R5/PT3M).");
    }

    // repeat is always the first one
    String repeat = split[0];
    // get the repeats
    if (!repeat.startsWith("R")) {
        throw new IllegalArgumentException(
                "A ISO 8601 repeat should start with" + " a 'R', followed by the number of cycles.");
    }
    // get all after the 'R'
    repeat = repeat.substring(1);
    boolean unbounded = false;
    if (repeat.equals("")) {
        /*
         * if we have a unbounded number of repetitions,
         * calculate the next fire time.
         */
        repeat = "1";
        unbounded = true;
    }
    int r = Integer.parseInt(repeat);
    DateTime baseTime = new DateTime(now);

    if (split.length == 2) {
        Period period = periodformatter.parsePeriod(split[1]);
        // calculate the timestamps for the cycles
        for (int i = 0; i < r; i++) {
            baseTime = baseTime.plus(period);
            result.add(baseTime.getMillis());
        }
    }

    // we have start or end date
    if (split.length == 3) {

        if (split[1].startsWith("P")) {
            /*
             * end date -- e.g. R4/PT1H/2013-01-30T23:00:00Z
             */
            DateTime end = dateFormatter.parseDateTime(split[2]);
            Period period = periodformatter.parsePeriod(split[1]);
            if (unbounded) {
                /*
                 * --> R/PT1H/2013-01-30T23:00:00Z <--
                 * calculate all times to fire, until the 
                 * end date is reached.
                 */
                while (baseTime.isBefore(end)) {
                    baseTime = baseTime.plus(period);
                    result.add(baseTime.getMillis());
                }
            } else {
                /*
                 * --> R4/PT1H/2013-01-30T23:00:00Z <--
                 * calculate all times to fire until the 
                 * end date, or the maximum number
                 * of cycles is reached.
                 */
                for (int i = 0; i < r; i++) {
                    baseTime = baseTime.plus(period);
                    if (baseTime.isBefore(end)) {
                        result.add(baseTime.getMillis());
                    }
                }
            }
        } else if (split[2].startsWith("P")) {
            /*
             * start date -- e.g. R/2013-04-09T16:34:08Z/P1D
             */
            DateTime start = dateFormatter.parseDateTime(split[1]);
            Period period = periodformatter.parsePeriod(split[2]);
            if (unbounded) {
                /*
                 * --> R/2013-04-09T16:34:08Z/P1D <--
                 * unbounded cycle with start date
                 */
                if (start.isBefore(now)) {
                    /*
                     * if the start date is in the past,
                     * calculate the next time to fire based
                     * on the 'now' time.
                     */
                    baseTime = baseTime.plus(period);
                    result.add(baseTime.getMillis());
                } else {
                    /* 
                     * if the start date is in the future,
                     * the first time to fire is the start
                     * date. 
                     */
                    result.add(start.getMillis());
                }
            } else {
                /*
                 * --> R7/2013-04-09T16:34:08Z/P1D <--
                 * bounded cycle with start date
                 */
                baseTime = new DateTime(start.getMillis());
                // the first entry is the start date
                result.add(baseTime.getMillis());
                for (int i = 0; i < r; i++) {
                    baseTime = baseTime.plus(period);
                    result.add(baseTime.getMillis());
                }
            }
        } else {
            throw new IllegalArgumentException(
                    "Either the middle or last section of a cycle with start or end date must define a duration.");
        }

    }

    return result;
}

From source file:com.catify.processengine.core.util.TimerUtil.java

License:Apache License

/**
 * Calculate the next time to fire time stamp (in millis) 
 * based on the given 'now' time, plus the ISO 8601 duration.
 * /*from ww w  . j  av a2s .c om*/
 * @param now actual time stamp in millis
 * @param isoDate as {@link String} e.g. PT2H1M10S
 * @return time to fire time stamp in millis
 */
public static long calculateTimeToFireForDuration(long now, String isoDate) {
    DateTime dateTime = new DateTime(now);
    Period period = periodformatter.parsePeriod(isoDate);
    dateTime = dateTime.plus(period);
    return dateTime.getMillis();
}

From source file:com.enonic.cms.business.portal.datasource.expressionfunctions.ExpressionFunctions.java

License:Open Source License

public String currentDatePlusOffset(String format, String periodStr) {
    DateTime nowDateTime = timeService.getNowAsDateTime();
    PeriodFormatter periodFormatter = ISOPeriodFormat.standard();
    Period period = periodFormatter.parsePeriod(periodStr);
    DateTime offsetDateTime = nowDateTime.plus(period);

    SimpleDateFormat fmt = new SimpleDateFormat(format);
    return fmt.format(offsetDateTime.toDate());
}

From source file:com.enonic.cms.core.content.index.queryexpression.DateCompareEvaluator.java

License:Open Source License

private ReadableDateTime createUpperBoundDate(DateMidnight date) {
    DateTime dateMidnight = date.toDateTime();
    return dateMidnight.plus(new Period(23, 59, 59, 999));
}

From source file:com.facebook.presto.execution.QueryTracker.java

License:Apache License

/**
 * Enforce query max runtime/execution time limits
 *//*  w  w w.j  a  va2  s.c o m*/
private void enforceTimeLimits() {
    for (T query : queries.values()) {
        if (query.isDone()) {
            continue;
        }
        Duration queryMaxRunTime = getQueryMaxRunTime(query.getSession());
        Duration queryMaxExecutionTime = getQueryMaxExecutionTime(query.getSession());
        Optional<DateTime> executionStartTime = query.getExecutionStartTime();
        DateTime createTime = query.getCreateTime();
        if (executionStartTime.isPresent()
                && executionStartTime.get().plus(queryMaxExecutionTime.toMillis()).isBeforeNow()) {
            query.fail(new PrestoException(EXCEEDED_TIME_LIMIT,
                    "Query exceeded the maximum execution time limit of " + queryMaxExecutionTime));
        }
        if (createTime.plus(queryMaxRunTime.toMillis()).isBeforeNow()) {
            query.fail(new PrestoException(EXCEEDED_TIME_LIMIT,
                    "Query exceeded maximum time limit of " + queryMaxRunTime));
        }
    }
}

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

License:Apache License

/**
 * Adds the value to the counter, and may create a new eventCounter
 * to store the value if needed./*from  w  w w  . j  a v a  2s . c  om*/
 */
@Override
public void add(long delta) {
    DateTime now = new DateTime();
    C last;

    synchronized (this) {
        if (eventCounters.isEmpty() || !now.isBefore(eventCounters.getLast().getEnd())) {
            addEventCounter(nextCounter(now, now.plus(maxChunkLength)));
        }

        last = eventCounters.getLast();
    }

    last.add(delta);
}