Example usage for org.joda.time Period toDurationFrom

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

Introduction

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

Prototype

public Duration toDurationFrom(ReadableInstant startInstant) 

Source Link

Document

Gets the total millisecond duration of this period relative to a start instant.

Usage

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//www  .  j  a  v  a 2s.  c om
 * @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 2 s.  c  o 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.wealdtech.utils.PeriodOrdering.java

License:Open Source License

@Override
public int compare(final Period left, final Period right) {
    return left.toDurationFrom(COMPARISONBASE).compareTo(right.toDurationFrom(COMPARISONBASE));
}

From source file:io.warp10.script.functions.DURATION.java

License:Apache License

@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {

    Object o = stack.pop();//from  w  w  w  . jav  a2  s . c o  m

    if (!(o instanceof String)) {
        throw new WarpScriptException(getName()
                + " expects an ISO8601 duration (a string) on top of the stack. See http://en.wikipedia.org/wiki/ISO_8601#Durations");
    }

    ReadWritablePeriod period = new MutablePeriod();

    ISOPeriodFormat.standard().getParser().parseInto(period, o.toString(), 0, Locale.US);

    Period p = period.toPeriod();

    if (p.getMonths() != 0 || p.getYears() != 0) {
        throw new WarpScriptException(getName()
                + " doesn't support ambiguous durations containing years or months, please convert those to days.");
    }

    Duration duration = p.toDurationFrom(new Instant());

    stack.push(duration.getMillis() * Constants.TIME_UNITS_PER_MS);

    return stack;
}

From source file:net.sf.janos.util.TimeUtilities.java

License:Apache License

/**
 * @param duration/*from  w w  w.j a va2 s .  c  om*/
 *          the UPNP representation of the duration
 * @return the java Date <code>long</code> style representation of the
 *         duration, or -1 if duration is NOT_IMPLEMENTED.
 */
public static long convertDurationToLong(String duration) {
    if ("NOT_IMPLEMENTED".equals(duration) || "".equals(duration) || duration == null) {
        return -1;
    }
    // TODO there's also an "END_OF_MEDIA" thing...
    Period period = periodFormatter.parsePeriod(duration);
    return period.toDurationFrom(new Instant()).getMillis();
}

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 .  ja 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.sleuthkit.autopsy.timeline.db.EventDB.java

License:Open Source License

/**
 * merge the events in the given list if they are within the same period
 * General algorithm is as follows:/* ww  w.j a  va  2s.  c  o  m*/
 *
 * 1) sort them into a map from (type, description)-> List<aggevent>
 * 2) for each key in map, merge the events and accumulate them in a list to
 * return
 *
 * @param timeUnitLength
 * @param preMergedEvents
 *
 * @return
 */
static private List<EventStripe> mergeClustersToStripes(Period timeUnitLength,
        List<EventCluster> preMergedEvents) {

    //effectively map from type to (map from description to events)
    Map<EventType, SetMultimap<String, EventCluster>> typeMap = new HashMap<>();

    for (EventCluster aggregateEvent : preMergedEvents) {
        typeMap.computeIfAbsent(aggregateEvent.getEventType(), eventType -> HashMultimap.create())
                .put(aggregateEvent.getDescription(), aggregateEvent);
    }
    //result list to return
    ArrayList<EventCluster> aggEvents = new ArrayList<>();

    //For each (type, description) key, merge agg events
    for (SetMultimap<String, EventCluster> descrMap : typeMap.values()) {
        //for each description ...
        for (String descr : descrMap.keySet()) {
            //run through the sorted events, merging together adjacent events
            Iterator<EventCluster> iterator = descrMap.get(descr).stream()
                    .sorted(Comparator.comparing(event -> event.getSpan().getStartMillis())).iterator();
            EventCluster current = iterator.next();
            while (iterator.hasNext()) {
                EventCluster next = iterator.next();
                Interval gap = current.getSpan().gap(next.getSpan());

                //if they overlap or gap is less one quarter timeUnitLength
                //TODO: 1/4 factor is arbitrary. review! -jm
                if (gap == null || gap.toDuration()
                        .getMillis() <= timeUnitLength.toDurationFrom(gap.getStart()).getMillis() / 4) {
                    //merge them
                    current = EventCluster.merge(current, next);
                } else {
                    //done merging into current, set next as new current
                    aggEvents.add(current);
                    current = next;
                }
            }
            aggEvents.add(current);
        }
    }

    //merge clusters to stripes
    Map<ImmutablePair<EventType, String>, EventStripe> stripeDescMap = new HashMap<>();

    for (EventCluster eventCluster : aggEvents) {
        stripeDescMap.merge(ImmutablePair.of(eventCluster.getEventType(), eventCluster.getDescription()),
                new EventStripe(eventCluster), EventStripe::merge);
    }

    return stripeDescMap.values().stream().sorted(Comparator.comparing(EventStripe::getStartMillis))
            .collect(Collectors.toList());
}

