Example usage for org.joda.time Interval getStart

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

Introduction

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

Prototype

public DateTime getStart() 

Source Link

Document

Gets the start of this time interval, which is inclusive, as a DateTime.

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));
                }/*from w  ww  .j a va2  s. com*/
            }
            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:com.addthis.basis.time.Dates.java

License:Apache License

/**
 * Truncate interval start and end by current time
 * (start/end values after current time are set to current time)
 * <p/>/* www .  j  av a2 s.c  o  m*/
 * Truncate interval start by a specified number of period types
 * (eg. 30 days, 52 weeks, etc.)
 * <p/>
 * If type is null, no truncation is performed.
 * <p/>
 * When no truncation is performed, the input interval is returned
 * (this is useful for efficiently testing if truncation was performed).
 *
 * @param interval
 * @param limit    number of TYPE periods above which interval should be truncated
 * @param type     single field period type (the result of this method is undefined for multi-field period types)
 * @return
 */
public static Interval truncateInterval(Interval interval, int limit, PeriodType type) {
    Interval truncatedInterval = interval;
    if (type != null) {
        // Truncate end
        DateTime now = new DateTime();
        if (interval.getEnd().isAfter(now)) {
            if (interval.getStart().isAfter(now)) {
                truncatedInterval = new Interval(now, now);
            } else {
                truncatedInterval = interval.withEnd(now);
            }
        }

        // Truncate start
        if (truncatedInterval.toPeriod(type).getValue(0) > --limit) {
            Period limitPeriod = period(limit, type);
            DateTime truncatedStart = truncatedInterval.getEnd().minus(limitPeriod);
            truncatedInterval = truncatedInterval.withStart(truncatedStart);
        }
    }
    return truncatedInterval;
}

From source file:com.almende.dsol.example.datacenters.Datacenter.java

License:Apache License

protected void newService(final Interval interval) throws RemoteException, SimRuntimeException {
    if (getModel().hasRemoteAllocation()) {
        if (isSavingsMode(interval.getStart())) {
            if (getModel().hasBroker())
                for (Datacenter dc : getModel().getDatacenters()) {
                    if (dc == this)
                        continue;

                    if (dc.isExtraMode(interval.getStart())) {
                        newService(interval, .1, .1);
                        dc.newService(interval, 1.0, .9);
                        // LOG.trace(getName() + " Outsourced to EXTRA dc "
                        // + interval);
                        return;
                    }/* w  w w.jav  a2  s .c  o m*/
                }
            for (Datacenter dc : getModel().getDatacenters()) {
                if (dc == this)
                    continue;

                if (!dc.isSavingsMode(interval.getStart())) {
                    newService(interval, .1, .1);
                    dc.newService(interval, 1.0, .9);
                    return;
                }
            }

            LOG.trace(getName() + " Could not remotely allocate service " + interval);
        }
        // else
        // LOG.trace(getName()
        // + " Running locally during EXTRA mode, service: "
        // + interval);
    }
    // else
    // LOG.trace(getName()
    // + " Running locally during REGULAR mode, service: "
    // + interval);
    newService(interval, 1.0, 1.0);
    newService(interval, 0.0, 0.0);
}

From source file:com.almende.dsol.example.datacenters.Datacenter.java

License:Apache License

protected void newAdaption(final Interval interval, final double consumptionFactor)
        throws RemoteException, SimRuntimeException {
    if (consumptionFactor > 1.0)
        this.outsourceSchedule.put(interval.getStart(), interval);
    else if (consumptionFactor < 1.0)
        this.insourceSchedule.put(interval.getStart(), interval);

    final double startTime = simTime(interval.getStart());
    final double endTime = simTime(interval.getEnd());
    this.adaptionHours.addValue(DsolUtil.toTimeUnit(TimeUnitInterface.HOUR, interval.toDuration().getMillis(),
            TimeUnitInterface.MILLISECOND));
    getSimulator().scheduleEvent(new SimEvent(startTime, this, this, APPLY_CONSUMPTION_FACTOR_METHOD_ID,
            new Object[] { consumptionFactor, false }));
    getSimulator().scheduleEvent(new SimEvent(endTime, this, this, APPLY_CONSUMPTION_FACTOR_METHOD_ID,
            new Object[] { 1.0 / consumptionFactor, true }));
}

From source file:com.almende.dsol.example.datacenters.Datacenter.java

License:Apache License

