Example usage for org.joda.time Duration plus

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

Introduction

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

Prototype

public Duration plus(ReadableDuration amount) 

Source Link

Document

Returns a new duration with this length plus that specified.

Usage

From source file:au.id.hazelwood.xmltvguidebuilder.postprocessor.ListingVerifier.java

License:Apache License

public void verifyListing(ChannelListings listings, DateTime from, DateTime to, DateTime subsetTo) {
    Duration listingDurationTotal = new Interval(from, to).toDuration();
    Duration listingDurationSubset = new Interval(from, subsetTo).toDuration();
    LOGGER.info(repeat("-", 100));
    for (ChannelDetail channelDetail : listings.getChannels()) {
        Duration missingDurationTotal = Duration.ZERO;
        Duration missingDurationSubset = Duration.ZERO;
        StringBuilder allMissingIntervalDetails = new StringBuilder();
        for (Interval missing : findMissingIntervals(listings, from, to, channelDetail.getId())) {
            missingDurationTotal = missingDurationTotal.plus(missing.toDuration());
            if (missing.getStart().isBefore(subsetTo)) {
                if (missing.getEnd().isBefore(subsetTo)) {
                    missingDurationSubset = missingDurationSubset.plus(missing.toDuration());
                } else {
                    missingDurationSubset = missingDurationSubset
                            .plus(new Duration(missing.getStart(), subsetTo));
                }/*  w w w.  j a  va 2s . c o  m*/
            }
            allMissingIntervalDetails.append(allMissingIntervalDetails.length() == 0 ? "missing " : ", ");
            allMissingIntervalDetails.append(
                    format("{0}-{1}", toISODateTime(missing.getStart()), toISODateTime(missing.getEnd())));
        }
        Duration availableDurationTotal = listingDurationTotal.minus(missingDurationTotal);
        Duration availableDurationSubset = listingDurationSubset.minus(missingDurationSubset);
        Integer availablePercentageTotal = getPercentage(availableDurationTotal, listingDurationTotal);
        Integer availablePercentageSubset = getPercentage(availableDurationSubset, listingDurationSubset);
        LOGGER.info("{} {} [{}|{}] {}", rightPad(channelDetail.getId() + " - " + channelDetail.getName(), 42),
                formatDurationDHM(availableDurationTotal.getMillis()),
                leftPad(availablePercentageSubset + "%", 4), leftPad(availablePercentageTotal + "%", 4),
                allMissingIntervalDetails.toString());
    }
    LOGGER.info(repeat("-", 100));
}

From source file:ch.eitchnet.android.mabea.MabeaParsing.java

License:Open Source License

public static Duration parseBalance(String value) throws MabeaParsingException {
    try {/*from  w ww  . j  a va 2  s  .  com*/

        int posColon = value.indexOf(':');
        int posSpace = value.indexOf(' ');

        int hours = Integer.parseInt(value.substring(0, posColon));
        int minutes = Integer.parseInt(value.substring(posColon + 1, posSpace));
        if (hours < 0)
            minutes = -minutes;

        Duration duration = Hours.hours(hours).toStandardDuration();
        duration = duration.plus(Minutes.minutes((int) minutes).toStandardDuration());
        return duration;

    } catch (Exception e) {
        throw new MabeaParsingException("Balance can not be parsed from value " + value, e);
    }
}

From source file:ch.eitchnet.android.mabea.MabeaParsing.java

License:Open Source License

public static Duration parseRemainingVacation(String value) throws MabeaParsingException {
    try {/*from  w w  w.  j  av a  2 s.c  o  m*/

        int posSpace = value.indexOf(' ');
        String daysS = value.substring(0, posSpace).replace(",", ".");
        double days = Double.parseDouble(daysS);

        Duration duration = Days.days((int) Math.floor(days)).toStandardDuration();
        if ((Math.floor(days)) <= (int) days) {
            duration = duration.plus(Hours.hours(12).toStandardDuration());
        }

        return duration;

    } catch (Exception e) {
        throw new MabeaParsingException("Remaining vacation can not be parsed from value " + value, e);
    }
}

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;
        }//from w  w w  .  j a  va  2  s  . c om
        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.SolutionCandidate.java

