Exemplo n.º 1
1
  @Override
  public void handle(TaskSchedulerEvent event) {
    if (event.getType() == EventType.T_SCHEDULE) {
      if (event instanceof FragmentScheduleEvent) {
        FragmentScheduleEvent castEvent = (FragmentScheduleEvent) event;
        if (context.isLeafQuery()) {
          TaskAttemptScheduleContext taskContext = new TaskAttemptScheduleContext();
          Task task = Stage.newEmptyTask(context, taskContext, stage, nextTaskId++);
          task.addFragment(castEvent.getLeftFragment(), true);
          scheduledObjectNum++;
          if (castEvent.hasRightFragments()) {
            task.addFragments(castEvent.getRightFragments());
          }
          stage.getEventHandler().handle(new TaskEvent(task.getId(), TaskEventType.T_SCHEDULE));
        } else {
          fragmentsForNonLeafTask = new FileFragment[2];
          fragmentsForNonLeafTask[0] = castEvent.getLeftFragment();
          if (castEvent.hasRightFragments()) {
            Collection<Fragment> var = castEvent.getRightFragments();
            FileFragment[] rightFragments = var.toArray(new FileFragment[var.size()]);
            fragmentsForNonLeafTask[1] = rightFragments[0];
            if (rightFragments.length > 1) {
              broadcastFragmentsForNonLeafTask = new FileFragment[rightFragments.length - 1];
              System.arraycopy(
                  rightFragments,
                  1,
                  broadcastFragmentsForNonLeafTask,
                  0,
                  broadcastFragmentsForNonLeafTask.length);
            } else {
              broadcastFragmentsForNonLeafTask = null;
            }
          }
        }
      } else if (event instanceof FetchScheduleEvent) {
        FetchScheduleEvent castEvent = (FetchScheduleEvent) event;
        Map<String, List<FetchImpl>> fetches = castEvent.getFetches();
        TaskAttemptScheduleContext taskScheduleContext = new TaskAttemptScheduleContext();
        Task task = Stage.newEmptyTask(context, taskScheduleContext, stage, nextTaskId++);
        scheduledObjectNum++;
        for (Entry<String, List<FetchImpl>> eachFetch : fetches.entrySet()) {
          task.addFetches(eachFetch.getKey(), eachFetch.getValue());
          task.addFragment(fragmentsForNonLeafTask[0], true);
          if (fragmentsForNonLeafTask[1] != null) {
            task.addFragment(fragmentsForNonLeafTask[1], true);
          }
        }
        if (broadcastFragmentsForNonLeafTask != null
            && broadcastFragmentsForNonLeafTask.length > 0) {
          task.addFragments(Arrays.asList(broadcastFragmentsForNonLeafTask));
        }
        stage.getEventHandler().handle(new TaskEvent(task.getId(), TaskEventType.T_SCHEDULE));
      } else if (event instanceof TaskAttemptToSchedulerEvent) {
        TaskAttemptToSchedulerEvent castEvent = (TaskAttemptToSchedulerEvent) event;
        if (context.isLeafQuery()) {
          scheduledRequests.addLeafTask(castEvent);
        } else {
          scheduledRequests.addNonLeafTask(castEvent);
        }

        if (needWakeup.getAndSet(false)) {
          // wake up scheduler thread after scheduled
          synchronized (schedulingThread) {
            schedulingThread.notifyAll();
          }
        }
      }
    } else if (event.getType() == EventType.T_SCHEDULE_CANCEL) {
      // when a stage is killed, unassigned query unit attmpts are canceled from the scheduler.
      // This event is triggered by TaskAttempt.
      TaskAttemptToSchedulerEvent castedEvent = (TaskAttemptToSchedulerEvent) event;
      scheduledRequests.leafTasks.remove(castedEvent.getTaskAttempt().getId());
      LOG.info(
          castedEvent.getTaskAttempt().getId()
              + " is canceled from "
              + this.getClass().getSimpleName());
      ((TaskAttemptToSchedulerEvent) event)
          .getTaskAttempt()
          .handle(
              new TaskAttemptEvent(
                  castedEvent.getTaskAttempt().getId(), TaskAttemptEventType.TA_SCHEDULE_CANCELED));
    }
  }
  private void completeTask(TracksAction act) {
    final boolean badcert = _prefs.getBoolean(PreferenceConstants.BADCERT, false);
    final String username = _prefs.getString(PreferenceConstants.USERNAME, null);
    final String password = _prefs.getString(PreferenceConstants.PASSWORD, null);

    Task t = (Task) act.target;
    HttpResponse r;

    Log.d(TAG, "Marking task " + String.valueOf(t.getId()) + " as done");

    try {
      r =
          HttpConnection.put(
              PreferenceUtils.getUri(
                  _prefs, "todos/" + String.valueOf(t.getId()) + "/toggle_check.xml"),
              username,
              password,
              null,
              badcert);
    } catch (Exception e) {
      return;
    }

    t.remove();
    act.notify.sendEmptyMessage(0);
  }
