Example usage for org.joda.time Interval toDuration

List of usage examples for org.joda.time Interval toDuration

Introduction

In this page you can find the example usage for org.joda.time Interval toDuration.

Prototype

public Duration toDuration() 

Source Link

Document

Gets the duration of this time interval.

Usage

From source file:com.yahoo.bard.webservice.web.apirequest.ApiRequestImpl.java

License:Apache License

/**
 * Extracts the set of intervals from the api request.
 *
 * @param now The 'now' for which time macros will be relatively calculated
 * @param apiIntervalQuery  API string containing the intervals in ISO 8601 format, values separated by ','.
 * @param granularity  The granularity to generate the date based on period or macros.
 * @param dateTimeFormatter  The formatter to parse date time interval segments
 *
 * @return Set of jodatime interval objects.
 * @throws BadApiRequestException if the requested interval is not found.
 *//*from  w  w  w .jav  a  2 s  . com*/
protected static List<Interval> generateIntervals(DateTime now, String apiIntervalQuery,
        Granularity granularity, DateTimeFormatter dateTimeFormatter) throws BadApiRequestException {
    try (TimedPhase timer = RequestLog.startTiming("GeneratingIntervals")) {
        List<Interval> generated = new ArrayList<>();
        if (apiIntervalQuery == null || apiIntervalQuery.equals("")) {
            LOG.debug(INTERVAL_MISSING.logFormat());
            throw new BadApiRequestException(INTERVAL_MISSING.format());
        }
        List<String> apiIntervals = Arrays.asList(apiIntervalQuery.split(","));
        // Split each interval string into the start and stop instances, parse them, and add the interval to the
        // list

        for (String apiInterval : apiIntervals) {
            String[] split = apiInterval.split("/");

            // Check for both a start and a stop
            if (split.length != 2) {
                String message = "Start and End dates are required.";
                LOG.debug(INTERVAL_INVALID.logFormat(apiIntervalQuery, message));
                throw new BadApiRequestException(INTERVAL_INVALID.format(apiIntervalQuery, message));
            }

            try {
                String start = split[0].toUpperCase(Locale.ENGLISH);
                String end = split[1].toUpperCase(Locale.ENGLISH);
                //If start & end intervals are period then marking as invalid interval.
                //Becacuse either one should be macro or actual date to generate an interval
                if (start.startsWith("P") && end.startsWith("P")) {
                    LOG.debug(INTERVAL_INVALID.logFormat(start));
                    throw new BadApiRequestException(INTERVAL_INVALID.format(apiInterval));
                }

                Interval interval;
                //If start interval is period, then create new interval with computed end date
                //possible end interval could be next,current, date
                if (start.startsWith("P")) {
                    interval = new Interval(Period.parse(start),
                            getAsDateTime(now, granularity, split[1], dateTimeFormatter));
                    //If end string is period, then create an interval with the computed start date
                    //Possible start & end string could be a macro or an ISO 8601 DateTime
                } else if (end.startsWith("P")) {
                    interval = new Interval(getAsDateTime(now, granularity, split[0], dateTimeFormatter),
                            Period.parse(end));
                } else {
                    //start and end interval could be either macros or actual datetime
                    interval = new Interval(getAsDateTime(now, granularity, split[0], dateTimeFormatter),
                            getAsDateTime(now, granularity, split[1], dateTimeFormatter));
                }

                // Zero length intervals are invalid
                if (interval.toDuration().equals(Duration.ZERO)) {
                    LOG.debug(INTERVAL_ZERO_LENGTH.logFormat(apiInterval));
                    throw new BadApiRequestException(INTERVAL_ZERO_LENGTH.format(apiInterval));
                }
                generated.add(interval);
            } catch (IllegalArgumentException iae) {
                // Handle poor JodaTime message (special case)
                String internalMessage = iae.getMessage().equals("The end instant must be greater the start")
                        ? "The end instant must be greater than the start instant"
                        : iae.getMessage();
                LOG.debug(INTERVAL_INVALID.logFormat(apiIntervalQuery, internalMessage), iae);
                throw new BadApiRequestException(INTERVAL_INVALID.format(apiIntervalQuery, internalMessage),
                        iae);
            }
        }
        return generated;
    }
}

