Example usage for org.joda.time Interval Interval

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

Introduction

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

Prototype

public Interval(Object interval, Chronology chronology) 

Source Link

Document

Constructs a time interval by converting or copying from another object, overriding the chronology.

Usage

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

License:Apache License

/**
 * Schedule the meeting based on currently known event status, infeasible
 * intervals, and preferences//w ww  .ja  v  a  2  s.  c  om
 * 
 * @return rescheduled Returns true if the activity has been rescheduled
 *         When rescheduled, events must be synchronized again with
 *         syncEvents.
 */
private boolean scheduleActivity() {
    LOG.info("scheduleActivity started"); // TODO: cleanup
    final State state = getState();
    final Activity activity = state.get("activity", Activity.class);
    if (activity == null) {
        return false;
    }

    // read planned start and end from the activity
    DateTime activityStart = null;
    if (activity.withStatus().getStart() != null) {
        activityStart = new DateTime(activity.withStatus().getStart());
    }
    DateTime activityEnd = null;
    if (activity.withStatus().getEnd() != null) {
        activityEnd = new DateTime(activity.withStatus().getEnd());
    }
    Interval activityInterval = null;
    if (activityStart != null && activityEnd != null) {
        activityInterval = new Interval(activityStart, activityEnd);
    }

    // calculate solutions
    final List<Weight> solutions = calculateSolutions();
    if (solutions.size() > 0) {
        // there are solutions. yippie!
        final Weight solution = solutions.get(0);
        if (activityInterval == null || !solution.getInterval().equals(activityInterval)) {
            // interval is changed, save new interval
            final Status status = activity.withStatus();
            status.setStart(solution.getStart().toString());
            status.setEnd(solution.getEnd().toString());
            status.setActivityStatus(Status.ACTIVITY_STATUS.planned);
            status.setUpdated(DateTime.now().toString());
            state.put("activity", activity);
            // TODO: cleanup logging
            LOG.info("Activity replanned at " + solution.toString());
            try {
                // TODO: cleanup
                LOG.info("Replanned activity: " + JOM.getInstance().writeValueAsString(activity));
            } catch (final Exception e) {
            }
            return true;
        }
        // planning did not change. nothing to do.
    } else {
        if (activityStart != null || activityEnd != null) {
            // no solution
            final Issue issue = new Issue();
            issue.setCode(Issue.NO_PLANNING);
            issue.setType(Issue.TYPE.error);
            issue.setMessage("No free interval found for the meeting");
            issue.setTimestamp(DateTime.now().toString());
            // TODO: generate hints
            addIssue(issue);

            final Status status = activity.withStatus();
            status.setStart(null);
            status.setEnd(null);
            status.setActivityStatus(Status.ACTIVITY_STATUS.error);
            status.setUpdated(DateTime.now().toString());
            state.put("activity", activity);
            LOG.info(issue.getMessage()); // TODO: cleanup logging
            return true;
        }
        // planning did not change (no solution was already the case)
    }

    return false;
}

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  a2s  .  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.almende.eve.agent.MeetingAgent.java

License:Apache License

/**
 * Start automatic updating//www  . j  a  va2s .com
 * The interval of the update task depends on the timestamp the activity
 * is last updated. When recently updated, the interval is smaller.
 * interval is minimum 10 sec and maximum 1 hour.
 */
public void startAutoUpdate() {
    final State state = getState();
    final Activity activity = getActivity();

    // determine the interval (1 hour by default)
    final long TEN_SECONDS = 10 * 1000;
    final long ONE_HOUR = 60 * 60 * 1000;
    long interval = ONE_HOUR; // default is 1 hour
    if (activity != null) {
        final String updated = activity.withStatus().getUpdated();
        if (updated != null) {
            final DateTime dateUpdated = new DateTime(updated);
            final DateTime now = DateTime.now();
            interval = new Interval(dateUpdated, now).toDurationMillis();
        }
    }
    if (interval < TEN_SECONDS) {
        interval = TEN_SECONDS;
    }
    if (interval > ONE_HOUR) {
        interval = ONE_HOUR;
    }

    // stop any running task
    stopAutoUpdate();

    // schedule an update task and store the task id
    final JSONRequest request = new JSONRequest("update", null);
    final String task = getScheduler().createTask(request, interval);
    state.put("updateTask", task);

    LOG.info("Auto update started. Interval = " + interval + " milliseconds");
}

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

License:Apache License

/**
 * Convert a calendar event into an activity
 * /*from ww  w .  j a v a2s.com*/
 * @param event
 * @return activity
 */
