Example usage for org.joda.time Duration isShorterThan

List of usage examples for org.joda.time Duration isShorterThan

Introduction

In this page you can find the example usage for org.joda.time Duration isShorterThan.

Prototype

public boolean isShorterThan(ReadableDuration duration) 

Source Link

Document

Is the length of this duration shorter than the duration passed in.

Usage

From source file:be.fedict.eid.dss.spi.utils.XAdESUtils.java

License:Open Source License

/**
 * Checks whether the given date-times are close enough next to each other.
 * //ww w. j a  va2 s. co m
 * @param t1
 * @param t2
 * @param millis
 * @throws XAdESValidationException
 */
public static void checkCloseEnough(DateTime t1, DateTime t2, long millis) throws XAdESValidationException {
    Duration dt;
    if (t1.isBefore(t2)) {
        dt = new Duration(t1, t2);
    } else {
        dt = new Duration(t2, t1);
    }
    if (false == dt.isShorterThan(new Duration(millis))) {
        throw new XAdESValidationException(
                "max dt of " + millis + " ms exceeded between " + t1 + " and " + t2 + " with dt = " + dt);
    }
}

From source file:ch.eitchnet.android.util.JodaHelper.java

License:Open Source License

public static String toHourMinute(Duration duration) {
    PeriodFormatterBuilder builder = new PeriodFormatterBuilder();
    builder.printZeroAlways();/*ww  w . j a va2 s  . c om*/
    if (duration.isShorterThan(Duration.ZERO))
        builder.appendLiteral("-");
    builder.minimumPrintedDigits(2).appendHours().appendLiteral(":").minimumPrintedDigits(2).appendMinutes();
    return builder.toFormatter().print(new Period(Math.abs(duration.getMillis())));
}

From source file:ch.oakmountain.tpa.solver.PeriodicalTrainPathSlot.java

License:Apache License

/**
 * Get a train path slot/*  w ww . j a  va 2  s .  c  om*/
 *
 * @param earliest
 * @return
 */
public TrainPathSlot getNextOrQuickestTrainPathSlot(PeriodicalTimeFrame earliest) {
    TrainPathSlot nextSlot = null;
    Duration shortestDistance = null;
    for (Integer day : periodicity.getWeekDays()) {
        TrainPathSlot daySlot = slots[day];
        Duration thisDistance;
        Duration distanceAfterStartTime = daySlot.getStartTime().distanceAfter(earliest);
        thisDistance = distanceAfterStartTime;
        if (shortestDistance == null || thisDistance.isShorterThan(shortestDistance)) {
            nextSlot = daySlot;
            shortestDistance = thisDistance;
        }
    }
    return nextSlot;
}

From source file:ch.oakmountain.tpa.solver.SimpleTrainPathApplication.java

License:Apache License

public String getHTMLDescription(MacroscopicTopology macro, TrainPathSlotCatalogue catalogue)
        throws IllegalAccessException {
    StringBuilder sb = new StringBuilder();
    sb.append("<table>");
    sb.append("<th> Property </th>");
    sb.append("<th> Value </th>");

    for (Field field : this.getClass().getDeclaredFields()) {
        // HACK: JaCoCo adds field $jacocoData; which gives problems in regular expressions at 1 A.M....
        if (field.getName().contains("$") || field.get(this) == null
                || field.get(this).toString().contains("$")) {
            continue;
        }/* w ww  . j a v a2s.c o  m*/
        sb.append("<tr>");
        sb.append("<td> " + field.getName() + " </td>");
        sb.append("<td> " + field.get(this) + " </td>");
        sb.append("</tr>");
    }
    for (List<SystemNode> route : macro.getRoutes(from, to)) {
        sb.append("<tr>");
        sb.append("<td> route </td>");
        sb.append("<td>");
        SystemNode previous = null;
        Duration duration = new Duration(0);
        for (SystemNode systemNode : route) {
            sb.append("- " + systemNode.getName() + " -");
            if (previous != null) {
                List<TrainPathSlot> sortedTrainPathSlots = catalogue.getSortedTrainPathSlots(previous,
                        systemNode, PeriodicalTimeFrame.START_OF_WEEK, PeriodicalTimeFrame.END_OF_WEEK);
                if (sortedTrainPathSlots.size() == 0) {
                    throw new IllegalStateException("No slot");

                }
                TrainPathSlot aSlot = sortedTrainPathSlots.get(0);
                Duration stepDuration = aSlot.getEndTime().distanceAfter(aSlot.getStartTime());
                if (stepDuration.isShorterThan(new Duration(0))) {
                    throw new IllegalStateException("Duration of " + aSlot.getFrom() + " - " + aSlot.getTo()
                            + " is negative: " + PeriodicalTimeFrame.formatDuration(stepDuration));
                }
                duration = duration.plus(stepDuration);
            }
            previous = systemNode;
        }
        sb.append("----- " + PeriodicalTimeFrame.formatDuration(duration));
        sb.append("</td>");
        sb.append("</tr>");
    }
    sb.append("</table>");
    return sb.toString();
}

