Example usage for org.joda.time DateTime minus

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

Introduction

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

Prototype

public DateTime minus(ReadablePeriod period) 

Source Link

Document

Returns a copy of this datetime with the specified period taken away.

Usage

From source file:debop4k.timeperiod.samples.TimeBlockPeriodRelationTestData.java

License:Apache License

public TimeBlockPeriodRelationTestData(DateTime start, DateTime end, Duration duration) {
    assert duration.compareTo(Duration.ZERO) >= 0 : "duration ? 0 ??? ?  .";
    reference = new TimeBlock(start, end, true);

    val beforeEnd = start.minus(duration);
    val beforeStart = beforeEnd.minus(reference.getDuration());
    val insideStart = start.plus(duration);
    val insideEnd = end.minus(duration);
    val afterStart = end.plus(duration);
    val afterEnd = afterStart.plus(reference.getDuration());

    after = new TimeBlock(beforeStart, beforeEnd, true);
    startTouching = new TimeBlock(beforeStart, start, true);
    startInside = new TimeBlock(beforeStart, insideStart, true);
    insideStartTouching = new TimeBlock(start, afterStart, true);
    enclosingStartTouching = new TimeBlock(start, insideEnd, true);
    enclosing = new TimeBlock(insideStart, insideEnd, true);
    enclosingEndTouching = new TimeBlock(insideStart, end, true);
    exactMatch = new TimeBlock(start, end, true);
    inside = new TimeBlock(beforeStart, afterEnd, true);
    insideEndTouching = new TimeBlock(beforeStart, end, true);
    endInside = new TimeBlock(insideEnd, afterEnd, true);
    endTouching = new TimeBlock(end, afterEnd, true);
    before = new TimeBlock(afterStart, afterEnd, true);

    allPeriods.addAll(Arrays.asList(reference, after, startTouching, startInside, insideStartTouching,
            enclosingStartTouching, enclosing, enclosingEndTouching, exactMatch, inside, insideEndTouching,
            endInside, endTouching, before));
}

From source file:debop4k.timeperiod.samples.TimeRangePeriodRelationTestData.java

License:Apache License

public TimeRangePeriodRelationTestData(DateTime start, DateTime end, Duration duration) {
    assert duration.compareTo(Duration.ZERO) >= 0 : "duration ? 0 ??? ?  .";
    reference = new TimeRange(start, end, true);

    val beforeEnd = start.minus(duration);
    val beforeStart = beforeEnd.minus(reference.getDuration());
    val insideStart = start.plus(duration);
    val insideEnd = end.minus(duration);
    val afterStart = end.plus(duration);
    val afterEnd = afterStart.plus(reference.getDuration());

    after = new TimeRange(beforeStart, beforeEnd, true);
    startTouching = new TimeRange(beforeStart, start, true);
    startInside = new TimeRange(beforeStart, insideStart, true);
    insideStartTouching = new TimeRange(start, afterStart, true);
    enclosingStartTouching = new TimeRange(start, insideEnd, true);
    enclosing = new TimeRange(insideStart, insideEnd, true);
    enclosingEndTouching = new TimeRange(insideStart, end, true);
    exactMatch = new TimeRange(start, end, true);
    inside = new TimeRange(beforeStart, afterEnd, true);
    insideEndTouching = new TimeRange(beforeStart, end, true);
    endInside = new TimeRange(insideEnd, afterEnd, true);
    endTouching = new TimeRange(end, afterEnd, true);
    before = new TimeRange(afterStart, afterEnd, true);

    allPeriods.addAll(Arrays.asList(reference, after, startTouching, startInside, insideStartTouching,
            enclosingStartTouching, enclosing, enclosingEndTouching, exactMatch, inside, insideEndTouching,
            endInside, endTouching, before));
}

From source file:dk.dma.epd.common.prototype.service.IntendedRouteHandlerCommon.java

License:Apache License

/**
 * Calculates the ETA for the given way point index of the given route.
 * //from   w  w w . j a v  a 2  s.  c  o  m
 * @param route
 * @param index
 * @return
 */
private DateTime getEta(Route route, int index) {

    int activeWpIndex = (route instanceof IntendedRoute) ? ((IntendedRoute) route).getActiveWpIndex()
            : ((ActiveRoute) route).getActiveWaypointIndex();

    // If the way point is after the active way point, rely on stored ETA's
    if (index >= activeWpIndex) {
        return new DateTime(route.getEtas().get(index));
    }

    // Calculate backwards from the active way point
    DateTime date = new DateTime(route.getEtas().get(activeWpIndex));
    for (int j = activeWpIndex - 1; j >= index; j--) {
        RouteLeg leg = route.getWaypoints().get(j).getOutLeg();
        date = date.minus(new Dist(DistType.NAUTICAL_MILES, leg.calcRng())
                .withSpeed(new Speed(SpeedType.KNOTS, leg.getSpeed())).in(TimeType.MILLISECONDS).longValue());
    }
    return date;
}