Exemplo n.º 3
0
 @Test
 public void save_assignsIdToObject() {
   Task myTask = new Task("Mow the lawn", 1);
   myTask.save();
   Task savedTask = Task.all().get(0);
   assertEquals(myTask.getId(), savedTask.getId());
 }
 @Test
 public void testGetTasksWithFilter() throws Exception {
   List<Task> tasks = taskService.getTasks(TaskService.Filter.ALL);
   for (Task task : tasks) {
     assertNotNull(task);
     assertTrue(task.getId() > 0);
     assertNotNull(task.getName());
     assertNotNull(task.getDescription());
     assertNotNull(task.getTestSteps());
     assertNotNull(task.getCreator());
     assertNotNull(task.getAssignee());
     assertNotNull(task.getStatus());
     assertNotNull(task.getPriority());
     assertNotNull(task.getType());
   }
   tasks = taskService.getTasks(TaskService.Filter.CREATOR, "1");
   for (Task task : tasks) {
     assertNotNull(task);
     assertTrue(task.getId() > 0);
     assertNotNull(task.getName());
     assertNotNull(task.getDescription());
     assertNotNull(task.getTestSteps());
     assertNotNull(task.getCreator());
     assertNotNull(task.getAssignee());
     assertNotNull(task.getStatus());
     assertNotNull(task.getPriority());
     assertNotNull(task.getType());
   }
 }
Exemplo n.º 5
0
 public List<Task> doTaskSearch(String query, int user_id) {
   List<TaskEntry> list = taskEntryRepository.findByTitleOrDescription(query, query);
   List<Task> ret = new ArrayList<>();
   for (TaskEntry entry : list) {
     System.out.println(
         "entry userID = "
             + entry.getUser_id()
             + " required UserID = "
             + Integer.toString(user_id));
     System.out.println(entry.getType());
     String type = entry.getType();
     if ((type.equals("task") || type.equals("taskItem"))
         && entry.getUser_id().equals(Integer.toString(user_id))) {
       if (type.equals("task")) {
         Task task = OrganizerDAO.getTaskByTitle(user_id, entry.getTitle());
         ret.add(task);
       }
       if (type.equals("taskItem")) {
         TaskItem item = OrganizerDAO.getTaskId(Integer.parseInt(entry.getObj_id()));
         Task task = OrganizerDAO.getTaskById(item.getTask_id());
         List<TaskItem> taskList = OrganizerDAO.getTaskItems(task.getId());
         if (taskList != null) {
           task.setTaskList(taskList);
           task.setTaskListSize(taskList.size());
         }
         ret.add(task);
       }
     }
   }
   return ret;
 }
Exemplo n.º 6
0
  @Override
  public void run() {
    logger.log(Level.INFO, "---- STARTED TASK: {0}", task.getId());
    try {
      int runningTime = randon.nextInt(10 - 3) + 3;

      Thread.sleep(runningTime * 1000);

      task.setResult("DONE TASK " + task.getId());
      task.setRunning(false);

    } catch (InterruptedException ex) {
      Logger.getLogger(MultipleAsyncController.class.getName()).log(Level.SEVERE, null, ex);
    }
    logger.log(Level.INFO, "---- FINISHED RUNNABLE: {0}", task.getId());
  }
  private void doUpdate(@Nullable Runnable onComplete) {
    try {
      List<Task> issues =
          getIssuesFromRepositories(
              null, myConfig.updateIssuesCount, 0, false, new EmptyProgressIndicator());
      if (issues == null) return;

      synchronized (myIssueCache) {
        myIssueCache.clear();
        for (Task issue : issues) {
          myIssueCache.put(issue.getId(), issue);
        }
      }
      // update local tasks
      synchronized (myTasks) {
        for (Map.Entry<String, LocalTask> entry : myTasks.entrySet()) {
          Task issue = myIssueCache.get(entry.getKey());
          if (issue != null) {
            entry.getValue().updateFromIssue(issue);
          }
        }
      }
    } finally {
      if (onComplete != null) {
        onComplete.run();
      }
      myUpdating = false;
    }
  }