From source file:com.yahoo.bard.webservice.web.DataApiRequest.java

License:Apache License

/**
 * Extracts the set of intervals from the api request.
 *
 * @param apiIntervalQuery  API string containing the intervals in ISO 8601 format, values separated by ','.
 * @param granularity  The granularity to generate the date based on period or macros.
 * @param dateTimeFormatter  The formatter to parse date time interval segments
 *
 * @return Set of jodatime interval objects.
 * @throws BadApiRequestException if the requested interval is not found.
 *///ww  w. jav  a 2  s .  com
protected static Set<Interval> generateIntervals(String apiIntervalQuery, Granularity granularity,
        DateTimeFormatter dateTimeFormatter) throws BadApiRequestException {
    Set<Interval> generated = new LinkedHashSet<>();
    if (apiIntervalQuery == null || apiIntervalQuery.equals("")) {
        LOG.debug(INTERVAL_MISSING.logFormat());
        throw new BadApiRequestException(INTERVAL_MISSING.format());
    }
    List<String> apiIntervals = Arrays.asList(apiIntervalQuery.split(","));
    // Split each interval string into the start and stop instances, parse them, and add the interval to the list
    for (String apiInterval : apiIntervals) {
        String[] split = apiInterval.split("/");

        // Check for both a start and a stop
        if (split.length != 2) {
            String message = "Start and End dates are required.";
            LOG.debug(INTERVAL_INVALID.logFormat(apiIntervalQuery, message));
            throw new BadApiRequestException(INTERVAL_INVALID.format(apiIntervalQuery, message));
        }

        try {
            String start = split[0].toUpperCase(Locale.ENGLISH);
            String end = split[1].toUpperCase(Locale.ENGLISH);
            //If start & end intervals are period then marking as invalid interval.
            //Becacuse either one should be macro or actual date to generate an interval
            if (start.startsWith("P") && end.startsWith("P")) {
                LOG.debug(INTERVAL_INVALID.logFormat(start));
                throw new BadApiRequestException(INTERVAL_INVALID.format(apiInterval));
            }

            Interval interval;
            DateTime now = new DateTime();
            //If start interval is period, then create new interval with computed end date
            //possible end interval could be next,current, date
            if (start.startsWith("P")) {
                interval = new Interval(Period.parse(start),
                        getAsDateTime(now, granularity, split[1], dateTimeFormatter));
                //If end string is period, then create an interval with the computed start date
                //Possible start & end string could be a macro or an ISO 8601 DateTime
            } else if (end.startsWith("P")) {
                interval = new Interval(getAsDateTime(now, granularity, split[0], dateTimeFormatter),
                        Period.parse(end));
            } else {
                //start and end interval could be either macros or actual datetime
                interval = new Interval(getAsDateTime(now, granularity, split[0], dateTimeFormatter),
                        getAsDateTime(now, granularity, split[1], dateTimeFormatter));
            }

            // Zero length intervals are invalid
            if (interval.toDuration().equals(Duration.ZERO)) {
                LOG.debug(INTERVAL_ZERO_LENGTH.logFormat(apiInterval));
                throw new BadApiRequestException(INTERVAL_ZERO_LENGTH.format(apiInterval));
            }
            generated.add(interval);
        } catch (IllegalArgumentException iae) {
            LOG.debug(INTERVAL_INVALID.logFormat(apiIntervalQuery, iae.getMessage()), iae);
            throw new BadApiRequestException(INTERVAL_INVALID.format(apiIntervalQuery, iae.getMessage()), iae);
        }
    }
    return generated;
}

From source file:de.avanux.smartapplianceenabler.appliance.RunningTimeMonitor.java

License:Open Source License

/**
 * Updates remainingMinRunningTime for the given instant. The value may become negative!
 * Subsequent calls to this method within one second are omitted.
 * @param now/*from  w w  w . j  av  a2 s  .  co m*/
 */