From source file:ch.oakmountain.tpa.solver.SolutionCandidateFinder.java

License:Apache License

/**
 * Gets the earliest path within the request's hard bounds.
 *
 * Greedy approach:/*from ww  w  .j  av  a 2 s .c  o m*/
 * - at each system node A and for all next system nodes C, choose the slot that brings us first to C (this should be deterministic, if the construction of train path slots does not produce overtakings)
 * - finally choose arbitrarily one of the paths that brings us first to the destination (here, indeterminism happens as seen in the real-world data set)
 *
 * @param macro
 * @param catalogue
 * @param from
 * @param to
 * @param lb
 * @param ub
 * @return
 */
// TODO make a data set with alternative routes, for instance---</=======>---<===
// TODO remove indeterministic behaviour?
private static List<TrainPathSlot> getEarliestPath(MacroscopicTopology macro, TrainPathSlotCatalogue catalogue,
        SystemNode from, SystemNode to, PeriodicalTimeFrame lb, Duration dt, PeriodicalTimeFrame ub) {
    HashSet<List<TrainPathSlot>> paths = new HashSet<>();
    Duration bestDuration = null;
    List<TrainPathSlot> bestPath = null;
    getEarliestPathIter(macro, catalogue, from, to, lb, dt, ub, from, new LinkedList<TrainPathSlot>(), paths);

    // N.B: the choice of the earliest path is Non-deterministic!
    for (List<TrainPathSlot> path : paths) {

        Duration durationCand = lb.distanceAfter(path.get(path.size() - 1).getEndTime());
        if (bestDuration == null || durationCand.isShorterThan(bestDuration)) {
            bestDuration = durationCand;
            bestPath = path;
        }
    }
    return bestPath;
}

From source file:ch.oakmountain.tpa.solver.TrainPathAllocationProblemPruningParameters.java

License:Apache License

public void setDefaultPruning() {
    // set to applications hard bounds
    setMINIMUM_DWELL_TIME(getHARD_MINIMUM_DWELL_TIME());
    setMAXIMUM_EARLIER_DEPARTURE(getHARD_MAXIMUM_EARLIER_DEPARTURE());
    setMAXIMUM_LATER_ARRIVAL(getHARD_MAXIMUM_LATER_ARRIVAL());

    // set to arbitrary initial values
    // TODO command-line options for default pruning?
    setMAXIMUM_ADDITIONAL_DWELL_TIME(Minutes.minutes(15).toStandardDuration());
    Duration maxDuration = getApplicationHardMaxDuration();
    Duration anHour = Minutes.minutes(60).toStandardDuration();
    if (maxDuration.isShorterThan(anHour)) {
        setMAXIMUM_LATER_DEPARTURE(maxDuration);
        setMAXIMUM_EARLIER_ARRIVAL(maxDuration);
    } else {/*from w  w  w  .  j  a va  2s  . c  om*/
        setMAXIMUM_LATER_DEPARTURE(Minutes.minutes(60).toStandardDuration());
        setMAXIMUM_EARLIER_ARRIVAL(Minutes.minutes(60).toStandardDuration());
    }

    nonDefaultAddiontalDwellTimesMap.clear();
}

From source file:ch.oakmountain.tpa.solver.TrainPathAllocationProblemPruningParameters.java

License:Apache License

public void setMINIMUM_DWELL_TIME(Duration MINIMUM_DWELL_TIME) {
    if (MINIMUM_DWELL_TIME.isShorterThan(HARD_MINIMUM_DWELL_TIME)) {
        throw new IllegalArgumentException("Must not be shorter than hard minimum.");
    }/*from   ww w.j  av a  2 s . c  o  m*/
    this.MINIMUM_DWELL_TIME = MINIMUM_DWELL_TIME;
}

From source file:ch.oakmountain.tpa.solver.TrainPathApplicationStatistics.java

License:Apache License