Exemplo n.º 8
0
 @Test
 public void find_findsTaskInDatabase_true() {
   Task myTask = new Task("Mow the lawn", 1);
   myTask.save();
   Task savedTask = Task.find(myTask.getId());
   assertTrue(myTask.equals(savedTask));
 }
  @Test
  public void testCreateTask() throws Exception {
    TaskBuilder builder = taskService.createTask();
    builder.creator(user);
    builder.project(project);
    builder.name(name);
    builder.description(desc);
    builder.testSteps(teststeps);
    builder.type(type);
    builder.estimated(8);
    builder.priority(priority);
    Task task = builder.build();

    task.store();

    assertNotNull(task);
    assertTrue(task.getId() > 0);
    assertEquals(name, task.getName());
    assertEquals(desc, task.getDescription());
    assertEquals(teststeps, task.getTestSteps());
    assertEquals(user.getName(), task.getCreator().getName());
    assertEquals(user.getName(), task.getAssignee().getName());
    assertEquals("New", task.getStatus().getName());
    assertEquals(priority, task.getPriority());
    assertEquals(type, task.getType());
  }
Exemplo n.º 10
0
  private void removeCompletedTasks() {
    ArrayList<Long> removedTaskIds = new ArrayList<>();
    for (int i = 0, count = mTaskAdapter.getCount(); i < count; ) {
      Task task = mTaskAdapter.getItem(i);
      if (task.getDone()) {
        removedTaskIds.add(task.getId());
        mTaskAdapter.remove(task);
        count--;
      } else {
        i++;
      }
    }
    if (removedTaskIds.isEmpty()) return;

    boolean first = true;
    String idsStr = "";
    for (long id : removedTaskIds) {
      if (first) {
        first = false;
      } else {
        idsStr += ",";
      }
      idsStr += "" + id;
    }
    SQLiteDatabase db = mDbHelper.getWritableDatabase();
    db.delete(Task.TABLE_NAME, String.format("%s IN (%s)", Task._ID, idsStr), new String[] {});
    db.close();
  }
 @Nullable
 public String getTaskComment(@NotNull Task task) {
   return isShouldFormatCommitMessage()
       ? myCommitMessageFormat
           .replace("{id}", task.getId())
           .replace("{summary}", task.getSummary())
       : null;
 }
Exemplo n.º 12
0
 @Test
 public void save_savesCategoryIdIntoDB_true() {
   Category myCategory = new Category("Household chores");
   myCategory.save();
   Task myTask = new Task("Mow the lawn", myCategory.getId());
   myTask.save();
   Task savedTask = Task.find(myTask.getId());
   assertEquals(savedTask.getCategoryId(), myCategory.getId());
 }
Exemplo n.º 13
0
 @Override
 public boolean equals(Object otherTask) {
   if (!(otherTask instanceof Task)) {
     return false;
   } else {
     Task newTask = (Task) otherTask;
     return this.getDescription().equals(newTask.getDescription())
         && this.getId() == newTask.getId();
   }
 }
Exemplo n.º 14
0
 @AfterClass
 public static void afterClass() throws Exception {
   jToggl.destroyTimeEntry(timeEntry.getId());
   jToggl.destroyClient(client.getId());
   try {
     jToggl.destroyTask(task.getId());
   } catch (Exception e) {
     // Ignore because Task is only for paying customers
   }
 }
 public String suggestBranchName(Task task) {
   if (task.isIssue() && StringUtil.isNotEmpty(task.getNumber())) {
     return task.getId().replace(' ', '-');
   } else {
     String summary = task.getSummary();
     List<String> words = StringUtil.getWordsIn(summary);
     String[] strings = ArrayUtil.toStringArray(words);
     return StringUtil.join(strings, 0, Math.min(2, strings.length), "-");
   }
 }
