Example usage for org.joda.time MutableDateTime add

List of usage examples for org.joda.time MutableDateTime add

Introduction

In this page you can find the example usage for org.joda.time MutableDateTime add.

Prototype

public void add(ReadablePeriod period) 

Source Link

Document

Adds a period to this instant.

Usage

From source file:com.ning.metrics.serialization.util.DateTimeUtil.java

License:Apache License

public DateTime truncateToWeek(ReadableDateTime time) {
    MutableDateTime result = new MutableDateTime(time);
    result.setMillisOfSecond(0);/*from   ww w  .  ja v  a  2  s  .  c  o  m*/
    result.setSecondOfMinute(0);
    result.setMinuteOfHour(0);
    result.setHourOfDay(0);
    result.setHourOfDay(0);

    if (time.getDayOfWeek() != 7) {
        result.setDayOfWeek(1);
        result.add(Days.ONE.multipliedBy(-1));
    }

    return new DateTime(result);
}

From source file:de.ifgi.airbase.feeder.io.csv.EEARawDataParser.java

License:Open Source License

static EEARawDataFile parseFile(File f, EEAStation station) throws IOException {
    log.debug("Parsing {}", f.getName());
    CSVReader reader = null;//from   w ww. java2s .  c  o m
    try {
        reader = new CSVReader(new FileReader(f), '\t');
        String[] line = null;
        EEARawDataFile file = parseFileName(f, station);
        while ((line = reader.readNext()) != null) {
            Period period = file.getType().getPeriod();
            MutableDateTime lineStart = Utils.parseDateReverse(line[0]).toMutableDateTime();
            for (int i = 1; i < line.length; i += 2) {
                EEAMeasurement m = new EEAMeasurement(Double.parseDouble(line[i]),
                        Integer.parseInt(line[i + 1]), lineStart.toDateTime());
                file.addMeasurement(m);
                lineStart.add(period);
            }
        }
        reader.close();
        return file;
    } finally {
        if (reader != null) {
            reader.close();
        }
        reader = null;
    }
}

From source file:net.solarnetwork.central.dras.mock.biz.MockDRASQueryBiz.java

License:Open Source License

@Override
public List<? extends NodeDatum> getAggregatedDatum(Class<? extends NodeDatum> datumClass,
        DatumQueryCommand criteria) {//from   w  w  w  .  j a  v a 2 s  .c  o m
    MutableDateTime mdt = new MutableDateTime(criteria.getStartDate());
    Period period;
    switch (criteria.getAggregate()) {
    case Hour:
        period = Period.hours(1);
        break;

    case Day:
        period = Period.days(1);
        break;

    case Week:
        period = Period.weeks(1);
        break;

    case Month:
        period = Period.months(1);
        break;

    default:
        period = Period.minutes(1);
    }
    List<NodeDatum> results = new ArrayList<NodeDatum>();
    do {
        NodeDatum datum = null;
        if (ConsumptionDatum.class.isAssignableFrom(datumClass)) {
            ReportingConsumptionDatum d = new ReportingConsumptionDatum();
            d.setNodeId(criteria.getNodeId());
            d.setCreated(mdt.toDateTime());
            Duration dur = period.toDurationFrom(mdt);
            float hours = (float) ((double) dur.getMillis() / (double) (1000 * 60 * 60));
            d.setWattHours(Double.valueOf(hours * consumptionWattHours));
            datum = d;
        } else if (PowerDatum.class.isAssignableFrom(datumClass)) {
            ReportingPowerDatum d = new ReportingPowerDatum();
            d.setNodeId(criteria.getNodeId());
            d.setCreated(mdt.toDateTime());
            Duration dur = period.toDurationFrom(mdt);
            float hours = (float) ((double) dur.getMillis() / (double) (1000 * 60 * 60));
            d.setWattHours(Double.valueOf(hours * generationWattHours));
            datum = d;
        }
        if (datum != null) {
            results.add(datum);
        }
        mdt.add(period);
    } while (mdt.isBefore(criteria.getEndDate()));
    return results;
}

From source file:org.graylog2.indexer.results.FieldHistogramResult.java

License:Open Source License