protected void newPowermix(final Interval interval, final double emissionFactor)
        throws RemoteException, SimRuntimeException {
    final double startTime = simTime(interval.getStart());
    final double endTime = simTime(interval.getEnd());
    getSimulator().scheduleEvent(new SimEvent(startTime, this, this, APPLY_EMISSION_FACTOR_METHOD_ID,
            new Object[] { emissionFactor, false }));
    getSimulator().scheduleEvent(new SimEvent(endTime, this, this, APPLY_EMISSION_FACTOR_METHOD_ID,
            new Object[] { 1.0 / emissionFactor, true }));
}

From source file:com.almende.dsol.example.datacenters.Service.java

License:Apache License

/**
 * @param datacenter/*from  w w w.  j  av  a  2s.co  m*/
 * @throws RemoteException
 * @throws SimRuntimeException
 */
public Service(final FederationModel model, final Datacenter owner, final Interval interval,
        final double consumptionKW, final double hourlyCashflow) {
    super(model, "SVC" + ID_COUNT++);
    this.ownerName = owner.getName();
    this.consumptionKW = consumptionKW;
    this.hourlyCashflow = hourlyCashflow;

    this.startTime = simTime(interval.getStart());
    final double endTime = simTime(interval.getEnd());
    try {
        getSimulator().scheduleEvent(
                new SimEvent(this.startTime, this, this, STARTED_METHOD_ID, FederationModel.NO_ARGS));
        getSimulator()
                .scheduleEvent(new SimEvent(endTime, this, this, COMPLETED_METHOD_ID, FederationModel.NO_ARGS));
    } catch (final RemoteException | SimRuntimeException e) {
        LOG.error("t=" + model.getSimTime() + " (" + model.getDateTime()
                + ") Problem scheduling service start/end: " + interval, e);
    }

    // LOG.trace(String.format(
    // "t=%.4f (%s) Service %d scheduled for %.2f-%.2f (%s)",
    // model.getSimTime(), model.getDateTime(), getId(),
    // this.startTime, endTime, interval));
}

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   w  w w .j a v  a 2  s. com*/
 * @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.almende.eve.agent.MeetingAgent.java

License:Apache License

/**
 * Merge the busy intervals of all attendees, and the preferred intervals
 *///w  w w  .  j  a  v a 2 s  . c  o  m
private void mergeTimeConstraints() {
    final ArrayList<Interval> infeasibleIntervals = new ArrayList<Interval>();
    final ArrayList<Weight> preferredIntervals = new ArrayList<Weight>();

    final Activity activity = getActivity();
    if (activity != null) {
        // read and merge the stored busy intervals of all attendees
        for (final Attendee attendee : activity.withConstraints().withAttendees()) {
            final String agent = attendee.getAgent();
            if (attendee.getResponseStatus() != RESPONSE_STATUS.declined) {
                if (new Boolean(true).equals(attendee.getOptional())) {
                    // This attendee is optional.
                    // Add its busy intervals to the soft constraints
                    final List<Interval> attendeeBusy = getAgentBusy(agent);
                    if (attendeeBusy != null) {
                        for (final Interval i : attendeeBusy) {
                            final Weight wi = new Weight(i.getStart(), i.getEnd(),
                                    WEIGHT_BUSY_OPTIONAL_ATTENDEE);

                            preferredIntervals.add(wi);
                        }
                    }
                } else {
                    // this attendee is required.
                    // Add its busy intervals to the hard constraints
                    final List<Interval> attendeeBusy = getAgentBusy(agent);
                    if (attendeeBusy != null) {
                        infeasibleIntervals.addAll(attendeeBusy);
                    }
                }
            }
            // else This attendee declined. Ignore this attendees busy
            // interval
        }

        // read the time preferences and add them to the soft constraints
        final List<Preference> preferences = activity.withConstraints().withTime().withPreferences();
        for (final Preference p : preferences) {
            if (p != null) {
                final Weight wi = new Weight(new DateTime(p.getStart()), new DateTime(p.getEnd()),
                        p.getWeight());

                preferredIntervals.add(wi);
            }
        }
    }

    // add office hours profile to the soft constraints
    // TODO: don't include (hardcoded) office hours here, should be handled
    // by a PersonalAgent
    final DateTime timeMin = DateTime.now();
    final DateTime timeMax = timeMin.plusDays(LOOK_AHEAD_DAYS);
    final List<Interval> officeHours = IntervalsUtil.getOfficeHours(timeMin, timeMax);
    for (final Interval i : officeHours) {
        final Weight wi = new Weight(i, WEIGHT_OFFICE_HOURS);
        preferredIntervals.add(wi);
    }

    // add delay penalties to the soft constraints
    final DateTime now = DateTime.now();
    final MutableDateTime d = new MutableDateTime(now.getYear(), now.getMonthOfYear(), now.getDayOfMonth(), 0,
            0, 0, 0);
    for (int i = 0; i <= LOOK_AHEAD_DAYS; i++) {
        final DateTime start = d.toDateTime();
        final DateTime end = start.plusDays(1);
        final Weight wi = new Weight(start, end, WEIGHT_DELAY_PER_DAY * i);
        preferredIntervals.add(wi);
        d.addDays(1);
    }

    // order and store the aggregated lists with intervals
    IntervalsUtil.order(infeasibleIntervals);
    getState().put("infeasible", infeasibleIntervals);
    WeightsUtil.order(preferredIntervals);
    getState().put("preferred", preferredIntervals);
}

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