From source file:dk.dma.epd.ship.layers.intendedroute.IntendedRouteLayer.java

License:Apache License

private Position findPositionActiveRoute(DateTime intendedRouteETA) {

    // System.out.println("Where are we at " + intendedRouteETA);

    ActiveRoute activeRoute = EPDShip.getInstance().getRouteManager().getActiveRoute();

    // The ETA of the time is before we start our active route, or after the
    // last waypoint date
    if (intendedRouteETA.isBefore(new DateTime(activeRoute.getEtas().get(0).getTime()))

            || intendedRouteETA.isAfter(
                    new DateTime(activeRoute.getEtas().get(activeRoute.getEtas().size() - 1).getTime()))) {

        return null;
    }// w ww  . ja v  a 2  s  .  c  o m

    // Find leg we're on

    // Find start WP
    int startWP = activeRoute.getActiveWaypointIndex();
    if (startWP < 0) {
        startWP = 0;
    }

    for (int i = startWP; i < activeRoute.getWaypoints().size(); i++) {

        RouteWaypoint currentWaypoint = activeRoute.getWaypoints().get(i);

        // We are in the route
        if (new DateTime(activeRoute.getEtas().get(i).getTime()).isBefore(intendedRouteETA)) {

            // Do we have an out leg
            if (currentWaypoint.getOutLeg() != null) {

                if (new DateTime(activeRoute.getEtas().get(i + 1).getTime()).isAfter(intendedRouteETA)) {

                    // Time Left in route
                    // long secondsSailTime = (activeRoute.getEtas()
                    // .get(i + 1).getTime() - intendedRouteETA
                    // .getMillis()) / 1000;

                    long secondsSailTime = intendedRouteETA.minus(activeRoute.getEtas().get(i).getTime())
                            .getMillis() / 1000;

                    // System.out.println(intendedRouteETA.minus(
                    // activeRoute.getEtas().get(i).getTime())
                    // .getMillis() / 1000 / 60);

                    // secondsSailTime = totalTime - secondsSailTime;

                    // System.out.println("We have travelled for "
                    // + secondsSailTime / 60);

                    Date startEta = activeRoute.getEtas().get(i);
                    Date endEta = activeRoute.getEtas().get(i + 1);

                    // Try and calculate the speed
                    long milisecondsTravelTime = endEta.getTime() - startEta.getTime();

                    Position startPos = activeRoute.getWaypoints().get(i).getPos();
                    //
                    Position endPosition = activeRoute.getWaypoints().get(i + 1).getPos();
                    //

                    double lengthToTravel = Calculator.range(startPos, endPosition, Heading.RL);

                    double speed = (lengthToTravel / milisecondsTravelTime) * 1000 * 60 * 60;

                    double distanceTravelled = Calculator.distanceAfterTimeMph(speed, secondsSailTime);

                    return Calculator.findPosition(currentWaypoint.getPos(),
                            currentWaypoint.getOutLeg().calcBrg(), Converter.nmToMeters(distanceTravelled));

                }
            }
        }
    }

    // Test the leg going from own ships current position to wp 0;
    // We are in the route
    if (new DateTime(PntTime.getDate()).isBefore(intendedRouteETA)) {

        if (new DateTime(activeRoute.getEtas().get(activeRoute.getActiveWaypointIndex()).getTime())
                .isAfter(intendedRouteETA)) {

            // Time Left in route
            // long secondsSailTime = (activeRoute.getEtas()
            // .get(i + 1).getTime() - intendedRouteETA
            // .getMillis()) / 1000;

            long secondsSailTime = intendedRouteETA.minus(PntTime.getDate().getTime()).getMillis() / 1000;
            //

            // System.out.println(intendedRouteETA.minus(
            // activeRoute.getEtas().get(i).getTime())
            // .getMillis() / 1000 / 60);

            // secondsSailTime = totalTime - secondsSailTime;

            // System.out.println("We have travelled for "
            // + secondsSailTime / 60);

            Date startEta = PntTime.getDate();
            Date endEta = activeRoute.getEtas().get(activeRoute.getActiveWaypointIndex());

            // Try and calculate the speed
            long milisecondsTravelTime = endEta.getTime() - startEta.getTime();

            Position startPos = EPDShip.getInstance().getPosition();
            //
            Position endPosition = activeRoute.getWaypoints().get(activeRoute.getActiveWaypointIndex())
                    .getPos();
            //

            double lengthToTravel = Calculator.range(startPos, endPosition, Heading.RL);

            double speed = (lengthToTravel / milisecondsTravelTime) * 1000 * 60 * 60;

            double distanceTravelled = Calculator.distanceAfterTimeMph(speed, secondsSailTime);

            return Calculator.findPosition(startPos, Calculator.bearing(startPos, endPosition, Heading.RL),
                    Converter.nmToMeters(distanceTravelled));

        }
    }

    return null;

}