public Map<Long, Map<String, Number>> getResults() {
    if (result.getBuckets().isEmpty()) {
        return Collections.emptyMap();
    }//from w  w w .  j a v  a 2s .c  o  m

    final Map<Long, Map<String, Number>> results = Maps.newTreeMap();
    for (DateHistogram.Bucket b : result.getBuckets()) {
        final ImmutableMap.Builder<String, Number> resultMap = ImmutableMap.builder();
        resultMap.put("total_count", b.getDocCount());

        final Stats stats = b.getAggregations().get(Searches.AGG_STATS);
        resultMap.put("count", stats.getCount());
        resultMap.put("min", stats.getMin());
        resultMap.put("max", stats.getMax());
        resultMap.put("total", stats.getSum());
        resultMap.put("mean", stats.getAvg());

        // cardinality is only calculated if it was explicitly requested, so this might be null
        final Cardinality cardinality = b.getAggregations().get(Searches.AGG_CARDINALITY);
        resultMap.put("cardinality", cardinality == null ? 0 : cardinality.getValue());

        final long timestamp = b.getKeyAsDate().getMillis() / 1000L;
        results.put(timestamp, resultMap.build());
    }

    final long minTimestamp = Collections.min(results.keySet());
    final long maxTimestamp = Collections.max(results.keySet());
    final MutableDateTime currentTime = new MutableDateTime(minTimestamp, DateTimeZone.UTC);

    while (currentTime.getMillis() < maxTimestamp) {
        final Map<String, Number> entry = results.get(currentTime.getMillis());

        // advance timestamp by the interval's seconds value
        currentTime.add(interval.getPeriod());

        if (entry == null) {
            // synthesize a 0 value for this timestamp
            results.put(currentTime.getMillis(), EMPTY_RESULT);
        }
    }
    return results;
}

From source file:org.openehr.rm.datatypes.quantity.datetime.DvDate.java

License:LGPL

@Override
public DvDate add(DvDuration q) {
    if (!getDiffType().isInstance(q)) {
        throw new IllegalArgumentException("invalid difference type");
    }/*from  ww w .  j a  v a2s . c  o m*/
    DvDuration d = (DvDuration) q;
    MutableDateTime mdate = getDateTime().toMutableDateTimeISO();
    mdate.add(d.getPeriod());
    return new DvDate(getOtherReferenceRanges(), getNormalRange(), getNormalStatus(), getAccuracy(),
            getMagnitudeStatus(), mdate.toDateTimeISO(), toString());
}

From source file:org.openehr.rm.datatypes.quantity.datetime.DvDateTime.java

License:LGPL

@Override
public DvDateTime add(DvDuration q) {
    if (!getDiffType().isInstance(q)) {
        throw new IllegalArgumentException("invalid difference type");
    }/*w ww . j  a  va2  s . c om*/
    DvDuration d = (DvDuration) q;
    MutableDateTime mdate = getDateTime().toMutableDateTimeISO();
    mdate.add(d.getPeriod());

    return new DvDateTime(getOtherReferenceRanges(), getNormalRange(), getNormalStatus(), getAccuracy(),
            getMagnitudeStatus(), mdate.toDateTimeISO(), this.toString());
}

From source file:org.openehr.rm.datatypes.quantity.datetime.DvTime.java

License:LGPL

@Override
public DvTime add(DvDuration q) {
    if (!getDiffType().isInstance(q)) {
        throw new IllegalArgumentException("invalid difference type");
    }//  w w  w  . java2 s .c om
    DvDuration d = (DvDuration) q;
    MutableDateTime mdate = getDateTime().toMutableDateTimeISO();
    mdate.add(d.getPeriod());
    return new DvTime(getOtherReferenceRanges(), getNormalRange(), getNormalStatus(), getAccuracy(),
            getMagnitudeStatus(), mdate.toDateTimeISO(), this.toString());
}

From source file:org.springframework.analytics.metrics.redis.RedisAggregateCounterRepository.java

License:Apache License

/**
 * For each query, we need to convert the interval into two variations. One is the start and end points rounded to
 * the resolution (used to calculate the number of entries to be returned from the query). The second is the start
 * and end buckets we have to retrieve which may contain entries for the interval. For example, when querying
 * at day resolution, the number of entries is the number of Joda time days between the start (rounded down to a
 * day boundary) and the end plus one day (also rounded down). However, we need load the data from the buckets
 * from the month the start day occurs in to the month end day occurs in. These are then concatenated, using the
 * start day as the start index into the first array, and writing the total number of entries in sequence from that
 * point into the combined result counts array.
 *//*from   ww  w  . ja va 2 s .  c om*/