protected void update(LocalDateTime now) {
    // update not more than once per second in order to avoid spamming the log
    if (lastUpdate == null || now.isBefore(lastUpdate)
            || new Interval(lastUpdate.toDateTime(), now.toDateTime()).toDurationMillis() > 1000) {
        activateTimeframeInterval(now, schedules);
        deactivateExpiredTimeframeInterval(now);
        logger.debug("activeTimeframeInterval=" + activeTimeframeInterval + " statusChangedAt="
                + statusChangedAt + " intervalBegin=" + intervalBegin + " running=" + running);

        Interval interval = null;
        if (running) {
            // running
            if (intervalBegin == null) {
                // running was set to true after interval begin
                interval = new Interval(statusChangedAt.toDateTime(), now.toDateTime());
            } else {
                // no status change in interval
                interval = new Interval(intervalBegin.toDateTime(), now.toDateTime());
            }
            intervalBegin = now;
        } else if (intervalBegin != null && statusChangedAt != null) {
            // running was set to false after interval begin
            interval = new Interval(intervalBegin.toDateTime(), statusChangedAt.toDateTime());
            intervalBegin = null;
            statusChangedAt = null;
        }
        if (interval != null && remainingMinRunningTime != null && remainingMaxRunningTime != null) {
            int intervalSeconds = Double.valueOf(interval.toDuration().getMillis() / 1000).intValue();
            remainingMinRunningTime = remainingMinRunningTime - intervalSeconds;
            remainingMaxRunningTime = remainingMaxRunningTime - intervalSeconds;
        }
        lastUpdate = now;
    }
}

From source file:de.iteratec.iteraplan.model.RuntimePeriod.java

License:Open Source License

/**
 * @return Returns {@code true}, if this period is completely contained in the given period
 *         (inclusive at the start and end). If the given period is {@code null} (i.e.
 *         {@link BaseDateUtils#MIN_DATE} and {@link BaseDateUtils#MAX_DATE} is assumed), the test returns
 *         {@code true}.//  www .j a  va2 s  . c  o  m
 */
public boolean withinPeriod(RuntimePeriod period) {

    if (period == null) {
        return true;
    }

    Interval other = DateUtils.asInterval(period.getStart(), period.getEnd());
    Interval thiz = asInterval();

    Interval overlap = thiz.overlap(other);

    if (overlap == null) {
        return false;
    }

    return overlap.toDuration().equals(thiz.toDuration()) ? true : false;
}

From source file:dk.dma.ais.view.rest.AisStoreResource.java

License:Apache License

/**
 * Search data from AisStore and generate KMZ output.
 * /*  ww w  .  j  a  v  a2  s . c o  m*/
 * @param area
 *            extract AisPackets from AisStore inside this area.
 * @param interval
 *            extract AisPackets from AisStore inside this time interval.
 * @param title
 *            Stamp this title into the generated KML (optional).
 * @param description
 *            Stamp this description into the generated KML (optional).
 * @param primaryMmsi
 *            Style this MMSI as the primary target in the scenario
 *            (optional).
 * @param secondaryMmsi
 *            Style this MMSI as the secondary target in the scenario
 *            (optional).
 * @param snapshotAt
 *            Generate a KML snapshot folder for exactly this point in time
 *            (optional).
 * @param interpolationStepSecs
 *            Interpolate targets between AisPackets using this time step in
 *            seconds (optional).
 * @return HTTP response carrying KML for Google Earth
 */