private Activity convertEventToActivity(final ObjectNode event) {
    final Activity activity = new Activity();

    // agent
    URI agent = null;
    if (event.has("agent")) {
        agent = URI.create(event.get("agent").asText());
    }
    activity.setAgent(agent);

    // summary
    String summary = null;
    if (event.has("summary")) {
        summary = event.get("summary").asText();
    }
    activity.setSummary(summary);

    // description
    String description = null;
    if (event.has("description")) {
        description = event.get("description").asText();
    }
    activity.setDescription(description);

    // updated
    String updated = null;
    if (event.has("updated")) {
        updated = event.get("updated").asText();
    }
    activity.withStatus().setUpdated(updated);

    // start
    String start = null;
    if (event.with("start").has("dateTime")) {
        start = event.with("start").get("dateTime").asText();
    }
    activity.withStatus().setStart(start);

    // end
    String end = null;
    if (event.with("end").has("dateTime")) {
        end = event.with("end").get("dateTime").asText();
    }
    activity.withStatus().setEnd(end);

    // duration
    if (start != null && end != null) {
        final Interval interval = new Interval(new DateTime(start), new DateTime(end));
        final Long duration = interval.toDurationMillis();
        activity.withConstraints().withTime().setDuration(duration);
    }

    // location
    String location = null;
    if (event.has("location")) {
        location = event.get("location").asText();
    }
    activity.withConstraints().withLocation().setSummary(location);

    return activity;
}

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

License:Apache License

/**
 * Retrieve the busy intervals of a calendar agent
 * //from w w w . j  a v a2 s  . c om
 * @param agent
 */
private void updateBusyInterval(@Name("agent") final String agent) {
    try {
        // create parameters with the boundaries of the interval to be
        // retrieved
        final ObjectNode params = JOM.createObjectNode();
        final DateTime timeMin = DateTime.now();
        final DateTime timeMax = timeMin.plusDays(LOOK_AHEAD_DAYS);
        params.put("timeMin", timeMin.toString());
        params.put("timeMax", timeMax.toString());

        // exclude the event managed by this agent from the busy intervals
        final String eventId = getAgentData(agent).eventId;
        if (eventId != null) {
            final ArrayNode excludeEventIds = JOM.createArrayNode();
            excludeEventIds.add(eventId);
            params.put("excludeEventIds", excludeEventIds);
        }

        // get the busy intervals from the agent
        final ArrayNode array = send(URI.create(agent), "getBusy", params, ArrayNode.class);

        // convert from ArrayNode to List
        final List<Interval> busy = new ArrayList<Interval>();
        for (int i = 0; i < array.size(); i++) {
            final ObjectNode obj = (ObjectNode) array.get(i);
            final String start = obj.has("start") ? obj.get("start").asText() : null;
            final String end = obj.has("end") ? obj.get("end").asText() : null;
            busy.add(new Interval(new DateTime(start), new DateTime(end)));
        }

        // store the interval in the state
        putAgentBusy(agent, busy);

    } catch (final JSONRPCException e) {
        addIssue(TYPE.warning, Issue.JSONRPCEXCEPTION, e.getMessage());
        LOG.log(Level.WARNING, "", e);
    } catch (final Exception e) {
        addIssue(TYPE.warning, Issue.EXCEPTION, e.getMessage());
        LOG.log(Level.WARNING, "", e);
    }
}

From source file:com.almende.eve.entity.Weight.java

License:Apache License

/**
 * Instantiates a new weight.//from  ww w  . j a v a 2s. com
 * 
 * @param start
 *            the start
 * @param end
 *            the end
 * @param weight
 *            the weight
 */
public Weight(final DateTime start, final DateTime end, final Double weight) {
    interval = new Interval(start, end);
    this.weight = weight;
}

From source file:com.almende.eve.scheduler.clock.RunnableClock.java

License:Apache License

@Override
public void run() {
    synchronized (TIMELINE) {
        while (!TIMELINE.isEmpty()) {
            final ClockEntry ce = TIMELINE.firstEntry().getValue();
            if (future != null) {
                future.cancel(false);//from ww  w  . jav  a  2s . c o m
                future = null;
            }
            final DateTime now = DateTime.now();
            if (ce.getDue().isBefore(now)) {
                TIMELINE.remove(ce);
                POOL.execute(ce.getCallback());
                continue;
            }
            final long interval = new Interval(now, ce.getDue()).toDurationMillis();
            future = POOL.schedule(this, interval, TimeUnit.MILLISECONDS);
            break;
        }
    }
}

From source file:com.anasoft.os.daofusion.bitemporal.PersistentInterval.java

License:Apache License

public Object nullSafeGet(ResultSet resultSet, String[] names, SessionImplementor session, Object owner)
        throws HibernateException, SQLException {
    if (resultSet == null) {
        return null;
    }// w  ww . j a  va2s . c  om
    PersistentDateTime pst = new PersistentDateTime();
    DateTime start = (DateTime) pst.nullSafeGet(resultSet, names[0]);
    DateTime end = (DateTime) pst.nullSafeGet(resultSet, names[1]);
    if (start == null || end == null) {
        return null;
    }
    return new Interval(start, end);
}

From source file:com.axelor.apps.base.service.administration.AbstractBatch.java

License:Open Source License

private int getDuring() {

    return new Interval(batch.getStartDate(), batch.getEndDate()).toDuration().toStandardSeconds()
            .toStandardMinutes().getMinutes();

}

From source file:com.axelor.apps.base.service.DurationServiceImpl.java

License:Open Source License

public BigDecimal computeDurationInDays(DateTime startDate, DateTime endDate) {
    return new BigDecimal(new Interval(startDate, endDate).toDuration().toStandardDays().getDays());
}