@Override
public AggregateCounter getCounts(String name, Interval interval, AggregateCounterResolution resolution) {

    DateTime end = interval.getEnd();
    Chronology c = interval.getChronology();

    long[] counts;

    if (resolution == AggregateCounterResolution.minute) {
        // Iterate through each hour in the interval and load the minutes for it
        MutableDateTime dt = new MutableDateTime(interval.getStart());
        dt.setRounding(c.hourOfDay());
        Duration step = Duration.standardHours(1);
        List<long[]> hours = new ArrayList<long[]>();
        while (dt.isBefore(end) || dt.isEqual(end)) {
            hours.add(getMinCountsForHour(name, dt));
            dt.add(step);
        }
        counts = MetricUtils.concatArrays(hours, interval.getStart().getMinuteOfHour(),
                interval.toPeriod().toStandardMinutes().getMinutes() + 1);

    } else if (resolution == AggregateCounterResolution.hour) {
        DateTime cursor = new DateTime(c.dayOfMonth().roundFloor(interval.getStart().getMillis()));
        List<long[]> days = new ArrayList<long[]>();
        Duration step = Duration.standardHours(24);
        while (cursor.isBefore(end)) {
            days.add(getHourCountsForDay(name, cursor));
            cursor = cursor.plus(step);
        }

        counts = MetricUtils.concatArrays(days, interval.getStart().getHourOfDay(),
                interval.toPeriod().toStandardHours().getHours() + 1);

    } else if (resolution == AggregateCounterResolution.day) {
        DateTime startDay = new DateTime(c.dayOfYear().roundFloor(interval.getStart().getMillis()));
        DateTime endDay = new DateTime(c.dayOfYear().roundFloor(end.plusDays(1).getMillis()));
        int nDays = Days.daysBetween(startDay, endDay).getDays();
        DateTime cursor = new DateTime(c.monthOfYear().roundFloor(interval.getStart().getMillis()));
        List<long[]> months = new ArrayList<long[]>();
        DateTime endMonth = new DateTime(
                c.monthOfYear().roundCeiling(interval.getEnd().plusMonths(1).getMillis()));
        while (cursor.isBefore(endMonth)) {
            months.add(getDayCountsForMonth(name, cursor));
            cursor = cursor.plusMonths(1);
        }

        counts = MetricUtils.concatArrays(months, interval.getStart().getDayOfMonth() - 1, nDays);
    } else if (resolution == AggregateCounterResolution.month) {
        DateTime startMonth = new DateTime(c.monthOfYear().roundFloor(interval.getStartMillis()));
        DateTime endMonth = new DateTime(c.monthOfYear().roundFloor(end.plusMonths(1).getMillis()));
        int nMonths = Months.monthsBetween(startMonth, endMonth).getMonths();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> years = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(interval.getEnd().plusYears(1).getMillis()));
        while (cursor.isBefore(endYear)) {
            years.add(getMonthCountsForYear(name, cursor));
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(years, interval.getStart().getMonthOfYear() - 1, nMonths);
    } else if (resolution == AggregateCounterResolution.year) {
        DateTime startYear = new DateTime(interval.getStart().getYear(), 1, 1, 0, 0);
        DateTime endYear = new DateTime(end.getYear() + 1, 1, 1, 0, 0);
        int nYears = Years.yearsBetween(startYear, endYear).getYears();
        Map<String, Long> yearCounts = getYearCounts(name);
        counts = new long[nYears];

        for (int i = 0; i < nYears; i++) {
            int year = startYear.plusYears(i).getYear();
            Long count = yearCounts.get(Integer.toString(year));
            if (count == null) {
                count = 0L;
            }
            counts[i] = count;
        }
    } else {
        throw new IllegalStateException("Shouldn't happen. Unhandled resolution: " + resolution);
    }
    return new AggregateCounter(name, interval, counts, resolution);
}

From source file:org.springframework.xd.analytics.metrics.redis.RedisAggregateCounterRepository.java

License:Apache License

