Example usage for org.joda.time Duration Duration

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

Introduction

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

Prototype

public Duration(Object duration) 

Source Link

Document

Creates a duration from the specified object using the org.joda.time.convert.ConverterManager ConverterManager .

Usage

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 .java  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.piratenpartei.pivote.serialize.DataInput.java

License:Apache License

public LocalDateTime readDateTime() throws IOException {
    long offset = DataIO.nano100ToMillis(readInt64());
    return DataIO.BASE_DATETIME.plus(new Duration(offset));
}

From source file:ch.thp.time.utilties.database.DurationConverter.java

@Override
public Object convertDataValueToObjectValue(Object dataValue, Session session) {
    if (dataValue instanceof String) {
        return new Duration(dataValue);
    }/*ww  w . j  a  v  a 2  s  .c  o  m*/
    throw new IllegalStateException("Converstion exception, value is not of LocalDate type.");

}

From source file:co.edu.uelbosque.sistemas.swiii.c3.historiaclinica.entities.Medico.java

private void setNacimiento(Calendar nacimiento) {
    Calendar ahora = Calendar.getInstance();
    long hoy = ahora.getTimeInMillis();
    long dias = hoy - nacimiento.getTimeInMillis();
    Duration d = new Duration(dias);
    this.dias = (int) d.getStandardDays();
    Period period = new Period(nacimiento.getTimeInMillis(), hoy, PeriodType.months());
    this.meses = period.getMonths();
    this.nacimiento = nacimiento;
}

From source file:com.almende.bridge.resources.SimulatedResource.java

License:Apache License

/**
 * Task request.//  w  ww  .j av a 2s.  co  m
 * -Check if busy
 * -Check if capable of that task
 * -Check distance to start (rough guess if reachable in time) (TODO,
 * somewhat problematic due to datum issues)
 * -Check ETA to start
 * If all true, report possible match plus ETA.
 *
 * @param task
 *            the task
 * @param reportTo
 *            the report to
 */
public void taskRequest(final @Name("task") ObjectNode task, final @Name("reportTo") URI reportTo) {
    String resType = getResType();
    if (task.has("resType")) {
        if (!resType.equals(task.get("resType").asText())) {
            return;
        }
    }
    if (deploymentState.equals(DEPLOYMENTSTATE.Unassigned)) {
        boolean capable = false;
        String planName = task.get("planName").asText();
        if ("Goto".equals(planName) || "GotoAndStay".equals(planName)) {
            capable = true;
        } else if (resType.equals("medic vehicle")) {
            if (task.get("planName").asText().equals("Evac")) {
                capable = true;
            }
        }
        if (!capable) {
            return;
        }
        // distance/speed on Highway (~80km/h)

        final Params params = new Params();
        params.put("startLat", geoJsonPos[1]);
        params.put("startLon", geoJsonPos[0]);
        params.put("endLat", task.get("lat").asDouble());
        params.put("endLon", task.get("lon").asDouble());

        try {
            getRoute(params, new AsyncCallback<ObjectNode>() {
                /*
                 * (non-Javadoc)
                 * @see
                 * com.almende.util.callback.AsyncCallback#onSuccess(java.lang
                 * .Object
                 * )
                 */
                @Override
                public void onSuccess(ObjectNode result) {
                    Route myRoute = new Route();
                    myRoute.routeBase = DateTime.now();
                    myRoute.route = ROUTETYPE.inject(result.get("route"));
                    myRoute.index = 0;
                    myRoute.eta = new Duration(result.get("millis").asLong());

                    if (myRoute.routeBase.plus(myRoute.eta).isBefore(task.get("before").asLong())) {
                        // Potential!
                        Params params = new Params();
                        params.add("task", task);
                        params.add("eta", myRoute.eta.plus((long) Math.floor(Math.random() * 5000)));
                        try {
                            call(reportTo, "volunteer", params);
                        } catch (IOException e) {
                            LOG.log(Level.WARNING, "Couldn't volunteer for task", e);
                        }
                    }
                }

                @Override
                public void onFailure(Exception exception) {
                    LOG.log(Level.WARNING, "Couldn't plan route:", exception);
                }
            });
        } catch (IOException e) {
            LOG.log(Level.WARNING, "Couldn't plan route:", e);
        }
    }
}

From source file:com.almende.bridge.resources.SimulatedResource.java

License:Apache License

private void planRoute() throws IOException {
    final Params params = new Params();
    params.put("startLat", geoJsonPos[1]);
    params.put("startLon", geoJsonPos[0]);
    params.put("endLat", geoJsonGoal[1]);
    params.put("endLon", geoJsonGoal[0]);
    getRoute(params, new AsyncCallback<ObjectNode>() {

        /*//from  ww  w.  j  a  v  a 2  s.  c  o  m
         * (non-Javadoc)
         * @see
         * com.almende.util.callback.AsyncCallback#onSuccess(java.lang.Object
         * )
         */
        @Override
        public void onSuccess(ObjectNode result) {
            if (route == null) {
                route = new Route();
            }
            route.routeBase = DateTime.now().plus((long) (Math.random() * 10000));
            route.route = ROUTETYPE.inject(result.get("route"));
            route.index = 0;
            route.eta = new Duration(result.get("millis").asLong());
            checkArrival();
        }

        @Override
        public void onFailure(Exception exception) {
            LOG.log(Level.WARNING, "Couldn't get route:", exception);
            route = null;
        }
    });
}

From source file:com.almende.eve.agent.MeetingAgent.java

License:Apache License