Exemplo n.º 16
0
 /** ТЕСТ НАЧАЛО */
 public static void main(String[] args) {
   for (int i = 1; i < 10; i++) {
     Task t = new Task();
     long[] array = t.getPointNumber();
     System.out.print("Task #" + t.getId() + " Have digital: ");
     for (long a : array) {
       System.out.print(a + "; ");
     }
     System.out.println();
   }
 }
Exemplo n.º 17
0
  /**
   * @param tasks
   * @return
   */
  public List<TaskVo> buildTaskVos(List<Task> tasks) {
    List<TaskVo> taskRtn = new ArrayList<>();

    if (null != tasks && !tasks.isEmpty()) {
      // 根据流程的业务ID查询实体并关联
      for (Task task : tasks) {

        String processInstanceId = task.getProcessInstanceId();
        ProcessInstance processInstance =
            runtimeService
                .createProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .active()
                .singleResult();
        String businessName = (String) task.getTaskLocalVariables().get(WebConstants.BUSINESS_NAME);
        String taskId = task.getId();
        String businessKey = processInstance.getBusinessKey();

        if (StringUtils.isBlank(businessKey)) {
          continue;
        }
        if (StringUtils.isBlank(businessName)) {
          businessName = getBusinessName(taskId, businessKey);
        }

        ProcessDefinition processDefinition =
            getProcessDefinition(processInstance.getProcessDefinitionId());
        int version = processDefinition.getVersion();
        String taskName = task.getName();
        String createTime =
            DateUtils.SINGLETONE.format(task.getCreateTime(), DateUtils.YYYY_MM_DD_HH_MM_SS);
        String assignee = task.getAssignee();
        boolean suspended = task.isSuspended();

        String processDefinitionId = processInstance.getProcessDefinitionId();

        TaskVo taskInfo = new TaskVo();
        taskInfo.setProcessInstanceId(processInstanceId);
        taskInfo.setBusinessKey(businessKey);
        taskInfo.setProcessDefinitionId(processDefinitionId);
        taskInfo.setId(taskId);
        taskInfo.setName(taskName);
        taskInfo.setCreateTime(createTime);
        taskInfo.setAssignee(assignee);
        taskInfo.setSuspended(suspended);
        taskInfo.setVersion(version);
        taskInfo.setBusinessName(businessName);
        taskRtn.add(taskInfo);
      }
    }
    return taskRtn;
  }
 @Override
 public void setTaskState(Task task, TaskState state) throws Exception {
   String s;
   switch (state) {
     case IN_PROGRESS:
       s = "In+Progress";
       break;
     case RESOLVED:
       s = "fixed";
       break;
     default:
       s = state.name();
   }
   doREST("/rest/issue/execute/" + task.getId() + "?command=state+" + s, true);
 }
Exemplo n.º 19
0
 @Test
 public void testGetTaskByID() throws Exception {
   Optional<Task> optTask = taskService.getTaskByID(1);
   assertTrue(optTask.isPresent());
   Task task = optTask.get();
   assertNotNull(task);
   assertEquals(1, task.getId());
   assertNotNull(task.getName());
   assertNotNull(task.getDescription());
   assertNotNull(task.getTestSteps());
   assertNotNull(task.getCreator());
   assertNotNull(task.getAssignee());
   assertNotNull(task.getStatus());
   assertNotNull(task.getPriority());
   assertNotNull(task.getType());
 }
Exemplo n.º 20
0
 @Test
 public void testGetTaskByUserCommented() throws Exception {
   List<Task> tasks = taskService.getTaskByUserCommented(1);
   for (Task task : tasks) {
     assertNotNull(task);
     assertTrue(task.getId() > 0);
     assertNotNull(task.getName());
     assertNotNull(task.getDescription());
     assertNotNull(task.getTestSteps());
     assertNotNull(task.getCreator());
     assertNotNull(task.getAssignee());
     assertNotNull(task.getStatus());
     assertNotNull(task.getPriority());
     assertNotNull(task.getType());
   }
 }