@SuppressWarnings("unchecked")
private Response scenarioKmz(final BoundingBox area, final Interval interval, final String title,
        final String description, final boolean createSituationFolder, final boolean createMovementsFolder,
        final boolean createTracksFolder, final Integer primaryMmsi, final Integer secondaryMmsi,
        final DateTime snapshotAt, final Integer interpolationStepSecs) {

    // Pre-check input
    final Duration duration = interval.toDuration();
    final long hours = duration.getStandardHours();
    final long minutes = duration.getStandardMinutes();
    if (hours > 60) {
        throw new IllegalArgumentException("Queries spanning more than 6 hours are not allowed.");
    }

    final float size = area.getArea();
    if (size > 2500.0 * 1e6) {
        throw new IllegalArgumentException(
                "Queries spanning more than 2500 square kilometers are not allowed.");
    }

    LOG.info("Preparing KML for span of " + hours + " hours + " + minutes + " minutes and " + (float) size
            + " square kilometers.");

    // Create the query
    //AisStoreQueryBuilder b = AisStoreQueryBuilder.forTime(); // Cannot use
    // getArea
    // because this
    // removes all
    // type 5
    AisStoreQueryBuilder b = AisStoreQueryBuilder.forArea(area);
    b.setFetchSize(200);

    b.setInterval(interval);

    // Execute the query
    AisStoreQueryResult queryResult = get(CassandraConnection.class).execute(b);

    // Apply filters
    Iterable<AisPacket> filteredQueryResult = Iterables.filter(queryResult,
            AisPacketFilters.filterOnMessageId(1, 2, 3, 5, 18, 19, 24));
    filteredQueryResult = Iterables.filter(filteredQueryResult,
            AisPacketFilters.filterRelaxedOnMessagePositionWithin(area));

    if (!filteredQueryResult.iterator().hasNext()) {
        LOG.warn("No AIS data matching criteria.");
    }

    Predicate<? super AisPacket> isPrimaryMmsi = primaryMmsi == null ? e -> true
            : aisPacket -> aisPacket.tryGetAisMessage().getUserId() == primaryMmsi.intValue();

    Predicate<? super AisPacket> isSecondaryMmsi = secondaryMmsi == null ? e -> true
            : aisPacket -> aisPacket.tryGetAisMessage().getUserId() == secondaryMmsi.intValue();

    Predicate<? super AisPacket> triggerSnapshot = snapshotAt != null ? new Predicate<AisPacket>() {
        private final long snapshotAtMillis = snapshotAt.getMillis();
        private boolean snapshotGenerated;

        @Override
        public boolean test(AisPacket aisPacket) {
            boolean generateSnapshot = false;
            if (!snapshotGenerated) {
                if (aisPacket.getBestTimestamp() >= snapshotAtMillis) {
                    generateSnapshot = true;
                    snapshotGenerated = true;
                }
            }
            return generateSnapshot;
        }
    } : e -> true;

    Supplier<? extends String> supplySnapshotDescription = () -> {
        return "<table width=\"300\"><tr><td><h4>" + title + "</h4></td></tr><tr><td><p>" + description
                + "</p></td></tr></table>";
    };

    Supplier<? extends String> supplyTitle = title != null ? () -> title : null;

    Supplier<? extends String> supplyDescription = description != null ? () -> description : null;

    Supplier<? extends Integer> supplyInterpolationStep = interpolationStepSecs != null
            ? () -> interpolationStepSecs
            : null;

    final OutputStreamSink<AisPacket> kmzSink = AisPacketOutputSinks.newKmzSink(e -> true,
            createSituationFolder, createMovementsFolder, createTracksFolder, isPrimaryMmsi, isSecondaryMmsi,
            triggerSnapshot, supplySnapshotDescription, supplyInterpolationStep, supplyTitle, supplyDescription,
            null);

    return Response.ok().entity(StreamingUtil.createStreamingOutput(filteredQueryResult, kmzSink))
            .type(MEDIA_TYPE_KMZ).header("Content-Disposition", "attachment; filename = \"scenario.kmz\"")
            .build();
}

From source file:edu.wpi.cs.wpisuitetng.modules.cal.models.data.Event.java

License:Open Source License

@Override
public void setTime(DateTime newTime) {
    if (new Interval(new DateTime(this.start), new DateTime(this.end)).contains(newTime)) {
        //this is what stops the events from being dragged to the next day. leaving it in case we might want it later
        //return;
    }//  www  .  j ava2  s.  co  m

    Interval i;
    int daysBetween = 0;
    if (new DateTime(this.start).isAfter(newTime)) {
        i = new Interval(newTime, new DateTime(this.start));
        daysBetween = 0 - (int) i.toDuration().getStandardDays();
    } else {
        i = new Interval(new DateTime(this.start), newTime);
        daysBetween = (int) i.toDuration().getStandardDays();
    }

    MutableDateTime newEnd = new MutableDateTime(this.end);
    newEnd.addDays(daysBetween);

    MutableDateTime newStart = new MutableDateTime(this.start);
    newStart.addDays(daysBetween);

    this.end = newEnd.toDate();
    this.start = newStart.toDate();

}