From source file:org.sleuthkit.autopsy.timeline.events.db.EventDB.java

License:Open Source License

/**
 * //TODO: update javadoc //TODO: split this into helper methods
 *
 * get a list of {@link AggregateEvent}s.
 *
 * General algorithm is as follows://from w w  w.  ja v  a  2  s.co m
 *
 * - get all aggregate events, via one db query.
 * - sort them into a map from (type, description)-> aggevent
 * - for each key in map, merge the events and accumulate them in a list
 * to return
 *
 *
 * @param timeRange the Interval within in which all returned aggregate
 *                  events will be.
 * @param filter    only events that pass the filter will be included in
 *                  aggregates events returned
 * @param zoomLevel only events of this level will be included
 * @param lod       description level of detail to use when grouping events
 *
 *
 * @return a list of aggregate events within the given timerange, that pass
 *         the supplied filter, aggregated according to the given event type and
 *         description zoom levels
 */
private List<AggregateEvent> getAggregatedEvents(Interval timeRange, Filter filter,
        EventTypeZoomLevel zoomLevel, DescriptionLOD lod) {
    String descriptionColumn = getDescriptionColumn(lod);
    final boolean useSubTypes = (zoomLevel.equals(EventTypeZoomLevel.SUB_TYPE));

    //get some info about the time range requested
    RangeDivisionInfo rangeInfo = RangeDivisionInfo.getRangeDivisionInfo(timeRange);
    //use 'rounded out' range
    long start = timeRange.getStartMillis() / 1000;//.getLowerBound();
    long end = timeRange.getEndMillis() / 1000;//Millis();//rangeInfo.getUpperBound();
    if (Objects.equals(start, end)) {
        end++;
    }

    //get a sqlite srtftime format string
    String strfTimeFormat = getStrfTimeFormat(rangeInfo.getPeriodSize());

    //effectively map from type to (map from description to events)
    Map<EventType, SetMultimap<String, AggregateEvent>> typeMap = new HashMap<>();

    //get all agregate events in this time unit
    dbReadLock();
    String query = "select strftime('" + strfTimeFormat + "',time , 'unixepoch'"
            + (TimeLineController.getTimeZone().get().equals(TimeZone.getDefault()) ? ", 'localtime'" : "")
            + ") as interval,  group_concat(event_id) as event_ids, Min(time), Max(time),  " + descriptionColumn
            + ", " + (useSubTypes ? SUB_TYPE_COLUMN : BASE_TYPE_COLUMN) // NON-NLS
            + " from events where time >= " + start + " and time < " + end + " and " + getSQLWhere(filter) // NON-NLS
            + " group by interval, " + (useSubTypes ? SUB_TYPE_COLUMN : BASE_TYPE_COLUMN) + " , "
            + descriptionColumn // NON-NLS
            + " order by Min(time)"; // NON-NLS
    //System.out.println(query);
    ResultSet rs = null;
    try (Statement stmt = con.createStatement(); // scoop up requested events in groups organized by interval, type, and desription
    ) {

        Stopwatch stopwatch = new Stopwatch();
        stopwatch.start();

        rs = stmt.executeQuery(query);
        stopwatch.stop();
        //System.out.println(stopwatch.elapsedMillis() / 1000.0 + " seconds");
        while (rs.next()) {
            EventType type = useSubTypes ? RootEventType.allTypes.get(rs.getInt(SUB_TYPE_COLUMN))
                    : BaseTypes.values()[rs.getInt(BASE_TYPE_COLUMN)];

            AggregateEvent aggregateEvent = new AggregateEvent(
                    new Interval(rs.getLong("Min(time)") * 1000, rs.getLong("Max(time)") * 1000,
                            TimeLineController.getJodaTimeZone()), // NON-NLS
                    type, Arrays.asList(rs.getString("event_ids").split(",")), // NON-NLS
                    rs.getString(descriptionColumn), lod);

            //put events in map from type/descrition -> event
            SetMultimap<String, AggregateEvent> descrMap = typeMap.get(type);
            if (descrMap == null) {
                descrMap = HashMultimap.<String, AggregateEvent>create();
                typeMap.put(type, descrMap);
            }
            descrMap.put(aggregateEvent.getDescription(), aggregateEvent);
        }

    } catch (SQLException ex) {
        Exceptions.printStackTrace(ex);
    } finally {
        try {
            rs.close();
        } catch (SQLException ex) {
            Exceptions.printStackTrace(ex);
        }
        dbReadUnlock();
    }

    //result list to return
    ArrayList<AggregateEvent> aggEvents = new ArrayList<>();

    //save this for use when comparing gap size
    Period timeUnitLength = rangeInfo.getPeriodSize().getPeriod();

    //For each (type, description) key, merge agg events
    for (SetMultimap<String, AggregateEvent> descrMap : typeMap.values()) {
        for (String descr : descrMap.keySet()) {
            //run through the sorted events, merging together adjacent events
            Iterator<AggregateEvent> iterator = descrMap.get(descr).stream()
                    .sorted((AggregateEvent o1, AggregateEvent o2) -> Long
                            .compare(o1.getSpan().getStartMillis(), o2.getSpan().getStartMillis()))
                    .iterator();
            AggregateEvent current = iterator.next();
            while (iterator.hasNext()) {
                AggregateEvent next = iterator.next();
                Interval gap = current.getSpan().gap(next.getSpan());

                //if they overlap or gap is less one quarter timeUnitLength
                //TODO: 1/4 factor is arbitrary. review! -jm
                if (gap == null || gap.toDuration()
                        .getMillis() <= timeUnitLength.toDurationFrom(gap.getStart()).getMillis() / 4) {
                    //merge them
                    current = AggregateEvent.merge(current, next);
                } else {
                    //done merging into current, set next as new current
                    aggEvents.add(current);
                    current = next;
                }
            }
            aggEvents.add(current);
        }
    }

    //at this point we should have a list of aggregate events.
    //one per type/description spanning consecutive time units as determined in rangeInfo
    return aggEvents;
}

From source file:org.tensin.sonos.helpers.TimeUtilities.java

License:Apache License

/**
 * Convert duration to long.//from   w w w .j a  va 2s  . co  m
 * 
 * @param duration
 *            the UPNP representation of the duration
 * @return the java Date <code>long</code> style representation of the
 *         duration, or -1 if duration is NOT_IMPLEMENTED.
 */
public static long convertDurationToLong(final String duration) {
    if ("NOT_IMPLEMENTED".equals(duration) || "".equals(duration) || (duration == null)) {
        return -1;
    }
    // TODO there's also an "END_OF_MEDIA" thing...
    final Period period = periodFormatter.parsePeriod(duration);
    return period.toDurationFrom(new Instant()).getMillis();
}