From source file:dk.dma.epd.ship.service.IntendedRouteHandler.java

License:Apache License

/**
 * Main thread run method. Broadcasts the intended route
 */// ww  w  .ja  v  a2s .co  m
public void run() {

    // Initialize first send
    // lastSend = new DateTime();
    // broadcastIntendedRoute();

    while (running) {

        if (routeManager != null) {

            // We have no active route, keep sleeping
            if (routeManager.getActiveRoute() == null) {
                Util.sleep(BROADCAST_TIME * 1000L);
            } else {

                // Here we handle the periodical broadcasts
                DateTime calculatedTimeOfLastSend = new DateTime();
                calculatedTimeOfLastSend = calculatedTimeOfLastSend.minus(BROADCAST_TIME * 1000L);

                // Do we need to rebroadcast based on the broadcast time
                // setting
                if (calculatedTimeOfLastSend.isAfter(lastSend)) {
                    LOG.debug("Periodically rebroadcasting");
                    broadcastIntendedRoute();
                    lastSend = new DateTime();
                } else if (lastTransmitActiveWp != null) {

                    // We check for the adaptive route broadcast here
                    // We need to compare lastTransmitActiveWp which is the
                    // last stored
                    // ETA of the waypoint we sent to the current one
                    DateTime currentActiveWaypointETA = new DateTime(
                            routeManager.getActiveRoute().getActiveWaypointEta());

                    // LOG.debug("The ETA at last transmission was : " +
                    // lastTransmitActiveWp);
                    // LOG.debug("It is now                        : " +
                    // currentActiveWaypointETA);

                    // //It can either be before or after
                    //
                    if (currentActiveWaypointETA.isAfter(lastTransmitActiveWp)
                            || currentActiveWaypointETA.isBefore(lastTransmitActiveWp)) {

                        long etaTimeChange;

                        // Is it before?
                        if (currentActiveWaypointETA.isAfter(lastTransmitActiveWp)) {

                            etaTimeChange = currentActiveWaypointETA.minus(lastTransmitActiveWp.getMillis())
                                    .getMillis();

                            // Must be after
                        } else {
                            etaTimeChange = currentActiveWaypointETA.plus(lastTransmitActiveWp.getMillis())
                                    .getMillis();
                        }

                        if (etaTimeChange > ADAPTIVE_TIME * 1000L) {
                            LOG.debug("Broadcast based on adaptive time!");
                            broadcastIntendedRoute();
                            lastSend = new DateTime();
                        }

                        // LOG.debug("ETA has changed with " + etaTimeChange
                        // + " mili seconds" );

                    }

                }

                Util.sleep(1000L);

            }
        }

    }

}

From source file:es.jpons.persistence.TemporalPersistenceManager.java

License:Open Source License

/**
 * Function to close a vtp from another/* w  ww . ja  v  a2s  . co  m*/
 *
 * @param toClose The vtp to close
 * @param newVtp The other vtp to start
 * @return A copy of the object toClose closed to the left.
 * @throws TemporalException If the closure of the vtp can not be computed.
 */
public PossibilisticVTP closeR(PossibilisticVTP toClose, PossibilisticVTP newVtp) throws TemporalException {
    if (toClose.getSide() != null && toClose.getSide().compareTo(OpenInterval.UC) == 0) {
        DateTime startmp = new DateTime(toClose.getStartMP());
        //            DateTime leftmp = startmp.minus(toClose.getStartLeft());
        DateTime rightmp = startmp.plus(toClose.getStartRight());

        DateTime newmp = new DateTime(newVtp.getStartMP());
        DateTime newleft = newmp.minus(newVtp.getStartLeft());
        //            DateTime newright = newmp.plus(newVtp.getStartRight());

        if (rightmp.isBefore(newleft)) {
            log.trace("Closing ending point");
            Duration d = new Duration(startmp, newmp);
            Duration d1 = new Duration(d.getMillis() / 2);

            DateTime closeMp = new DateTime(startmp);
            closeMp = closeMp.plus(d1);

            Duration left = new Duration(startmp, closeMp);
            Duration right = new Duration(closeMp, newleft);

            toClose.setEndMP(closeMp.getMillis());
            toClose.setEndLeft(left.getMillis());
            toClose.setEndRight(right.getMillis());

            toClose.setSide(null);

        } else {
            log.error("The point cannot be closed");
            throw new TemporalException("The point cannot be closed");
        }

        //            
        //            DateTime lefts = startmp.plus( new Instant(newVtp.getStartLeft()));
        //            if(newVtp.getStartMP()> )
    } else {
        log.error("The point is not open");
        throw new TemporalException("The point is not open");
    }

    return toClose;
}