From source file:edu.wpi.cs.wpisuitetng.modules.cal.ui.views.week.WeekCalendar.java

License:Open Source License

/**
 * Selects an event's corresponding Displayable
 * //from  w w w  .  j a  v a2 s.  c om
 * @param on
 *            Event being selected
 * @param setTo
 *            Displayable of Event being selected
 */
private void selectEvents(Event on, Displayable setTo) {
    // TODO: refactor this pattern
    DayPanel mLouvreTour;
    MutableDateTime startDay = new MutableDateTime(on.getStart());
    MutableDateTime endDay = new MutableDateTime(on.getEnd());

    endDay.setMillisOfDay(0);
    endDay.addDays(1);
    endDay.addMillis(-1);
    startDay.setMillisOfDay(0);

    Interval eventLength = new Interval(startDay, endDay);
    if (setTo == null || eventLength.toDuration().getStandardHours() > 24) {
        for (WeekMultidayEventItem multidayItem : multidayItemList) {
            if (setTo != null && multidayItem.getEvent().getUuid().equals(((Event) on).getUuid()))
                multidayItem.setSelected(true);
            else
                multidayItem.setSelected(false);
        }
        return;
    }

    //TODO: can be simplified now that multiday events are handled elsewhere
    int index = 0;
    for (int i = 0; i < 7; i++) {
        if (startDay.getDayOfYear() == daysOfWeekArray[i].getDisplayDate().getDayOfYear()) {
            index = i;
            break;
        }
    }

    while (index < 7 && !endDay.isBefore(daysOfWeekArray[index].getDisplayDate())) {
        mLouvreTour = daysOfWeekArray[index];
        try {
            mLouvreTour.select(setTo);
        } catch (NullPointerException ex) {
            // silently ignore as this is apparently not in the view
        }
        index++;
    }
}

From source file:io.coala.dsol.util.TreatmentBuilder.java

License:Apache License

public TreatmentBuilder withRunInterval(final Interval interval) {
    return withStartTime(interval.getStart()).withRunLength(interval.toDuration());
}

From source file:io.druid.server.coordinator.helper.SegmentCompactorUtil.java

License:Apache License

/**
 * Return an interval for looking up for timeline.
 * If {@code totalInterval} is larger than {@link #LOOKUP_PERIOD}, it returns an interval of {@link #LOOKUP_PERIOD}
 * and the end of {@code totalInterval}.
 */// w ww.  j  a  v  a2  s.c o  m
static Interval getNextLoopupInterval(Interval totalInterval) {
    final Duration givenDuration = totalInterval.toDuration();
    return givenDuration.isLongerThan(LOOKUP_DURATION) ? new Interval(LOOKUP_PERIOD, totalInterval.getEnd())
            : totalInterval;
}

From source file:it.mesis.utility.TimeUtil.java

License:Open Source License

/**
 * giorni trascorsi da dateFrom a dateTo, se dateFrom > dateTo il risultato sar negativo.
 * (usa joda-time)/*from  w  ww  . ja v  a  2s .  co  m*/
 * @param dateFrom cannot be null
 * @param dateTo cannot be null
 * @return giorni trascorsi
 * @throws IllegalArgumentException 
 */
public static Integer daysPast(Date dateFrom, Date dateTo) throws IllegalArgumentException {

    if (dateFrom == null || dateTo == null)
        throw new IllegalArgumentException("params cannot be null.");

    boolean sign = dateFrom.compareTo(dateTo) < 0;
    Interval interval = sign ? new Interval(dateFrom.getTime(), dateTo.getTime())
            : new Interval(dateTo.getTime(), dateFrom.getTime());

    return interval.toDuration().toStandardDays().getDays() * (sign ? 1 : -1);
}