Exemplo n.º 21
0
  private void onListItemClick(int position) {
    TasksAdapter adapter = (TasksAdapter) mListView.getAdapter();
    Task task = adapter.getItem(position);
    task.toggleDone();
    adapter.notifyDataSetChanged();

    SQLiteDatabase db = mDbHelper.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(Task.COLUMN_DONE, task.getDone());

    db.update(
        Task.TABLE_NAME,
        values,
        String.format("%s = ?", Task._ID),
        new String[] {"" + task.getId()});
    db.close();
  }
Exemplo n.º 22
0
  /**
   * Month conversion from entity object to jaxb model.
   *
   * @param data month entity object
   * @return jaxb model of month
   */
  public static Month transformMonthToModel(org.kaleta.scheduler.backend.entity.Month data) {
    Month model = new Month();

    model.setId(String.valueOf(data.getId()));

    Month.Specification specification = new Month.Specification();
    specification.setName(data.getName());
    specification.setDays(String.valueOf(data.getDaysNumber()));
    specification.setFirstDay(String.valueOf(data.getDayStartsWith()));
    for (Integer day : data.getPublicFreeDays()) {
      Month.Specification.FreeDay freeDay = new Month.Specification.FreeDay();
      freeDay.setDay(String.valueOf(day));
      specification.getFreeDayList().add(freeDay);
    }
    model.setSpecification(specification);

    Month.Schedule schedule = new Month.Schedule();
    for (Task task : data.getTasks()) {
      Month.Schedule.Task taskModel = new Month.Schedule.Task();
      taskModel.setId(String.valueOf(task.getId()));
      taskModel.setType(task.getType());
      taskModel.setDescription(task.getDescription());
      taskModel.setDay(String.valueOf(task.getDay()));
      taskModel.setStarts(task.getStarts().toString());
      taskModel.setDuration(task.getDuration().toString());
      taskModel.setPriority(String.valueOf(task.getPriority()));
      taskModel.setSuccessful(String.valueOf(task.getSuccessful()));
      schedule.getTaskList().add(taskModel);
    }
    model.setSchedule(schedule);

    Month.Accounting accounting = new Month.Accounting();
    for (Item item : data.getItems()) {
      Month.Accounting.Item itemModel = new Month.Accounting.Item();
      itemModel.setId(String.valueOf(item.getId()));
      itemModel.setType(item.getType());
      itemModel.setDescription(item.getDescription());
      itemModel.setDay(String.valueOf(item.getDay()));
      itemModel.setIncome(String.valueOf(item.getIncome()));
      itemModel.setAmount(String.valueOf(item.getAmount()));
      accounting.getItemList().add(itemModel);
    }
    model.setAccounting(accounting);

    return model;
  }
  /**
   * Returns control when task is complete.
   *
   * @param json
   * @param logger
   */
  private String waitForDeploymentCompletion(JSON json, OctopusApi api, Log logger) {
    final long WAIT_TIME = 5000;
    final double WAIT_RANDOM_SCALER = 100.0;
    JSONObject jsonObj = (JSONObject) json;
    String id = jsonObj.getString("TaskId");
    Task task = null;
    String lastState = "Unknown";
    try {
      task = api.getTask(id);
    } catch (IOException ex) {
      logger.error("Error getting task: " + ex.getMessage());
      return null;
    }

    logger.info("Task info:");
    logger.info("\tId: " + task.getId());
    logger.info("\tName: " + task.getName());
    logger.info("\tDesc: " + task.getDescription());
    logger.info("\tState: " + task.getState());
    logger.info("\n\nStarting wait...");
    boolean completed = task.getIsCompleted();
    while (!completed) {
      try {
        task = api.getTask(id);
      } catch (IOException ex) {
        logger.error("Error getting task: " + ex.getMessage());
        return null;
      }

      completed = task.getIsCompleted();
      lastState = task.getState();
      logger.info("Task state: " + lastState);
      if (completed) {
        break;
      }
      try {
        Thread.sleep(WAIT_TIME + (long) (Math.random() * WAIT_RANDOM_SCALER));
      } catch (InterruptedException ex) {
        logger.info("Wait interrupted!");
        logger.info(ex.getMessage());
        completed = true; // bail out of wait loop
      }
    }
    logger.info("Wait complete!");
    return lastState;
  }