License:Apache License

/**
 * Verifies that summed distances and direct distance are the same, assuming a path never takes more than whole week, .
 *
 * @param path//from  www. ja v a  2s  .c  o  m
 */
public static void sanityCheckPath(List<TrainPathSlot> path,
        SimpleTrainPathApplication simpleTrainPathApplication) {

    if (path.size() == 0) {
        throw new IllegalStateException(
                "Path should have size > 0 for request " + simpleTrainPathApplication.getName());
    } else if (!path.get(0).getFrom().equals(simpleTrainPathApplication.getFrom())
            || !path.get(path.size() - 1).getTo().equals(simpleTrainPathApplication.getTo())) {
        throw new IllegalStateException(
                "Path does not start or end at requested locations in " + simpleTrainPathApplication.getName());
    }

    Duration summedDistance = new Duration(0);
    for (TrainPathSlot trainPathSlot : path) {
        summedDistance = summedDistance
                .plus(trainPathSlot.getEndTime().distanceAfter(trainPathSlot.getStartTime()));
    }
    for (int i = 1; i < path.size(); i++) {
        TrainPathSlot previous = path.get(i - 1);
        TrainPathSlot current = path.get(i);
        summedDistance = summedDistance.plus(current.getStartTime().distanceAfter(previous.getEndTime()));

        if (!previous.getTo().equals(current.getFrom())) {
            throw new IllegalStateException("Path is not consistent" + simpleTrainPathApplication.getName());
        }

    }
    Duration directDistance = path.get(path.size() - 1).getEndTime().distanceAfter(path.get(0).getStartTime());
    if (!directDistance.isEqual(summedDistance)) {
        throw new IllegalStateException("Direct and summed distance should be the same in path for request"
                + simpleTrainPathApplication.getName());
    }
}

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   w  ww. j  a v  a  2 s .c o m*/
        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;//from  w  w w  .j a  v  a  2  s.c o  m
    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:com.anrisoftware.simplerest.core.AbstractRepeatSimpleGetWorker.java

License:Open Source License

@Override
protected T repeatRequest(CloseableHttpResponse previouslyResponse, HttpRequest previouslyRequest,
        StatusLine previouslyStatusLine) throws SimpleRestException {
    int repeateCount = requestsRepeateCount;
    int repeateMax = requestsRepeateMax;
    Duration repeateWait = requestsRepeateWait;
    if (repeateCount == repeateMax) {
        throw parseErrorMessage(previouslyRequest, previouslyResponse, previouslyStatusLine);
    }//  w ww . j av a 2s  .  c o  m
    try {
        log.repeatRequestsSleep(parent, repeateCount, repeateWait);
        Thread.sleep(repeateWait.getMillis());
    } catch (InterruptedException e) {
        return null;
    }
    CloseableHttpClient httpclient = createHttpClient();
    HttpGet httpget = createHttpGet();
    CloseableHttpResponse response = executeRequest(httpclient, httpget);
    StatusLine statusLine = response.getStatusLine();
    repeateCount++;
    repeateWait = repeateWait.plus(requestsRepeateWaitDuration);
    this.requestsRepeateCount = repeateCount;
    this.requestsRepeateWait = repeateWait;
    return parseResponse(response, httpget, statusLine);
}

From source file:com.kopysoft.chronos.adapter.clock.PayPeriodAdapterList.java

License:Open Source License

@Deprecated
public Duration getTime() {
    Duration dur = new Duration(0);

    for (DateTime date : gPunchesByDay.getDays()) {
        dur = dur.plus(getTime(gPunchesByDay.getPunchPair(date)));
    }//from w  ww.j  a  va  2 s.co m
    if (enableLog)
        Log.d(TAG, "Duration: " + dur);

    return dur;
}

From source file:com.kopysoft.chronos.adapter.clock.PayPeriodAdapterList.java

License:Open Source License

public static Duration getTime(PunchTable table) {
    Duration dur = new Duration(0);

    for (DateTime date : table.getDays()) {
        dur = dur.plus(getTime(table.getPunchPair(date)));
    }// w w w.j  a  v  a2 s .  co m
    if (enableLog)
        Log.d(TAG, "Duration: " + dur);

    return dur;
}