/**
 * For each query, we need to convert the interval into two variations. One is the start and end points rounded to
 * the resolution (used to calculate the number of entries to be returned from the query). The second is the start
 * and end buckets we have to retrieve which may contain entries for the interval. For example, when querying
 * at day resolution, the number of entries is the number of Joda time days between the start (rounded down to a
 * day boundary) and the end plus one day (also rounded down). However, we need load the data from the buckets
 * from the month the start day occurs in to the month end day occurs in. These are then concatenated, using the
 * start day as the start index into the first array, and writing the total number of entries in sequence from that
 * point into the combined result counts array.
 *///www  . j  a v a  2  s.  c o  m
@Override
public AggregateCount getCounts(String name, Interval interval, AggregateCountResolution resolution) {

    DateTime end = interval.getEnd();
    Chronology c = interval.getChronology();

    long[] counts;

    if (resolution == AggregateCountResolution.minute) {
        // Iterate through each hour in the interval and load the minutes for it
        MutableDateTime dt = new MutableDateTime(interval.getStart());
        dt.setRounding(c.hourOfDay());
        Duration step = Duration.standardHours(1);
        List<long[]> hours = new ArrayList<long[]>();
        while (dt.isBefore(end) || dt.isEqual(end)) {
            hours.add(getMinCountsForHour(name, dt));
            dt.add(step);
        }
        counts = MetricUtils.concatArrays(hours, interval.getStart().getMinuteOfHour(),
                interval.toPeriod().toStandardMinutes().getMinutes() + 1);

    } else if (resolution == AggregateCountResolution.hour) {
        DateTime cursor = new DateTime(c.dayOfMonth().roundFloor(interval.getStart().getMillis()));
        List<long[]> days = new ArrayList<long[]>();
        Duration step = Duration.standardHours(24);
        while (cursor.isBefore(end)) {
            days.add(getHourCountsForDay(name, cursor));
            cursor = cursor.plus(step);
        }

        counts = MetricUtils.concatArrays(days, interval.getStart().getHourOfDay(),
                interval.toPeriod().toStandardHours().getHours() + 1);

    } else if (resolution == AggregateCountResolution.day) {
        DateTime startDay = new DateTime(c.dayOfYear().roundFloor(interval.getStart().getMillis()));
        DateTime endDay = new DateTime(c.dayOfYear().roundFloor(end.plusDays(1).getMillis()));
        int nDays = Days.daysBetween(startDay, endDay).getDays();
        DateTime cursor = new DateTime(c.monthOfYear().roundFloor(interval.getStart().getMillis()));
        List<long[]> months = new ArrayList<long[]>();
        DateTime endMonth = new DateTime(
                c.monthOfYear().roundCeiling(interval.getEnd().plusMonths(1).getMillis()));
        while (cursor.isBefore(endMonth)) {
            months.add(getDayCountsForMonth(name, cursor));
            cursor = cursor.plusMonths(1);
        }

        counts = MetricUtils.concatArrays(months, interval.getStart().getDayOfMonth() - 1, nDays);
    } else if (resolution == AggregateCountResolution.month) {
        DateTime startMonth = new DateTime(c.monthOfYear().roundFloor(interval.getStartMillis()));
        DateTime endMonth = new DateTime(c.monthOfYear().roundFloor(end.plusMonths(1).getMillis()));
        int nMonths = Months.monthsBetween(startMonth, endMonth).getMonths();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> years = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(interval.getEnd().plusYears(1).getMillis()));
        while (cursor.isBefore(endYear)) {
            years.add(getMonthCountsForYear(name, cursor));
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(years, interval.getStart().getMonthOfYear() - 1, nMonths);
    } else if (resolution == AggregateCountResolution.year) {
        DateTime startYear = new DateTime(interval.getStart().getYear(), 1, 1, 0, 0);
        DateTime endYear = new DateTime(end.getYear() + 1, 1, 1, 0, 0);
        int nYears = Years.yearsBetween(startYear, endYear).getYears();
        Map<String, Long> yearCounts = getYearCounts(name);
        counts = new long[nYears];

        for (int i = 0; i < nYears; i++) {
            int year = startYear.plusYears(i).getYear();
            Long count = yearCounts.get(Integer.toString(year));
            if (count == null) {
                count = 0L;
            }
            counts[i] = count;
        }
    } else {
        throw new IllegalStateException("Shouldn't happen. Unhandled resolution: " + resolution);
    }
    return new AggregateCount(name, interval, counts, resolution);
}