List<String> compileAndGetTrainPathApplicationListRow() throws IOException {
    HashMap<TrainPathSlot, Vertex> slotVertexHashMap = new HashMap<>();
    HashMap<SystemNode, Set<TrainPathSlot>> systemNodeTrainPathSlotHashMap = new HashMap<>();
    HashMap<SystemNode, Set<Pair<TrainPathSlot, TrainPathSlot>>> connectionsThroughSystemNode = new HashMap<>();
    for (Vertex vertex : dag.getVerticies()) {
        if (vertex.isLeaf() || vertex.isRoot()) {
            continue;
        }/*from   ww  w  .  ja v  a 2 s .com*/
        TrainPathSlot trainPathSlot = dag.getSlotFromVertex(vertex.getLabel());
        slotVertexHashMap.put(trainPathSlot, vertex);
        SystemNode from = trainPathSlot.getFrom();
        SystemNode to = trainPathSlot.getTo();
        initSystemNodeInMaps(systemNodeTrainPathSlotHashMap, connectionsThroughSystemNode, to);
        initSystemNodeInMaps(systemNodeTrainPathSlotHashMap, connectionsThroughSystemNode, from);
        systemNodeTrainPathSlotHashMap.get(from).add(trainPathSlot);

        for (Vertex child : vertex.getChildren()) {
            if (vertex.isLeaf() || vertex.isRoot()) {
                continue;
            }
            TrainPathSlot childSlot = dag.getSlotFromVertex(child.getLabel());
            Pair<TrainPathSlot, TrainPathSlot> connection = new Pair<TrainPathSlot, TrainPathSlot>(
                    trainPathSlot, childSlot);

            connectionsThroughSystemNode.get(to).add(connection);
        }
    }
    int minSlotsPerSystemNode = Integer.MAX_VALUE;
    int maxSlotsPerSystemNode = Integer.MIN_VALUE;

    for (SystemNode systemNode : systemNodeTrainPathSlotHashMap.keySet()) {

        Set<TrainPathSlot> succSlots = systemNodeTrainPathSlotHashMap.get(systemNode);
        int nbSuccSlots = succSlots.size();
        maxSlotsPerSystemNode = Math.max(nbSuccSlots, maxSlotsPerSystemNode);
        minSlotsPerSystemNode = Math.min(nbSuccSlots, minSlotsPerSystemNode);

        Duration minDwellTime = new Duration(Long.MAX_VALUE);
        Duration maxDwellTime = Duration.ZERO;
        Duration totalDwellTime = Duration.ZERO;

        Set<Pair<TrainPathSlot, TrainPathSlot>> connections = connectionsThroughSystemNode.get(systemNode);
        String dwellStats = "--";
        if (!systemNode.equals(simpleTrainPathApplication.getTo())
                && !systemNode.equals(simpleTrainPathApplication.getFrom())) {
            for (Pair<TrainPathSlot, TrainPathSlot> trainPathSlotTrainPathSlotPair : connections) {
                Duration dwell = trainPathSlotTrainPathSlotPair.second.getStartTime()
                        .distanceAfter(trainPathSlotTrainPathSlotPair.first.getEndTime());
                if (dwell.isShorterThan(Duration.ZERO)) {
                    throw new IllegalStateException("");
                }
                if (dwell.isLongerThan(maxDwellTime)) {
                    maxDwellTime = dwell;
                }
                if (dwell.isShorterThan(minDwellTime)) {
                    minDwellTime = dwell;
                }
                totalDwellTime = totalDwellTime.plus(dwell);
            }
            dwellStats = PeriodicalTimeFrame.formatDuration(minDwellTime) + "/"
                    + PeriodicalTimeFrame.formatDuration(maxDwellTime) + "/"
                    + PeriodicalTimeFrame.formatDuration(
                            totalDwellTime.dividedBy(connectionsThroughSystemNode.get(systemNode).size()));
        }

        String timeWindow;
        if (systemNode.equals(simpleTrainPathApplication.getFrom())) {
            timeWindow = "[" + simpleTrainPathApplication.getParams().getDepartureLowerBound().toString() + ","
                    + simpleTrainPathApplication.getParams().getDepartureUpperBound().toString() + "]";
        } else if (systemNode.equals(simpleTrainPathApplication.getTo())) {
            timeWindow = "[" + simpleTrainPathApplication.getParams().getArrivalLowerBound().toString() + ","
                    + simpleTrainPathApplication.getParams().getArrivalUpperBound().toString() + "]";
        } else {
            timeWindow = "[arr+ "
                    + PeriodicalTimeFrame.formatDuration(simpleTrainPathApplication.getParams()
                            .getMINIMUM_DWELL_TIME())
                    + ", arr+"
                    + PeriodicalTimeFrame.formatDuration(simpleTrainPathApplication.getParams()
                            .getHARD_MINIMUM_DWELL_TIME().plus(simpleTrainPathApplication.getParams()
                                    .getMAXIMUM_ADDITIONAL_DWELL_TIME(systemNode)))
                    + "]";
        }
        table.writeRow(Arrays.asList(
                systemNode.getName(), String.valueOf(nbSuccSlots), timeWindow, "["
                        + PeriodicalTimeFrame
                                .formatDuration(simpleTrainPathApplication.getParams().getMINIMUM_DWELL_TIME())
                        + ","
                        + PeriodicalTimeFrame.formatDuration(simpleTrainPathApplication.getParams()
                                .getMAXIMUM_ADDITIONAL_DWELL_TIME(systemNode))
                        + "]",
                "Min/max/average slots", dwellStats));
    }

    List<String> data = Arrays.asList(simpleTrainPathApplication.getName(),
            simpleTrainPathApplication.getFrom().getName(), simpleTrainPathApplication.getTo().getName(),
            simpleTrainPathApplication.getStartTime().toString(),
            simpleTrainPathApplication.getEndTime().toString(),
            PeriodicalTimeFrame
                    .formatDuration(simpleTrainPathApplication.getParams().getHARD_MAXIMUM_EARLIER_DEPARTURE()),
            PeriodicalTimeFrame
                    .formatDuration(simpleTrainPathApplication.getParams().getHARD_MAXIMUM_LATER_ARRIVAL()),
            PeriodicalTimeFrame
                    .formatDuration(simpleTrainPathApplication.getParams().getHARD_MINIMUM_DWELL_TIME()),
            String.valueOf(dag.nbPaths()), String.valueOf(dag.getCyclomaticComplexity()));

    table.finishTable();
    return data;
}