Exemplo n.º 24
0
 public void FillList() {
   /*   for (int i=0; i<FAKE_NUMBER; i++)
   * {
          pushTask("Mock task " + i);
      }
      pushTask("Get milk");
      pushTask("Call Amnon");
      pushTask("Taks a vacation");
      pushTask("Prepare shenkar mobile workshop #2");
      pushTask("Find a job");
      SQLiteDatabase db = this.getReadableDatabase();
      Reading all contacts*/
   Log.d("Reading: ", "Reading all contacts..");
   tasks = getAllContacts();
   for (Task cn : tasks) {
     String log = "Id: " + cn.getId() + " ,Name: " + cn.getDescription();
     // Writing Contacts to log
     Log.d("Name: ", log);
   }
 }
  @Override
  protected void doOKAction() {
    TaskManagerImpl taskManager = (TaskManagerImpl) TaskManager.getManager(myProject);

    taskManager.getState().markAsInProgress = isMarkAsInProgress();
    if (taskManager.isVcsEnabled()) {
      taskManager.getState().createChangelist = myCreateChangelist.isSelected();
    }

    TaskRepository repository = myTask.getRepository();
    if (isMarkAsInProgress() && repository != null) {
      try {
        repository.setTaskState(myTask, TaskState.IN_PROGRESS);
      } catch (Exception ex) {
        Messages.showErrorDialog(myProject, "Could not set state for " + myTask.getId(), "Error");
        LOG.warn(ex);
      }
    }
    taskManager.activateTask(myTask, isClearContext(), isCreateChangelist());
    if (myTask.getType() == TaskType.EXCEPTION && AnalyzeTaskStacktraceAction.hasTexts(myTask)) {
      AnalyzeTaskStacktraceAction.analyzeStacktrace(myTask, myProject);
    }
    super.doOKAction();
  }