/**
 * Calculate all feasible intervals with their preference weight, based on
 * the event status, stored infeasible intervals, and preferred intervals.
 * If there are no solutions, an empty array is returned.
 * /*from ww w .  j a  v  a  2 s .  c  o  m*/
 * @return solutions
 */
private List<Weight> calculateSolutions() {
    LOG.info("calculateSolutions started"); // TODO: cleanup

    final State state = getState();
    final List<Weight> solutions = new ArrayList<Weight>();

    // get the activity
    final Activity activity = state.get("activity", Activity.class);
    if (activity == null) {
        return solutions;
    }

    // get infeasible intervals
    ArrayList<Interval> infeasible = state.get("infeasible", new TypeUtil<ArrayList<Interval>>() {
    });
    if (infeasible == null) {
        infeasible = new ArrayList<Interval>();
    }

    // get preferred intervals
    List<Weight> preferred = state.get("preferred", new TypeUtil<ArrayList<Weight>>() {
    });
    if (preferred == null) {
        preferred = new ArrayList<Weight>();
    }

    // get the duration of the activity
    final Long durationLong = activity.withConstraints().withTime().getDuration();
    Duration duration = null;
    if (durationLong != null) {
        duration = new Duration(durationLong);
    } else {
        // TODO: give error when duration is not defined?
        duration = Duration.standardHours(1);
    }

    // check interval at next half hour
    final DateTime firstTimeslot = getNextHalfHour();
    Interval test = new Interval(firstTimeslot, firstTimeslot.plus(duration));
    testInterval(infeasible, preferred, test, solutions);

    // loop over all infeasible intervals
    for (final Interval i : infeasible) {
        // test timeslot left from the infeasible interval
        test = new Interval(i.getStart().minus(duration), i.getStart());
        testInterval(infeasible, preferred, test, solutions);

        // test timeslot right from the infeasible interval
        test = new Interval(i.getEnd(), i.getEnd().plus(duration));
        testInterval(infeasible, preferred, test, solutions);
    }

    // loop over all preferred intervals
    for (final Weight w : preferred) {
        // test timeslot left from the start of the preferred interval
        test = new Interval(w.getStart().minus(duration), w.getStart());
        testInterval(infeasible, preferred, test, solutions);

        // test timeslot right from the start of the preferred interval
        test = new Interval(w.getStart(), w.getStart().plus(duration));
        testInterval(infeasible, preferred, test, solutions);

        // test timeslot left from the end of the preferred interval
        test = new Interval(w.getEnd().minus(duration), w.getEnd());
        testInterval(infeasible, preferred, test, solutions);

        // test timeslot right from the end of the preferred interval
        test = new Interval(w.getEnd(), w.getEnd().plus(duration));
        testInterval(infeasible, preferred, test, solutions);
    }

    // order the calculated feasible timeslots by weight, from highest to
    // lowest. In case of equals weights, the timeslots are ordered by
    // start date
    class WeightComparator implements Comparator<Weight> {
        @Override
        public int compare(final Weight a, final Weight b) {
            if (a.getWeight() != null && b.getWeight() != null) {
                final int cmp = Double.compare(a.getWeight(), b.getWeight());
                if (cmp == 0) {
                    return a.getStart().compareTo(b.getStart());
                } else {
                    return -cmp;
                }
            }
            return 0;
        }
    }
    final WeightComparator comparator = new WeightComparator();
    Collections.sort(solutions, comparator);

    // remove duplicates
    int i = 1;
    while (i < solutions.size()) {
        if (solutions.get(i).equals(solutions.get(i - 1))) {
            solutions.remove(i);
        } else {
            i++;
        }
    }

    return solutions;
}

From source file:com.anrisoftware.globalpom.format.duration.DurationFormat.java

License:Open Source License

private Duration decodeDuration(String source, ParsePosition pos) throws ParseException {
    Matcher matcher = PATTERN.matcher(source);
    log.checkMatches(matcher.find(), source, pos);
    long y = (long) (parseLongSave(matcher.group(2)) * YEARS);
    long m = (long) (parseLongSave(matcher.group(4)) * MONTH);
    long d = (long) (parseLongSave(matcher.group(6)) * DAYS);
    long h = (long) (parseLongSave(matcher.group(9)) * HOURS);
    long min = (long) (parseLongSave(matcher.group(11)) * MINUTES);
    long s = (long) (parseDoubleSave(matcher.group(13)) * SECONDS);
    return new Duration(y + m + d + h + min + s);
}

From source file:com.auth10.federation.SamlTokenValidator.java

License:Open Source License

private boolean validateExpiration(Instant notBefore, Instant notOnOrAfter) {

    Instant now = new Instant();
    Duration skew = new Duration(MAX_CLOCK_SKEW_IN_MINUTES * 60 * 1000);

    if (now.plus(skew).isBefore(notBefore)) {
        return true;
    }/*from   www .j  a  va  2s.  c o m*/

    if (now.minus(skew).isAfter(notOnOrAfter)) {
        return true;
    }

    return false;
}

From source file:com.chiorichan.Loader.java

License:Mozilla Public License

public static String getUptime() {
    Duration duration = new Duration(System.currentTimeMillis() - startTime);
    PeriodFormatter formatter = new PeriodFormatterBuilder().appendDays().appendSuffix(" Day(s) ").appendHours()
            .appendSuffix(" Hour(s) ").appendMinutes().appendSuffix(" Minute(s) ").appendSeconds()
            .appendSuffix(" Second(s)").toFormatter();
    return formatter.print(duration.toPeriod());
}