Package com.almende.eve.state

Examples of com.almende.eve.state.State


   *         When rescheduled, events must be synchronized again with
   *         syncEvents.
   */
  private boolean scheduleActivity() {
    logger.info("scheduleActivity started"); // TODO: cleanup
    State state = getState();
    Activity activity = (Activity) state.get("activity");
    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
    List<Weight> solutions = calculateSolutions();
    if (solutions.size() > 0) {
      // there are solutions. yippie!
      Weight solution = solutions.get(0);
      if (activityInterval == null ||
          !solution.getInterval().equals(activityInterval)) {
        // interval is changed, save new interval
        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);
        logger.info("Activity replanned at " + solution.toString()); // TODO: cleanup logging
        try {
          // TODO: cleanup
          logger.info("Replanned activity: " + JOM.getInstance().writeValueAsString(activity));
        } catch (Exception e) {}
        return true;
      }
      else {
        // planning did not change. nothing to do.
      }
    }
    else {
      if (activityStart != null || activityEnd != null) {
        // no solution
        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);
 
        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);
        logger.info(issue.getMessage()); // TODO: cleanup logging
        return true;
      }
      else {
        // planning did not change (no solution was already the case)
View Full Code Here


   */
  @SuppressWarnings("unchecked")
  private List<Weight> calculateSolutions() {
    logger.info("calculateSolutions started"); // TODO: cleanup
   
    State state = getState();
    List<Weight> solutions = new ArrayList<Weight>();
   
    // get the activity
    Activity activity = (Activity) state.get("activity");
    if (activity == null) {
      return solutions;
    }
   
    // get infeasible intervals
    List<Interval> infeasible = (List<Interval>) state.get("infeasible");
    if (infeasible == null) {
      infeasible = new ArrayList<Interval>();
    }
   
    // get preferred intervals
    List<Weight> preferred = (List<Weight>) state.get("preferred");
    if (preferred == null) {
      preferred = new ArrayList<Weight>();
    }
   
    // get the duration of the activity
View Full Code Here

   * @throws JSONRPCException
   * @throws JsonMappingException
   * @throws JsonParseException
   */
  public void startAutoUpdate() {
    State state = getState();
    Activity activity = getActivity();
   
    // determine the interval (1 hour by default)
    long TEN_SECONDS = 10 * 1000;
    long ONE_HOUR = 60 * 60 * 1000;
    long interval = ONE_HOUR; // default is 1 hour
    if (activity != null) {
      String updated = activity.withStatus().getUpdated();
      if (updated != null) {
        DateTime dateUpdated = new DateTime(updated);
        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
    JSONRequest request = new JSONRequest("update", null);
    String task = getScheduler().createTask(request, interval);
    state.put("updateTask", task);

    logger.info("Auto update started. Interval = " + interval
        + " milliseconds");
  }
View Full Code Here

  /**
   * Stop automatic updating
   */
  public void stopAutoUpdate() {
    State state = getState();

    String task = (String) state.get("updateTask");
    if (task != null) {
      getScheduler().cancelTask(task);
      state.remove("updateTask");
    }

    logger.info("Auto update stopped");
  }
View Full Code Here

   * @param agentUrl
   * @param data
   */
  @SuppressWarnings("unchecked")
  private void putAgentData(String agentUrl, AgentData data) {
    State state = getState();
    HashMap<String, AgentData> calendarAgents =
        (HashMap<String, AgentData>) state.get("calendarAgents");
    if (calendarAgents == null) {
      calendarAgents = new HashMap<String, AgentData>();
    }

    calendarAgents.put(agentUrl, data);
    state.put("calendarAgents", calendarAgents);
  }
View Full Code Here

   * @param agent
   * @param data
   */
  @SuppressWarnings("unchecked")
  private void removeAgentData(String agent) {
    State state = getState();
    HashMap<String, AgentData> calendarAgents = (HashMap<String, AgentData>) state
        .get("calendarAgents");
    if (calendarAgents != null && calendarAgents.containsKey(agent)) {
      calendarAgents.remove(agent);
      state.put("calendarAgents", calendarAgents);
    }
  }
View Full Code Here

   * @param agent
   */
  // TODO: the method syncEvent has grown to large. split it up
  private void syncEvent(@Name("agent") String agent) {
    logger.info("syncEvent started for agent " + agent);
    State state = getState();

    // retrieve event from calendar agent
    ObjectNode event = getEvent(agent);
    if (event == null) {
      event = JOM.createObjectNode();
    }
    Activity eventActivity = convertEventToActivity(event);
   
    // verify all kind of stuff
    Activity activity = (Activity) state.get("activity");
    if (activity == null) {
      return; // oops no activity at all
    }
    if (activity.withStatus().getStart() == null ||
        activity.withStatus().getEnd() == null) {
      return; // activity is not yet planned. cancel synchronization
    }
    Attendee attendee = activity.withConstraints().getAttendee(agent);
    if (attendee == null) {
      return; // unknown attendee
    }
    if (attendee.getResponseStatus() == Attendee.RESPONSE_STATUS.declined) {
      // attendee does not want to attend
      clearAttendee(agent);
      return;
    }
   
    // check if the activity or the retrieved event is changed since the
    // last synchronization
    AgentData agentData = getAgentData(agent);
    boolean activityChanged = !equalsDateTime(agentData.activityUpdated,
        activity.withStatus().getUpdated());
    boolean eventChanged = !equalsDateTime(agentData.eventUpdated,
        eventActivity.withStatus().getUpdated());
    boolean changed = activityChanged || eventChanged;   
    if (changed && activity.isNewerThan(eventActivity)) {
      // activity is updated (event is out-dated or not yet existing)

      // merge the activity into the event
      mergeActivityIntoEvent(event, activity);
     
      // TODO: if attendee cannot attend (=optional or declined), show this somehow in the event
     
      // save the event
      ObjectNode params = JOM.createObjectNode();
      params.put("event", event);
      try {
        // TODO: only update/create the event when the attendee
        // is not optional or is available at the planned time
        String method = event.has("id") ? "updateEvent" : "createEvent";
        ObjectNode updatedEvent = send(agent, method, params,
            ObjectNode.class);

        // update the agent data
        agentData.eventId = updatedEvent.get("id").asText();
        agentData.eventUpdated = updatedEvent.get("updated").asText();
        agentData.activityUpdated = activity.withStatus().getUpdated();
        putAgentData(agent, agentData);
      } catch (JSONRPCException e) {
        addIssue(TYPE.warning, Issue.JSONRPCEXCEPTION, e.getMessage());
        e.printStackTrace(); // TODO remove printing stacktrace
      } catch (Exception e) {
        addIssue(TYPE.warning, Issue.EXCEPTION, e.getMessage());
        e.printStackTrace(); // TODO remove printing stacktrace
      }
    } else if (changed) {
      // event is updated (activity is out-dated or both have the same
      // updated timestamp)
     
      // if start is changed, add this as preferences to the constraints
      if (!equalsDateTime(activity.withStatus().getStart(),
          eventActivity.withStatus().getStart())) {
        /* TODO: store the old interval as undesired?
        String oldStart = activity.withStatus().getStart();
        String oldEnd = activity.withStatus().getEnd();
        if (oldStart != null && oldEnd != null) {
          Preference undesired = new Preference ();
          undesired.setStart(oldStart);
          undesired.setEnd(oldEnd);
          undesired.setWeight(WEIGHT_UNDESIRED_INTERVAL);
          activity.getConstraints().getTime().addPreference(undesired); 
        }
        */
       
        // store the new interval as preferred
        String newStart = eventActivity.withStatus().getStart();
        String newEnd = eventActivity.withStatus().getEnd();
        if (newStart != null && newEnd != null) {
          Preference preferred = new Preference ();
          preferred.setStart(newStart);
          preferred.setEnd(newEnd);
          preferred.setWeight(WEIGHT_PREFERRED_INTERVAL);

          // overwrite other preferences with this new preference
          // TODO: all preferences are overwritten for now. Behavior should be changed.
          List<Preference> preferences = new ArrayList<Preference>();
          preferences.add(preferred);
          activity.getConstraints().getTime().setPreferences(preferences);       
         
          //activity.getConstraints().getTime().addPreference(preferred);
        }
      }
      else {
        // events are in sync, nothing to do
      }
     
      // update the activity
      activity.merge(eventActivity);
      state.put("activity", activity);

      // update the agent data
      agentData.eventId = event.get("id").asText();
      agentData.eventUpdated = event.get("updated").asText();
      agentData.activityUpdated = activity.withStatus().getUpdated();
View Full Code Here

      return agent;
    }
    // No agent found, normal initialization:
   
    // load the State
    final State state = getStateFactory().get(agentId);
    if (state == null) {
      // agent does not exist
      return null;
    }
    state.init();
   
    // read the agents class name from state
    final Class<?> agentType = state.getAgentType();
    if (agentType == null) {
      LOG.warning("Cannot instantiate agent. "
          + "Class information missing in the agents state "
          + "(agentId='" + agentId + "')");
      return null;
View Full Code Here

      final String agentId) throws InstantiationException,
      IllegalAccessException, InvocationTargetException,
      NoSuchMethodException, IOException {
   
    // create the state
    final State state = getStateFactory().create(agentId);
    state.setAgentType(agentType);
    state.init();
   
    // instantiate the agent
    final T agent = agentType.getConstructor().newInstance();
    agent.constr(this, state);
    agent.signalAgent(new AgentSignal<Void>(AgentSignal.CREATE));
View Full Code Here

      if (agentId == null){
        LOG.warning("Parameter 'id' is required for a file State.");
        return null;
      }
     
      State state = null;
      try {
        if (!exists(agentId)) {
          final String filename = getFilename(agentId);
          final File file = new File(filename);
         
View Full Code Here

TOP

Related Classes of com.almende.eve.state.State

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.