License:Apache License

/**
 * Calculate whether given interval is feasible (i.e. does not overlap with
 * any of the infeasible intervals, and is not in the past)
 * /*from  ww w  .  j a  v a2 s.  c om*/
 * @param infeasibleIntervals
 *            list with intervals ordered by start
 * @param timeMin
 * @param timeMax
 * @return feasible
 */
private boolean calculateFeasible(final List<Interval> infeasibleIntervals, final Interval test) {
    if (test.getStart().isBeforeNow()) {
        // interval starts in the past
        return false;
    }

    for (final Interval interval : infeasibleIntervals) {
        if (test.overlaps(interval)) {
            return false;
        }
        if (interval.getStart().isAfter(test.getEnd())) {
            // as the list is ordered, we can exit as soon as we have an
            // interval which starts after the wanted interval.
            break;
        }
    }

    return true;
}

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

License:Apache License

/**
 * Retrieve the feasible and preferred intervals.
 * //from  w  w  w. j  a v a 2  s .  co m
 * @return the intervals
 */
// TODO: remove this temporary method
public ObjectNode getIntervals() {
    final ObjectNode intervals = JOM.createObjectNode();

    final List<Interval> infeasible = getState().get("infeasible", new TypeUtil<ArrayList<Interval>>() {
    });
    final List<Weight> preferred = getState().get("preferred", new TypeUtil<ArrayList<Weight>>() {
    });
    final List<Weight> solutions = calculateSolutions();

    // merge the intervals
    List<Interval> mergedInfeasible = null;
    List<Weight> mergedPreferred = null;
    if (infeasible != null) {
        mergedInfeasible = IntervalsUtil.merge(infeasible);
    }
    if (preferred != null) {
        mergedPreferred = WeightsUtil.merge(preferred);
    }

    if (infeasible != null) {
        final ArrayNode arr = JOM.createArrayNode();
        for (final Interval interval : infeasible) {
            final ObjectNode o = JOM.createObjectNode();
            o.put("start", interval.getStart().toString());
            o.put("end", interval.getEnd().toString());
            arr.add(o);
        }
        intervals.put("infeasible", arr);
    }

    if (preferred != null) {
        final ArrayNode arr = JOM.createArrayNode();
        for (final Weight weight : preferred) {
            final ObjectNode o = JOM.createObjectNode();
            o.put("start", weight.getStart().toString());
            o.put("end", weight.getEnd().toString());
            o.put("weight", weight.getWeight());
            arr.add(o);
        }
        intervals.put("preferred", arr);
    }

    if (solutions != null) {
        final ArrayNode arr = JOM.createArrayNode();
        for (final Weight weight : solutions) {
            final ObjectNode o = JOM.createObjectNode();
            o.put("start", weight.getStart().toString());
            o.put("end", weight.getEnd().toString());
            o.put("weight", weight.getWeight());
            arr.add(o);
        }
        intervals.put("solutions", arr);
    }

    if (mergedInfeasible != null) {
        final ArrayNode arr = JOM.createArrayNode();
        for (final Interval i : mergedInfeasible) {
            final ObjectNode o = JOM.createObjectNode();
            o.put("start", i.getStart().toString());
            o.put("end", i.getEnd().toString());
            arr.add(o);
        }
        intervals.put("mergedInfeasible", arr);
    }

    if (mergedPreferred != null) {
        final ArrayNode arr = JOM.createArrayNode();
        for (final Weight wi : mergedPreferred) {
            final ObjectNode o = JOM.createObjectNode();
            o.put("start", wi.getStart().toString());
            o.put("end", wi.getEnd().toString());
            o.put("weight", wi.getWeight());
            arr.add(o);
        }
        intervals.put("mergedPreferred", arr);
    }

    return intervals;
}