Exemplo n.º 26
0
    public static List<Version> filterPrivateVersions(Task task) {
        if (task.getVersions().isEmpty()) {
            throw new IllegalStateException(
                    "task has no versions: " + task.getId()
            );
        }

        final List<Version> versions = new ArrayList<Version>(
            task.getVersions().values()
        );
        final List<Version> versionsPriv = new ArrayList<Version>(
                versions
        );
        for (
            Iterator<Version> verIt = versionsPriv.iterator();
            verIt.hasNext();
        ) {
            if (verIt.next().isShared()) {
                verIt.remove();
            }
        }

        return versionsPriv.isEmpty() ? versions : versionsPriv;
    }
  public void testAddRemoveComment() {
    Map vars = fillVariables(users, groups);

    String str =
        "(with (new Task()) { priority = 55, taskData = (with( new TaskData()) { createdOn = now, activationTime = now}), ";
    str += "deadlines = new Deadlines(),";
    str += "delegation = new Delegation(),";
    str += "peopleAssignments = new PeopleAssignments(),";
    str += "names = [ new I18NText( 'en-UK', 'This is my task name')] })";

    Task task = (Task) eval(new StringReader(str), vars);
    client.addTask(task, null);

    long taskId = task.getId();

    Comment comment = new Comment();
    Date addedAt = new Date(System.currentTimeMillis());
    comment.setAddedAt(addedAt);
    comment.setAddedBy(users.get("luke"));
    comment.setText("This is my comment1!!!!!");

    client.addComment(taskId, comment);

    long commentId = comment.getId();

    Task task1 = client.getTask(taskId);
    // We are reusing this for local clients where the object is the same
    // assertNotSame(task, task1);
    // assertFalse(task.equals(task1));

    List<Comment> comments1 = task1.getTaskData().getComments();
    assertEquals(1, comments1.size());
    Comment returnedComment = comments1.get(0);
    assertEquals("This is my comment1!!!!!", returnedComment.getText());
    assertEquals(addedAt, returnedComment.getAddedAt());
    assertEquals(users.get("luke"), returnedComment.getAddedBy());

    assertEquals(commentId, (long) returnedComment.getId());

    // Make the same as the returned tasks, so we can test equals
    task.getTaskData().setComments(comments1);
    task.getTaskData().setStatus(Status.Created);
    assertEquals(task, task1);

    // test we can have multiple comments
    comment = new Comment();
    addedAt = new Date(System.currentTimeMillis());
    comment.setAddedAt(addedAt);
    comment.setAddedBy(users.get("tony"));
    comment.setText("This is my comment2!!!!!");

    client.addComment(taskId, comment);
    long commentId2 = comment.getId();

    task1 = client.getTask(taskId);
    List<Comment> comments2 = task1.getTaskData().getComments();
    assertEquals(2, comments2.size());

    // make two collections the same and compare
    comments1.add(comment);
    assertTrue(CollectionUtils.equals(comments1, comments2));

    client.deleteComment(taskId, commentId2);

    task1 = client.getTask(taskId);
    comments2 = task1.getTaskData().getComments();
    assertEquals(1, comments2.size());

    assertEquals("This is my comment1!!!!!", comments2.get(0).getText());
  }
  private void updateTask(TracksAction act) {
    final boolean badcert = _prefs.getBoolean(PreferenceConstants.BADCERT, false);
    final String username = _prefs.getString(PreferenceConstants.USERNAME, null);
    final String password = _prefs.getString(PreferenceConstants.PASSWORD, null);

    Task t = (Task) act.target;

    Log.d(TAG, "Updating task " + String.valueOf(t.getId()));

    StringBuilder xml = new StringBuilder("<todo>");
    xml.append("<description>");
    xml.append(t.getDescription());
    xml.append("</description>");
    xml.append("<notes>");
    xml.append(t.getNotes() == null ? "" : t.getNotes());
    xml.append("</notes>");
    xml.append("<context-id type=\"integer\">");
    xml.append(String.valueOf(t.getContext().getId()));
    xml.append("</context-id>");

    xml.append("<project-id type=\"integer\"");
    if (t.getProject() == null) {
      xml.append(" nil=\"true\"></project-id>");
    } else {
      xml.append(">");
      xml.append(String.valueOf(t.getProject().getId()));
      xml.append("</project-id>");
    }

    xml.append("<due type=\"datetime\"");
    if (t.getDue() == null) {
      xml.append(" nil=\"true\"></due>");
    } else {
      xml.append(">");
      xml.append(DATEFORM.format(t.getDue()));
      xml.append("</due>");
    }

    xml.append("<show-from type=\"datetime\"");
    if (t.getShowFrom() == null) {
      xml.append(" nil=\"true\"></show-from>");
    } else {
      xml.append(">");
      xml.append(DATEFORM.format(t.getShowFrom()));
      xml.append("</show-from>");
    }

    xml.append("</todo>");

    Log.v(TAG, "Sending: " + xml.toString());

    try {
      HttpResponse r;
      int resp;

      if (t.getId() < 0) {
        Log.v(TAG, "Posting to todos.xml to create new task");
        r =
            HttpConnection.post(
                PreferenceUtils.getUri(_prefs, "todos.xml"),
                username,
                password,
                xml.toString(),
                badcert);
      } else {
        Log.v(TAG, "Putting to update existing task");
        r =
            HttpConnection.put(
                PreferenceUtils.getUri(_prefs, "todos/" + String.valueOf(t.getId()) + ".xml"),
                username,
                password,
                xml.toString(),
                badcert);
      }

      resp = r.getStatusLine().getStatusCode();

      if (resp == 200) {
        Log.d(TAG, "Successfully updated task");
        act.notify.sendEmptyMessage(SUCCESS_CODE);
      } else if (resp == 201) {
        Log.d(TAG, "Successfully created task.");
        String got = r.getFirstHeader("Location").getValue();
        got = got.substring(got.lastIndexOf('/') + 1);
        int tno = Integer.parseInt(got);
        t.setId(tno);
        Log.d(TAG, "ID of new task is: " + String.valueOf(tno));
        act.notify.sendEmptyMessage(SUCCESS_CODE);
      } else {
        Log.w(TAG, "Unexpected response from server: " + String.valueOf(resp));
        act.notify.sendEmptyMessage(UPDATE_FAIL_CODE);
      }
    } catch (Exception e) {
      Log.w(TAG, "Error updating task", e);
      act.notify.sendEmptyMessage(UPDATE_FAIL_CODE);
    }
  }
  public void testAddRemoveAttachment() throws Exception {
    Map vars = new HashMap();
    vars.put("users", users);
    vars.put("groups", groups);
    vars.put("now", new Date());

    String str =
        "(with (new Task()) { priority = 55, taskData = (with( new TaskData()) { createdOn = now, activationTime = now}), ";
    str += "deadlines = new Deadlines(),";
    str += "delegation = new Delegation(),";
    str += "peopleAssignments = new PeopleAssignments(),";
    str += "names = [ new I18NText( 'en-UK', 'This is my task name')] })";

    Task task = (Task) eval(new StringReader(str), vars);
    client.addTask(task, null);

    long taskId = task.getId();

    Attachment attachment = new Attachment();
    Date attachedAt = new Date(System.currentTimeMillis());
    attachment.setAttachedAt(attachedAt);
    attachment.setAttachedBy(users.get("luke"));
    attachment.setName("file1.txt");
    attachment.setAccessType(AccessType.Inline);
    attachment.setContentType("txt");

    byte[] bytes = "Ths is my attachment text1".getBytes();
    Content content = new Content();
    content.setContent(bytes);

    client.addAttachment(taskId, attachment, content);

    Task task1 = client.getTask(taskId);
    // For local clients this will be the same.. that's why is commented
    // assertNotSame(task, task1);
    // assertFalse(task.equals(task1));

    List<Attachment> attachments1 = task1.getTaskData().getAttachments();
    assertEquals(1, attachments1.size());
    Attachment returnedAttachment = attachments1.get(0);
    assertEquals(attachedAt, returnedAttachment.getAttachedAt());
    assertEquals(users.get("luke"), returnedAttachment.getAttachedBy());
    assertEquals(AccessType.Inline, returnedAttachment.getAccessType());
    assertEquals("txt", returnedAttachment.getContentType());
    assertEquals("file1.txt", returnedAttachment.getName());
    assertEquals(bytes.length, returnedAttachment.getSize());

    assertEquals((long) attachment.getId(), (long) returnedAttachment.getId());
    assertEquals((long) content.getId(), (long) returnedAttachment.getAttachmentContentId());

    // Make the same as the returned tasks, so we can test equals
    task.getTaskData().setAttachments(attachments1);
    task.getTaskData().setStatus(Status.Created);
    assertEquals(task, task1);

    content = client.getContent(returnedAttachment.getAttachmentContentId());
    assertEquals("Ths is my attachment text1", new String(content.getContent()));

    // test we can have multiple attachments

    attachment = new Attachment();
    attachedAt = new Date(System.currentTimeMillis());
    attachment.setAttachedAt(attachedAt);
    attachment.setAttachedBy(users.get("tony"));
    attachment.setName("file2.txt");
    attachment.setAccessType(AccessType.Inline);
    attachment.setContentType("txt");

    bytes = "Ths is my attachment text2".getBytes();
    content = new Content();
    content.setContent(bytes);

    client.addAttachment(taskId, attachment, content);

    task1 = client.getTask(taskId);
    // In local clients this will be the same object and we are reusing the tests
    // assertNotSame(task, task1);
    // assertFalse(task.equals(task1));

    List<Attachment> attachments2 = task1.getTaskData().getAttachments();
    assertEquals(2, attachments2.size());

    content = client.getContent(content.getId());
    assertEquals("Ths is my attachment text2", new String(content.getContent()));

    // make two collections the same and compare
    attachment.setSize(26);
    attachment.setAttachmentContentId(content.getId());
    attachments1.add(attachment);
    assertTrue(CollectionUtils.equals(attachments2, attachments1));

    client.deleteAttachment(taskId, attachment.getId(), content.getId());

    task1 = client.getTask(taskId);
    attachments2 = task1.getTaskData().getAttachments();
    assertEquals(1, attachments2.size());

    assertEquals("file1.txt", attachments2.get(0).getName());
  }
Exemplo n.º 30
0
 private TaskOrderInfo(Task t, long order) {
   this.created = t.getCreated();
   this.priority = t.getPriority();
   this.order = order;
   this.taskId = t.getId();
 }