From source file:es.jpons.temporal.types.PossibilisticVTP.java

License:Open Source License

@Override
public String toString() {
    String result = new String();

    if (this.getSide() != null && this.getSide().compareTo(OpenInterval.FB) == 0) {
        result += " [ FB ,";
    } else {/*w  ww .ja v a2  s .c  o m*/
        DateTime mp = new DateTime(this.startMP);
        DateTime left = new DateTime(mp.minus(this.startLeft));
        DateTime right = new DateTime(mp.plus(this.startRight));
        result += " [ ( " + left + " , " + mp + " , " + right + " ) ,";
    }

    if (this.getSide() != null && this.getSide().compareTo(OpenInterval.UC) == 0) {
        result += "  UC ";
    } else {
        DateTime mp = new DateTime(this.endMP);
        DateTime left = new DateTime(mp.minus(this.endLeft));
        DateTime right = new DateTime(mp.plus(this.endRight));
        result += "  ( " + left + " , " + mp + " , " + right + " ) ]";
    }

    return result;
}

From source file:fi.hsl.parkandride.back.prediction.PredictionDao.java

License:EUPL

private static BooleanExpression isWithinPredictionWindow(DateTime time) {
    time = toPredictionResolution(time);
    return qPrediction.start.between(time.minus(PREDICTION_WINDOW).plus(PREDICTION_RESOLUTION), time);
}

From source file:fi.hsl.parkandride.core.domain.prediction.AverageOfPreviousWeeksPredictor.java

License:EUPL

@Override
public List<Prediction> predict(PredictorState state, UtilizationHistory history, int maxCapacity) {
    Optional<Utilization> latest = history.getLatest();
    if (!latest.isPresent())
        return Collections.emptyList();
    DateTime now = state.latestUtilization = latest.get().timestamp;

    List<List<Prediction>> groupedByWeek = Stream.of(Weeks.weeks(1), Weeks.weeks(2), Weeks.weeks(3))
            .map(offset -> {//w  w w .j  av a2s.c  o  m
                DateTime start = now.minus(offset);
                DateTime end = start.plus(PredictionRepository.PREDICTION_WINDOW);
                List<Utilization> utilizations = history.getRange(start, end);
                return utilizations.stream()
                        .map(u -> new Prediction(u.timestamp.plus(offset), u.spacesAvailable))
                        .collect(Collectors.toList());
            }).collect(Collectors.toList());

    List<List<Prediction>> groupedByTimeOfDay = ListUtil.transpose(groupedByWeek);

    return groupedByTimeOfDay.stream().map(this::reduce).collect(Collectors.toList());
}

From source file:fi.hsl.parkandride.core.domain.prediction.RelativizedAverageOfPreviousWeeksPredictor.java

License:EUPL

@Override
public List<Prediction> predict(PredictorState state, UtilizationHistory history, int maxCapacity) {
    Optional<Utilization> latest = history.getLatest();
    if (!latest.isPresent()) {
        return Collections.emptyList();
    }//from w w w.  j  ava 2  s . c  om
    DateTime now = state.latestUtilization = latest.get().timestamp;
    final UtilizationHistory inMemoryHistory = new UtilizationHistoryList(
            history.getRange(now.minusWeeks(3).minus(LOOKBACK_MINUTES), now));

    List<List<Prediction>> groupedByWeek = LOOKBACK_PERIODS.stream().map(offset -> {
        DateTime start = now.minus(offset);
        DateTime end = start.plus(PredictionRepository.PREDICTION_WINDOW);
        Optional<Utilization> utilizationAtReferenceTime = inMemoryHistory.getAt(start);
        if (!utilizationAtReferenceTime.isPresent()) {
            return null;
        }

        Integer spacesAvailableAtReferenceTime = utilizationAtReferenceTime.get().spacesAvailable;
        List<Utilization> utilizations = inMemoryHistory.getRange(start, end);
        return utilizations.stream().map(u -> new Prediction(u.timestamp.plus(offset),
                u.spacesAvailable - spacesAvailableAtReferenceTime)).collect(Collectors.toList());
    }).filter(Objects::nonNull).collect(Collectors.toList());

    List<List<Prediction>> groupedByTimeOfDay = ListUtil.transpose(groupedByWeek);

    return groupedByTimeOfDay.stream().map(predictions -> reduce(predictions, latest.get().spacesAvailable,
            getUtilizationMultiplier(now, inMemoryHistory), maxCapacity)).collect(Collectors.toList());
}