From source file:ch.oakmountain.tpa.solver.TrainPathSlotCatalogue.java

License:Apache License

private TrainPathSlot getNextOrQuickestTrainPathSlot(SystemNode from, SystemNode to,
        PeriodicalTimeFrame earliest, boolean takeStartTime) {
    Pair<SystemNode, SystemNode> link = new Pair(from, to);
    TrainPathSlot bestSlot = null;/* ww w.j  av a2 s  . com*/
    Duration bestDistance = null;
    if (linkMap.get(link) == null) {
        throw new IllegalArgumentException("There is no edge from " + from.getName() + " to " + to.getName()
                + " in the macroscopic topology");
    }
    for (PeriodicalTrainPathSlot periodicalTrainPathSlot : linkMap.get(link)) {
        TrainPathSlot slotCand = periodicalTrainPathSlot.getNextOrQuickestTrainPathSlot(earliest);
        if (slotCand == null) {
            LOGGER.warn("Found no successor slot at " + periodicalTrainPathSlot.getName()
                    + "; are there no slots for this periodical slot?");
            continue;
        }
        Duration distanceCand;
        if (takeStartTime) {
            distanceCand = slotCand.getStartTime().distanceAfter(earliest);
        } else {
            // situation [------>start-->earliest-->end---->[ vs. [---->earliest-->start-->end--[
            Duration durationEarliestToStart = slotCand.getStartTime().distanceAfter(earliest);
            Duration durationStartToEnd = slotCand.getEndTime().distanceAfter(slotCand.getStartTime());
            distanceCand = durationEarliestToStart.plus(durationStartToEnd);
        }

        if (bestDistance == null || distanceCand.isShorterThan(bestDistance)) {
            bestSlot = slotCand;
            bestDistance = distanceCand;
        }
    }
    return bestSlot;
}

From source file:ch.oakmountain.tpa.solver.TrainPathSlotCatalogue.java

License:Apache License

public TrainPathSlot getNextTrainPathSlotWithin24(SystemNode from, SystemNode to,
        PeriodicalTimeFrame earliest) {//from   ww w  .j a v  a 2  s  .c  o m
    Pair<SystemNode, SystemNode> link = new Pair(from, to);
    List<TrainPathSlot> slots = new LinkedList<>();
    if (linkMap.get(link) == null) {
        throw new IllegalArgumentException("There is no edge from " + from.getName() + " to " + to.getName()
                + " in the macroscopic topology");
    }
    if (linkMap.get(link) != null) {
        for (PeriodicalTrainPathSlot periodicalTrainPathSlot : linkMap.get(link)) {
            periodicalTrainPathSlot.addAllStartTimeContainedInclusive(earliest,
                    earliest.plus(Hours.hours(24).toStandardDuration()), slots);
        }
    }
    Duration minDistance = Hours.hours(24).toStandardDuration();
    TrainPathSlot slot = null;
    for (TrainPathSlot trainPathSlot : slots) {
        Duration distance = trainPathSlot.getStartTime().distanceAfter(earliest);
        if (distance.isShorterThan(minDistance)) {
            minDistance = distance;
            slot = trainPathSlot;
        }
    }
    return slot;
}