@Test
 public void testFindTagsByTask() throws Exception {
   Map<String, Integer> tags = taskService.findTagsByTask(taskService.getTaskByID(1).get());
   for (Map.Entry<String, Integer> entry : tags.entrySet()) {
     assertNotEquals("", entry.getKey());
   }
 }
  @Deployment(
      resources = {
        "org/activiti/examples/bpmn/event/timer/BoundaryTimerEventTest.testInterruptingTimerDuration.bpmn"
      })
  @Test
  public void testInterruptingTimerDuration() {

    // Start process instance
    RuntimeService runtimeService = activitiRule.getRuntimeService();
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("escalationExample");

    // There should be one task, with a timer : first line support
    TaskService taskService = activitiRule.getTaskService();
    Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
    assertEquals("First line support", task.getName());

    // Manually execute the job
    ManagementService managementService = activitiRule.getManagementService();
    Job timer = managementService.createJobQuery().singleResult();
    managementService.executeJob(timer.getId());

    // The timer has fired, and the second task (secondlinesupport) now exists
    task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
    assertEquals("Second line support", task.getName());
  }
 @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());
   }
 }
 /**
  * Look up a task service by name.
  *
  * @param name Name of the task service to retrieve.
  * @return Task service found, or null if no service of that name found
  */
 public TaskService getTaskService(String name) {
   if (name == null) {
     throw new IllegalArgumentException("null name");
   }
   for (TaskService taskService : taskServices) {
     if (name.equals(taskService.getName())) {
       return taskService;
     }
   }
   return null;
 }
 @BeforeClass
 public static void setUpClass() throws Exception {
   ABEntityTest.initDB();
   StorageSingleton.init(new StorageServiceImpl());
   taskService = new TaskServiceImpl();
   project = new ProjectServiceImpl().getProjectByID(1).get();
   user = new UserServiceImpl().findUserByID(1).get();
   assigneeUser = new UserServiceImpl().findUserByID(2).get();
   type = taskService.getTaskTypeByID(1).get();
   priority = taskService.getTaskPriorityByID(1).get();
   status = taskService.getTaskStatusByID(1).get();
 }
Example #6
0
 @Test
 public void testSetAssignee() {
   ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();
   IdentityService identityService = engine.getIdentityService();
   User user = creatUser(identityService, "user1", "张三", "last", "*****@*****.**", "123");
   TaskService taskService = engine.getTaskService();
   Task task1 = taskService.newTask("task1");
   task1.setName("申请任务");
   taskService.saveTask(task1);
   taskService.setAssignee(task1.getId(), user.getId());
   System.out.println(
       "用户张三受理的任务数量:" + taskService.createTaskQuery().taskAssignee(user.getId()).count());
 }
Example #7
0
 /**
  * Instantiates a new razor server, its services, and starts the scheduler. This can be replaced
  * by a dynamic handler manager but has the benefit of simplicity.
  */
 public RazorServer() {
   super();
   SERVICES.put(Service.ACCOUNT, AccountService.getInstance());
   SERVICES.put(Service.ALERT, AlertService.getInstance());
   SERVICES.put(Service.ASSET, AssetService.getInstance());
   SERVICES.put(Service.ATTRIBUTE, AttributeService.getInstance());
   SERVICES.put(Service.AUDIT, AuditService.getInstance());
   SERVICES.put(Service.CONTRACT, ContractService.getInstance());
   SERVICES.put(Service.FINANCE, FinanceService.getInstance());
   SERVICES.put(Service.JOURNAL, JournalService.getInstance());
   SERVICES.put(Service.IMAGE, ImageService.getInstance());
   SERVICES.put(Service.IMAGETEXT, ImageTextService.getInstance());
   SERVICES.put(Service.LICENSE, LicenseService.getInstance());
   SERVICES.put(Service.LOCATION, LocationService.getInstance());
   SERVICES.put(Service.MAIL, MailService.getInstance());
   SERVICES.put(Service.MONITOR, MonitorService.getInstance());
   SERVICES.put(Service.PARTNER, PartnerService.getInstance());
   SERVICES.put(Service.PARTY, PartyService.getInstance());
   SERVICES.put(Service.PRICE, PriceService.getInstance());
   SERVICES.put(Service.PRODUCT, ProductService.getInstance());
   SERVICES.put(Service.RATE, RateService.getInstance());
   SERVICES.put(Service.REPORT, ReportService.getInstance());
   SERVICES.put(Service.RESERVATION, ReservationService.getInstance());
   SERVICES.put(Service.SESSION, SessionService.getInstance());
   SERVICES.put(Service.SMS, SmsService.getInstance());
   SERVICES.put(Service.TASK, TaskService.getInstance());
   SERVICES.put(Service.TAX, TaxService.getInstance());
   SERVICES.put(Service.TEXT, TextService.getInstance());
   SERVICES.put(Service.WORKFLOW, WorkflowService.getInstance());
   //		startScheduler();
   //		PartnerService.startSchedulers();
 }
  @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());
  }
  /**
   * 跳转到任务执行页面
   *
   * @param request
   * @return
   */
  @RequestMapping(value = "/form.do")
  public String from(
      HttpServletRequest request, @RequestParam("taskId") String taskId, Model model) {

    List<Task> taskList = taskService.createTaskQuery().taskId(taskId).list();
    Task task = taskList.get(0);
    // 获取表单数据
    TaskFormData tfd = formService.getTaskFormData(taskId);
    List<FormProperty> fpList = tfd.getFormProperties();

    Map map = runtimeService.getVariables(task.getExecutionId());

    List<ActivityImpl> activityList = new ArrayList<ActivityImpl>();

    try {
      // 查找所有可驳回的节点
      activityList = processExtensionService.findBackActivity(taskId);
      // model.addAttribute("activityList",activityList);
    } catch (Exception e) {
      e.printStackTrace();
    }

    //        model.addAttribute("task",task);
    //        model.addAttribute("fpList",fpList);
    //        model.addAttribute("map",map);
    //        model.addAttribute("taskId",taskId);

    request.setAttribute("task", task);
    request.setAttribute("fpList", fpList);
    request.setAttribute("map", map);
    request.setAttribute("taskId", taskId);
    request.setAttribute("activityList", activityList);

    return "/simple/form";
  }
 /**
  * 反签收
  *
  * @param taskId 任务id
  */
 @Override
 public void unclaim(String taskId) {
   boolean canUnclaim = false;
   // 反签收条件过滤
   List<IdentityLink> links = taskService.getIdentityLinksForTask(taskId);
   for (IdentityLink identityLink : links) {
     canUnclaim = StringUtils.equals(IdentityLinkType.CANDIDATE, identityLink.getType());
     if (canUnclaim) {
       taskService.claim(taskId, null);
       break;
     }
   }
   if (!canUnclaim) {
     throw new BusinessException(ReturnCodeConstant.UNCLAIM_TASK);
   }
 }
 @Test
 public void testGetAllTags() throws Exception {
   Map<String, Integer> tags = taskService.getAllTags();
   for (Map.Entry<String, Integer> entry : tags.entrySet()) {
     assertNotEquals("", entry.getKey());
     assertTrue(entry.getValue() > 0);
   }
 }
 @Test
 public void testGetAllStatuses() throws Exception {
   List<TaskStatus> statuses = taskService.getAllStatuses();
   for (TaskStatus taskStatus : statuses) {
     assertTrue(taskStatus.getId() > 0);
     assertNotNull(taskStatus.getName());
     assertNotEquals("", taskStatus.getName());
   }
 }
 @Test
 public void testGetTaskPriorityByID() throws Exception {
   Optional<TaskPriority> optPriority = taskService.getTaskPriorityByID(1);
   assertTrue(optPriority.isPresent());
   TaskPriority prior = optPriority.get();
   assertNotNull(prior);
   assertEquals(1, prior.getId());
   assertNotNull(prior.getName());
 }
 @Test
 public void testGetTaskStatusByName() throws Exception {
   Optional<TaskStatus> optStatus = taskService.getTaskStatusByName("New");
   assertTrue(optStatus.isPresent());
   TaskStatus stat = optStatus.get();
   assertNotNull(stat);
   assertEquals("New", stat.getName());
   assertTrue(stat.getId() > 0);
 }
  /**
   * 签收任务
   *
   * @return
   */
  @RequestMapping(value = "/claim/{id}")
  public String claimTask(
      @PathVariable("id") String taskId, @RequestParam("userId") String userId) {

    // 签收任务
    taskService.claim(taskId, userId);

    return "redirect:/simple/index.do";
  }
 @Test
 public void testGetTaskTypeByName() throws Exception {
   Optional<TaskType> optType = taskService.getTaskTypeByName("Bug");
   assertTrue(optType.isPresent());
   TaskType typ = optType.get();
   assertNotNull(typ);
   assertEquals("Bug", typ.getName());
   assertTrue(typ.getId() > 0);
   assertEquals(type.getName(), typ.getName());
 }
  /**
   * 提交流程
   *
   * @return
   */
  @RequestMapping(value = "/submit.do")
  public String submit(
      HttpServletRequest request,
      HttpServletResponse response,
      @RequestParam(value = "taskId", required = false) String taskId,
      @RequestParam(value = "day", required = false) String day,
      @RequestParam(value = "type", required = false) String type,
      @RequestParam(value = "reason", required = false) String reason,
      @RequestParam(value = "result", required = false) String result,
      @RequestParam(value = "toSign", required = false) String toSign,
      @RequestParam(value = "backActivityId", required = false) String backActivityId)
      throws Exception {
    List<Task> taskList = taskService.createTaskQuery().taskId(taskId).list();
    Task task = taskList.get(0);
    String taskName = task.getName();

    // result = new String(result.getBytes("ISO-8859-1"), "UTF-8");

    if (result.equals("同意")) {
      Map map = new HashMap();
      if (StringUtils.isNotBlank(day)) {
        map.put("day", day);
        map.put("reason", reason);
        map.put("type", 0);
        taskService.complete(taskId, map);
      } else {
        taskService.complete(taskId);
      }
    } else if (result.equals("驳回")) {
      ProcessInstance processInstance = processExtensionService.findProcessInstanceByTaskId(taskId);

      Map<String, Object> map = runtimeService.getVariables(processInstance.getId());

      processExtensionService.backProcess(taskId, backActivityId, map);
    } else if (result.equals("转签")) {

      if (processExtensionService.isPermissionInActivity(taskId, toSign)) {
        taskService.setAssignee(taskId, toSign);
      }
    }
    return "redirect:/simple/index.do";
  }
 @Test
 public void testGetTaskFulltext() throws Exception {
   String search = "Third Task";
   List<Task> tasks = taskService.getTaskFulltext("\"" + search + "\"");
   for (Task task : tasks) {
     assertTrue(
         task.getName().contains(search)
             || task.getDescription().contains(search)
             || task.getTestSteps().contains(search));
   }
 }
  /**
   * 个人任务首页
   *
   * @return
   */
  @RequestMapping("/index.do")
  public String index(HttpServletRequest request, HttpServletResponse response, Model model) {

    User user =
        request.getSession(true).getAttribute("user") == null
            ? null
            : (User) request.getSession(true).getAttribute("user");

    List<Group> groups =
        request.getSession(true).getAttribute("groups") == null
            ? null
            : (List<Group>) request.getSession(true).getAttribute("groups");

    if (null == user) {
      return "redirect:/simple/login.do";
    } else {
      model.addAttribute("user", user);
      model.addAttribute("groups", groups);
      /** */
      List<ProcessDefinition> pdList = repositoryService.createProcessDefinitionQuery().list();

      model.addAttribute("pdList", pdList);
      /** 该用户所有可以认领的任务 */
      List<Task> groupTasks = taskService.createTaskQuery().taskCandidateUser(user.getId()).list();

      List<Task> userTasks = taskService.createTaskQuery().taskAssignee(user.getId()).list();
      model.addAttribute("userTasks", userTasks);
      model.addAttribute("groupTasks", groupTasks);
      /** 查看任务实例 */
      List<Task> taskList = taskService.createTaskQuery().list();
      model.addAttribute("taskList", taskList);
      /** 历史流程 */
      List<HistoricProcessInstance> hpiList =
          historyService.createHistoricProcessInstanceQuery().finished().list();
      model.addAttribute("hpiList", hpiList);
    }

    return "/simple/index";
  }
 /**
  * @param taskQueryForm
  * @param userId
  * @return
  */
 @Override
 public List<TaskVo> queryToDoTaskFiltered(TaskQueryForm taskQueryForm, String userId) {
   DataTablesInfo dataTablesInfo = taskQueryForm.getDataTablesInfo();
   int start = dataTablesInfo.getStart();
   int length = dataTablesInfo.getLength();
   TaskQuery taskQuery =
       taskService
           .createTaskQuery()
           .taskCandidateOrAssigned(userId)
           .orderByTaskCreateTime()
           .desc();
   List<Task> tasks = taskQuery.listPage(start, start + length);
   List<TaskVo> taskRtn = buildTaskVos(tasks);
   return taskRtn;
 }
Example #21
0
 private void checkForMissingColumns() {
   // For some reason these properties are missing for some users.
   // Make them exist!
   try {
     TodorooCursor<Task> tasks = taskService.query(Query.select(Task.UUID, Task.USER_ID).limit(1));
     try {
       System.err.println(tasks.getCount());
     } finally {
       tasks.close();
     }
   } catch (SQLiteException e) {
     database.tryAddColumn(Task.TABLE, Task.UUID, "'0'"); // $NON-NLS-1$
     database.tryAddColumn(Task.TABLE, Task.USER_ID, "0"); // $NON-NLS-1$
   }
 }
 @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());
   }
 }
 @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());
 }
Example #24
0
  public void delete(Task item) {
    if (!item.isSaved()) {
      return;
    }

    if (item.containsValue(Task.TITLE) && item.getTitle().length() == 0) {
      taskDao.delete(item.getId());
      item.setId(Task.NO_ID);
    } else {
      long id = item.getId();
      item.clear();
      item.setId(id);
      gcalHelper.deleteTaskEvent(item);
      item.setDeletionDate(DateUtilities.now());
      taskService.save(item);
    }
  }
Example #25
0
 @Test
 public void test() {
   ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();
   RepositoryService repositoryService = engine.getRepositoryService();
   RuntimeService runtimeService = engine.getRuntimeService();
   TaskService taskService = engine.getTaskService();
   repositoryService.createDeployment().addClasspathResource("bpmn/first.bpmn").deploy();
   runtimeService.startProcessInstanceByKey("process1");
   Task task = taskService.createTaskQuery().singleResult();
   System.out.println("第一个任务完成前,当前任务名称:" + task.getName());
   taskService.complete(task.getId());
   task = taskService.createTaskQuery().singleResult();
   System.out.println("第二个任务完成前,当前任务名称:" + task.getName());
   taskService.complete(task.getId());
   task = taskService.createTaskQuery().singleResult();
   System.out.println("流程结束后,查找任务:" + task);
 }
Example #26
0
  @Test
  public void generateWorkList() throws Exception {
    DateTime dateTimeMonth = DateTime.now().withDayOfMonth(1).withTimeAtStartOfDay();

    Member member = EntityFactory.createMember();
    member.setId(randomLong);

    List<AbsenceDay> absenceDayList = EntityFactory.createList(EntityFactory::createAbsenceDay);
    List<Task> taskList = EntityFactory.createList(EntityFactory::createTask);

    when(mockMemberService.findActiveMembers()).thenReturn(Collections.singletonList(member));
    when(mockAbsenceDayService.findByMemberAndMonth(randomLong, dateTimeMonth.getMonthOfYear()))
        .thenReturn(absenceDayList);
    when(mockTaskService.findTasksForMember(member)).thenReturn(taskList);

    scheduleService.generateWorkList();

    verify(mockMemberService).findActiveMembers();
    verify(mockAbsenceDayService)
        .findByMemberAndMonth(eq(randomLong), eq(dateTimeMonth.getMonthOfYear()));
    verify(mockWorkService)
        .findOrCreateWorks(eq(member), eq(dateTimeMonth), eq(taskList), eq(absenceDayList));
  }
Example #27
0
  /** Fixes task filter missing tasks bug, migrate PDV/RTM notes */
  @SuppressWarnings("nls")
  private void upgrade3To3_7() {
    TodorooCursor<Task> t =
        taskService.query(Query.select(Task.ID, Task.DUE_DATE).where(Task.DUE_DATE.gt(0)));
    Task task = new Task();
    for (t.moveToFirst(); !t.isAfterLast(); t.moveToNext()) {
      task.readFromCursor(t);
      if (task.hasDueDate()) {
        task.setValue(Task.DUE_DATE, task.getValue(Task.DUE_DATE) / 1000L * 1000L);
        taskService.save(task);
      }
    }
    t.close();

    TodorooCursor<Metadata> m =
        metadataService.query(
            Query.select(Metadata.PROPERTIES)
                .where(
                    Criterion.or(
                        Metadata.KEY.eq("producteev-note"), Metadata.KEY.eq("rmilk-note"))));

    StringProperty PDV_NOTE_ID = Metadata.VALUE1;
    StringProperty PDV_NOTE_MESSAGE = Metadata.VALUE2;
    LongProperty PDV_NOTE_CREATED = new LongProperty(Metadata.TABLE, Metadata.VALUE3.name);

    StringProperty RTM_NOTE_ID = Metadata.VALUE1;
    StringProperty RTM_NOTE_TITLE = Metadata.VALUE2;
    StringProperty RTM_NOTE_TEXT = Metadata.VALUE3;
    LongProperty RTM_NOTE_CREATED = new LongProperty(Metadata.TABLE, Metadata.VALUE4.name);

    Metadata metadata = new Metadata();
    for (m.moveToFirst(); !m.isAfterLast(); m.moveToNext()) {
      metadata.readFromCursor(m);

      String id, body, title, provider;
      long created;
      if ("rmilk-note".equals(metadata.getValue(Metadata.KEY))) {
        id = metadata.getValue(RTM_NOTE_ID);
        body = metadata.getValue(RTM_NOTE_TEXT);
        title = metadata.getValue(RTM_NOTE_TITLE);
        created = metadata.getValue(RTM_NOTE_CREATED);
        provider = MilkNoteHelper.PROVIDER;
      } else {
        id = metadata.getValue(PDV_NOTE_ID);
        body = metadata.getValue(PDV_NOTE_MESSAGE);
        created = metadata.getValue(PDV_NOTE_CREATED);
        title =
            DateUtilities.getDateStringWithWeekday(ContextManager.getContext(), new Date(created));
        provider = ProducteevDataService.NOTE_PROVIDER;
      }

      metadata.setValue(Metadata.KEY, NoteMetadata.METADATA_KEY);
      metadata.setValue(Metadata.CREATION_DATE, created);
      metadata.setValue(NoteMetadata.BODY, body);
      metadata.setValue(NoteMetadata.TITLE, title);
      metadata.setValue(NoteMetadata.THUMBNAIL, null);
      metadata.setValue(NoteMetadata.EXT_PROVIDER, provider);
      metadata.setValue(NoteMetadata.EXT_ID, id);

      metadata.clearValue(Metadata.ID);
      metadataService.save(metadata);
    }
    m.close();
  }
Example #28
0
  /**
   * Return a change log string. Releases occur often enough that we don't expect change sets to be
   * localized.
   *
   * @param from
   * @param to
   * @return
   */
  @SuppressWarnings("nls")
  public void showChangeLog(Context context, int from) {
    if (!(context instanceof Activity) || from == 0) return;

    Preferences.clear(TagCaseMigrator.PREF_SHOW_MIGRATION_ALERT);

    Preferences.clear(AstridPreferences.P_UPGRADE_FROM);
    StringBuilder changeLog = new StringBuilder();

    if (from >= V4_2_0 && from < V4_2_1) {
      newVersionString(
          changeLog,
          "4.2.1 (6/08/12)",
          new String[] {
            "Fix for MyTouch 4G Lists",
            "Fixed a crash when adding tasks with due times to Google Calendar",
            "Better syncing of the people list",
            "Minor UI polish and bugfixes"
          });
    }

    if (from < V4_2_0) {
      newVersionString(
          changeLog,
          "4.2.0 (6/05/12)",
          new String[] {
            "Support for the Nook", "Fixed crash on large image attachments", "Minor bugfixes"
          });
    }

    if (from >= V4_1_3 && from < V4_1_3_1) {
      newVersionString(changeLog, "4.1.3.1 (5/18/12)", new String[] {"Fixed reminders for ICS"});
    }

    if (from >= V4_1_2 && from < V4_1_3) {
      newVersionString(
          changeLog,
          "4.1.3 (5/17/12)",
          new String[] {
            "Added ability to see shared tasks sorted by friend! Enable or disable "
                + "in Settings > Astrid Labs",
            "Fixed desktop shortcuts",
            "Fixed adding tasks from the Power Pack widget",
            "Fixed selecting photos on the Kindle Fire",
            "Various other minor bug and crash fixes"
          });
    }

    if (from >= V4_1_1 && from < V4_1_2) {
      newVersionString(
          changeLog, "4.1.2 (5/05/12)", new String[] {"Fixed some crashes and minor bugs"});
    }

    if (from < V4_1_1) {
      newVersionString(
          changeLog,
          "4.1.1 (5/04/12)",
          new String[] {
            "Respond to or set reminders for missed calls. This feature requires a new permission to read "
                + "the phone state.",
          });
    }

    if (from < V4_1_0) {
      newVersionString(
          changeLog,
          "4.1.0 (5/03/12)",
          new String[] {
            "Swipe between lists! Swipe left and right to move through your lists. Enable or adjust "
                + "in Settings > Astrid Labs",
            "Assign tasks to contacts without typing",
            "Links to tasks in comments",
            "Astrid.com sync improvements",
            "Other minor bugfixes",
          });
    }

    if (from >= V4_0_6 && from < V4_0_6_2) {
      newVersionString(
          changeLog,
          "4.0.6.2 (4/03/12)",
          new String[] {
            "Minor fix to backup migration fix to handle deleted tasks as well as completed tasks."
          });
    }

    if (from >= V4_0_6 && from < V4_0_6_1) {
      newVersionString(
          changeLog,
          "4.0.6.1 (4/03/12)",
          new String[] {
            "Fixed a bug where old tasks could become uncompleted. Sorry to those of you"
                + " who were affected by this! To recover, you can import your old tasks"
                + " from any backup file created before April 3 by clicking Menu -> Settings ->"
                + " Backups -> Manage Backups -> Import Tasks. Backup files from April 3 will start"
                + " with 'auto.120403'."
          });
    }

    if (from < V4_0_6) {
      newVersionString(
          changeLog,
          "4.0.6 (4/02/12)",
          new String[] {
            "Fixes and performance improvements to Astrid.com and Google Tasks sync",
            "Google TV support! (Beta)",
            "Fixed a bug that could put duetimes on tasks when changing timezones",
            "Fixed a rare crash when starting a task timer"
          });
    }

    if (from >= V4_0_0 && from < V4_0_5) {
      newVersionString(
          changeLog,
          "4.0.5 (3/22/12)",
          new String[] {
            "Better conflict resolution for Astrid.com sync",
            "Fixes and improvements to Gtasks sync",
            "Added option to report sync errors in sync preference screen"
          });
    }

    if (from >= V4_0_0 && from < V4_0_4) {
      newVersionString(
          changeLog,
          "4.0.4 (3/7/12)",
          new String[] {
            "Fixed crashes related to error reporting",
            "Fixed a crash when creating a task from the widget",
            "Fixed a bug where a manual sync wouldn't always start"
          });
    }

    if (from >= V4_0_0 && from < V4_0_3) {
      newVersionString(
          changeLog,
          "4.0.3 (3/6/12)",
          new String[] {
            "Fix some issues with Google Tasks sync. We're sorry to "
                + "everyone who's been having trouble with it!",
            "Updated translations for Portuguese, Chinese, German, Russian, and Dutch",
            "Centralize Android's menu key with in-app navigation",
            "Fixed crashes & improve crash logging",
          });
    }

    if (from >= V4_0_0 && from < V4_0_2) {
      newVersionString(
          changeLog,
          "4.0.2 (2/29/12)",
          new String[] {
            "Removed GPS permission - no longer needed",
            "Fixes for some subtasks issues",
            "No longer need to run the Crittercism service in the background",
            "Fixed a crash that could occur when cloning tasks",
            "Fixed a bug that prevented certain comments from syncing correctly",
            "Fixed issues where voice add wouldn't work correctly",
          });
    }

    if (from >= V4_0_0 && from < V4_0_1) {
      newVersionString(
          changeLog,
          "4.0.1 (2/23/12)",
          new String[] {
            "Fixed a database issue affecting Android 2.1 users",
            "Fixed a crash when using drag and drop in Google Tasks lists",
            "Other small bugfixes"
          });
    }

    if (from < V4_0_0) {
      newVersionString(
          changeLog,
          "4.0.0 (2/23/12)",
          new String[] {
            "Welcome to Astrid 4.0! Here's what's new:",
            "<b>Subtasks!!!</b><br>Press the Menu key and select 'Sort' to access",
            "<b>New Look!</b><br>Customize how Astrid looks from the Settings menu",
            "<b>Task Rabbit!</b><br>Outsource your tasks with the help of trustworthy people",
            "<b>More Reliable Sync</b><br>Including fixes to Astrid.com and Google Tasks sync",
            "<b>Tablet version</b><br>Enjoy Astrid on your luxurious Android tablet",
            "Many bug and usability fixes"
          });
    }

    // --- old messages

    if (from >= V3_0_0 && from < V3_9_0) {
      newVersionString(
          changeLog,
          "3.9 (12/09/11)",
          new String[] {
            "Cleaner design (especially the task edit page)!",
            "Customize the edit page (\"Beast Mode\" in preferences)",
            "Make shared lists with tasks open to anyone (perfect for potlucks, road trips etc)",
            "Fixes for some ICS crashes (full support coming soon)",
            "Google Tasks sync improvement - Note: If you have been experiencing \"Sync with errors\", try logging out and logging back in to Google Tasks.",
            "Other minor bug fixes",
            "Feedback welcomed!"
          });
    }

    if (from >= V3_0_0 && from < V3_8_0) {
      newVersionString(
          changeLog,
          "3.8.0 (7/15/11)",
          new String[] {
            "Astrid.com: sync & share tasks / lists with others!",
            "GTasks Sync using Google's official task API! Gtasks users "
                + "will need to perform a manual sync to set everything up.",
            "Renamed \"Tags\" to \"Lists\" (see blog.astrid.com for details)",
            "New style for \"Task Edit\" page!",
            "Purge completed or deleted tasks from settings menu!",
          });
      gtasksPreferenceService.setToken(null);
    }

    if (from >= V3_0_0 && from < V3_7_0) {
      newVersionString(
          changeLog,
          "3.7.0 (2/7/11)",
          new String[] {
            "Improved UI for displaying task actions. Tap a task to "
                + "bring up actions, tap again to dismiss.",
            "Task notes can be viewed by tapping the note icon to " + "the right of the task.",
            "Added Astrid as 'Send-To' choice in Android Browser and " + "other apps.",
            "Add tags and importance in quick-add, e.g. " + "\"call mom #family @phone !4\"",
            "Fixed bug with custom filters & tasks being hidden.",
          });
      upgrade3To3_7();
      if (gtasksPreferenceService.isLoggedIn()) taskService.clearDetails(Criterion.all);
      Preferences.setBoolean(Eula.PREFERENCE_EULA_ACCEPTED, true);
    }
    if (from >= V3_0_0 && from < V3_6_0) {
      newVersionString(
          changeLog,
          "3.6.0 (11/13/10)",
          new String[] {
            "Astrid Power Pack is now launched to the Android Market. "
                + "New Power Pack features include 4x2 and 4x4 widgets and voice "
                + "task reminders and creation. Go to the add-ons page to find out more!",
            "Fix for Google Tasks: due times got lost on sync, repeating tasks not repeated",
            "Fix for task alarms not always firing if multiple set",
            "Fix for various force closes",
          });
      upgrade3To3_6(context);
    }
    if (from >= V3_0_0 && from < V3_5_0)
      newVersionString(
          changeLog,
          "3.5.0 (10/25/10)",
          new String[] {
            "Google Tasks Sync (beta!)",
            "Bug fix with RMilk & new tasks not getting synced",
            "Fixed Force Closes and other bugs",
          });
    if (from >= V3_0_0 && from < V3_4_0) {
      newVersionString(
          changeLog,
          "3.4.0 (10/08/10)",
          new String[] {
            "End User License Agreement",
            "Option to disable usage statistics",
            "Bug fixes with Producteev",
          });
    }
    if (from >= V3_0_0 && from < V3_3_0)
      newVersionString(
          changeLog,
          "3.3.0 (9/17/10)",
          new String[] {
            "Fixed some RTM duplicated tasks issues",
            "UI updates based on your feedback",
            "Snooze now overrides other alarms",
            "Added preference option for selecting snooze style",
            "Hide until: now allows you to pick a specific time",
          });
    if (from >= V3_0_0 && from < V3_2_0)
      newVersionString(
          changeLog,
          "3.2.0 (8/16/10)",
          new String[] {
            "Build your own custom filters from the Filter page",
            "Easy task sorting (in the task list menu)",
            "Create widgets from any of your filters",
            "Synchronize with Producteev! (producteev.com)",
            "Select tags by drop-down box",
            "Cosmetic improvements, calendar & sync bug fixes",
          });
    if (from >= V3_0_0 && from < V3_1_0)
      newVersionString(
          changeLog,
          "3.1.0 (8/9/10)",
          new String[] {
            "Linkify phone numbers, e-mails, and web pages",
            "Swipe L => R to go from tasks to filters",
            "Moved task priority bar to left side",
            "Added ability to create fixed alerts for a task",
            "Restored tag hiding when tag begins with underscore (_)",
            "FROYO: disabled moving app to SD card, it would break alarms and widget",
            "Also gone: a couple force closes, bugs with repeating tasks",
          });

    if (changeLog.length() == 0) return;

    changeLog.append("Have a spectacular day!</body></html>");
    String color = ThemeService.getDialogTextColor();
    String changeLogHtml = "<html><body style='color: " + color + "'>" + changeLog;

    DialogUtilities.htmlDialog(context, changeLogHtml, R.string.UpS_changelog_title);
  }
  @RequestMapping(value = "/studentactivity", method = RequestMethod.GET)
  @PreAuthorize(Permission.SECURITY_PERSON_READ)
  public @ResponseBody List<RecentActivityTO> loadRecentStudentActivity(final @PathVariable UUID id)
      throws ObjectNotFoundException {
    List<RecentActivityTO> recentActivities = new ArrayList<RecentActivityTO>();
    Person person = personService.get(id);
    SortingAndPaging sAndP =
        SortingAndPaging.createForSingleSortWithPaging(
            ObjectStatus.ACTIVE, 0, 1000, "createdDate", "DESC", "createdDate");

    PagingWrapper<EarlyAlert> earlyAlerts = earlyAlertService.getAllForPerson(person, sAndP);
    SspUser currentUser = securityService.currentUser();
    List<EarlyAlertTO> earlyAlertTOs = earlyAlertTOFactory.asTOList(earlyAlerts.getRows());

    PagingWrapper<JournalEntry> journalEntries =
        journalEntryService.getAllForPerson(person, currentUser, sAndP);

    List<JournalEntryTO> journalEntriesTOs =
        journalEntryTOFactory.asTOList(journalEntries.getRows());

    PagingWrapper<Task> actions = taskService.getAllForPerson(person, currentUser, sAndP);

    List<TaskTO> actionsTOs = taskTOFactory.asTOList(actions.getRows());

    PagingWrapper<Plan> plans =
        planService.getAllForStudent(
            SortingAndPaging.createForSingleSortWithPaging(
                ObjectStatus.ALL, 0, 1000, null, null, null),
            id);

    List<PlanTO> planTOs = planTOFactory.asTOList(plans.getRows());

    for (EarlyAlertTO earlyAlert : earlyAlertTOs) {
      if (earlyAlert.getClosedDate() != null) {
        recentActivities.add(
            new RecentActivityTO(
                earlyAlert.getClosedById(),
                earlyAlert.getClosedByName(),
                "Early Alert Closed",
                earlyAlert.getClosedDate()));
      } else {
        recentActivities.add(
            new RecentActivityTO(
                earlyAlert.getCreatedBy().getId(),
                getPersonLiteName(earlyAlert.getCreatedBy()),
                "Early Alert Created",
                earlyAlert.getCreatedDate()));
      }
    }

    for (JournalEntryTO journalEntry : journalEntriesTOs) {
      recentActivities.add(
          new RecentActivityTO(
              journalEntry.getCreatedBy().getId(),
              getPersonLiteName(journalEntry.getCreatedBy()),
              "Journal Entry",
              journalEntry.getEntryDate()));
    }

    for (TaskTO action : actionsTOs) {
      if (action.isCompleted()) {
        recentActivities.add(
            new RecentActivityTO(
                action.getModifiedBy().getId(),
                getPersonLiteName(action.getModifiedBy()),
                "Action Plan Task Created",
                action.getCompletedDate()));
      } else {
        recentActivities.add(
            new RecentActivityTO(
                action.getCreatedBy().getId(),
                getPersonLiteName(action.getCreatedBy()),
                "Action Plan Task Created",
                action.getCreatedDate()));
      }
    }

    for (PlanTO planTO : planTOs) {
      Date testDate = DateUtils.addDays(planTO.getCreatedDate(), 1);
      String planName = planTO.getName();
      if (planTO.getModifiedDate().before(testDate)) {
        recentActivities.add(
            new RecentActivityTO(
                planTO.getCreatedBy().getId(),
                getPersonLiteName(planTO.getCreatedBy()),
                "Map Plan (" + planName + ") Created",
                planTO.getModifiedDate()));
      } else {
        recentActivities.add(
            new RecentActivityTO(
                planTO.getModifiedBy().getId(),
                getPersonLiteName(planTO.getModifiedBy()),
                "Map Plan (" + planName + ") Updated",
                planTO.getModifiedDate()));
      }
    }

    if (person.getStudentIntakeCompleteDate() != null) {
      recentActivities.add(
          new RecentActivityTO(
              person.getCoach().getId(),
              person.getCoach().getFullName(),
              "Student Intake Completed",
              person.getStudentIntakeCompleteDate()));
    }
    if (person.getStudentIntakeRequestDate() != null) {
      recentActivities.add(
          new RecentActivityTO(
              person.getCoach().getId(),
              person.getCoach().getFullName(),
              "Student Intake Requested",
              person.getStudentIntakeRequestDate()));
    }

    Collections.sort(recentActivities, RecentActivityTO.RECENT_ACTIVITY_TO_DATE_COMPARATOR);
    return recentActivities;
  }
  @Override
  protected void onHandleRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      String type = request.getParameter("type");
      String typeId = request.getParameter("typeId");
      Integer sAccountId = Integer.parseInt(request.getParameter("sAccountId"));
      String siteURL = request.getParameter("siteURL");
      String timeZoneId = request.getParameter("timeZone");
      TimeZone timeZone = TimezoneMapper.getTimezone(timeZoneId);
      String username = request.getParameter("username");
      String localeParam = request.getParameter("locale");
      Locale locale = LocaleHelper.toLocale(localeParam);

      String html = "";
      if (ProjectTypeConstants.PROJECT.equals(type)) {
        ProjectService service = ApplicationContextUtil.getSpringBean(ProjectService.class);
        SimpleProject project = service.findById(Integer.parseInt(typeId), sAccountId);
        html = ProjectTooltipGenerator.generateToolTipProject(locale, project, siteURL, timeZone);
      } else if (ProjectTypeConstants.MESSAGE.equals(type)) {
        MessageService service = ApplicationContextUtil.getSpringBean(MessageService.class);
        SimpleMessage message = service.findById(Integer.parseInt(typeId), sAccountId);
        html = ProjectTooltipGenerator.generateToolTipMessage(locale, message, siteURL, timeZone);
      } else if (ProjectTypeConstants.MILESTONE.equals(type)) {
        MilestoneService service = ApplicationContextUtil.getSpringBean(MilestoneService.class);
        SimpleMilestone mileStone = service.findById(Integer.parseInt(typeId), sAccountId);
        html =
            ProjectTooltipGenerator.generateToolTipMilestone(locale, mileStone, siteURL, timeZone);
      } else if (ProjectTypeConstants.BUG.equals(type)) {
        BugService service = ApplicationContextUtil.getSpringBean(BugService.class);
        SimpleBug bug = service.findById(Integer.parseInt(typeId), sAccountId);
        html = ProjectTooltipGenerator.generateToolTipBug(locale, bug, siteURL, timeZone);
      } else if (ProjectTypeConstants.TASK.equals(type)) {
        ProjectTaskService service = ApplicationContextUtil.getSpringBean(ProjectTaskService.class);
        SimpleTask task = service.findById(Integer.parseInt(typeId), sAccountId);
        html = ProjectTooltipGenerator.generateToolTipTask(locale, task, siteURL, timeZone);
      } else if (ProjectTypeConstants.RISK.equals(type)) {
        RiskService service = ApplicationContextUtil.getSpringBean(RiskService.class);
        SimpleRisk risk = service.findById(Integer.parseInt(typeId), sAccountId);
        html = ProjectTooltipGenerator.generateToolTipRisk(locale, risk, siteURL, timeZone);
      } else if (ProjectTypeConstants.PROBLEM.equals(type)) {
        ProblemService service = ApplicationContextUtil.getSpringBean(ProblemService.class);
        SimpleProblem problem = service.findById(Integer.parseInt(typeId), sAccountId);
        html = ProjectTooltipGenerator.generateToolTipProblem(locale, problem, siteURL, timeZone);
      } else if (ProjectTypeConstants.BUG_VERSION.equals(type)) {
        VersionService service = ApplicationContextUtil.getSpringBean(VersionService.class);
        SimpleVersion version = service.findById(Integer.parseInt(typeId), sAccountId);
        html = ProjectTooltipGenerator.generateToolTipVersion(locale, version, siteURL, timeZone);
      } else if (ProjectTypeConstants.BUG_COMPONENT.equals(type)) {
        ComponentService service = ApplicationContextUtil.getSpringBean(ComponentService.class);
        SimpleComponent component = service.findById(Integer.parseInt(typeId), sAccountId);
        html =
            ProjectTooltipGenerator.generateToolTipComponent(locale, component, siteURL, timeZone);
      } else if (ProjectTypeConstants.PAGE.equals(type)) {
        ProjectPageService pageService =
            ApplicationContextUtil.getSpringBean(ProjectPageService.class);
        Page page = pageService.getPage(typeId, username);
        html = ProjectTooltipGenerator.generateToolTipPage(locale, page, siteURL, timeZone);
      } else if (ProjectTypeConstants.STANDUP.equals(type)) {
        StandupReportService service =
            ApplicationContextUtil.getSpringBean(StandupReportService.class);
        SimpleStandupReport standup = service.findById(Integer.parseInt(typeId), sAccountId);
        html = ProjectTooltipGenerator.generateToolTipStandUp(locale, standup, siteURL, timeZone);
      } else if (CrmTypeConstants.ACCOUNT.equals(type)) {
        AccountService service = ApplicationContextUtil.getSpringBean(AccountService.class);
        SimpleAccount account = service.findById(Integer.parseInt(typeId), sAccountId);
        html = CrmTooltipGenerator.generateToolTipAccount(locale, account, siteURL);
      } else if (CrmTypeConstants.CONTACT.equals(type)) {
        ContactService service = ApplicationContextUtil.getSpringBean(ContactService.class);
        SimpleContact contact = service.findById(Integer.parseInt(typeId), sAccountId);
        html = CrmTooltipGenerator.generateToolTipContact(locale, contact, siteURL, timeZone);
      } else if (CrmTypeConstants.CAMPAIGN.equals(type)) {
        CampaignService service = ApplicationContextUtil.getSpringBean(CampaignService.class);
        SimpleCampaign account = service.findById(Integer.parseInt(typeId), sAccountId);
        html = CrmTooltipGenerator.generateTooltipCampaign(locale, account, siteURL, timeZone);
      } else if (CrmTypeConstants.LEAD.equals(type)) {
        LeadService service = ApplicationContextUtil.getSpringBean(LeadService.class);
        SimpleLead lead = service.findById(Integer.parseInt(typeId), sAccountId);
        html = CrmTooltipGenerator.generateTooltipLead(locale, lead, siteURL, timeZone);
      } else if (CrmTypeConstants.OPPORTUNITY.equals(type)) {
        OpportunityService service = ApplicationContextUtil.getSpringBean(OpportunityService.class);
        SimpleOpportunity opportunity = service.findById(Integer.parseInt(typeId), sAccountId);
        html =
            CrmTooltipGenerator.generateTooltipOpportunity(locale, opportunity, siteURL, timeZone);
      } else if (CrmTypeConstants.CASE.equals(type)) {
        CaseService service = ApplicationContextUtil.getSpringBean(CaseService.class);
        SimpleCase cases = service.findById(Integer.parseInt(typeId), sAccountId);
        html = CrmTooltipGenerator.generateTooltipCases(locale, cases, siteURL, timeZone);
      } else if (CrmTypeConstants.MEETING.equals(type)) {
        MeetingService service = ApplicationContextUtil.getSpringBean(MeetingService.class);
        SimpleMeeting meeting = service.findById(Integer.parseInt(typeId), sAccountId);
        html = CrmTooltipGenerator.generateToolTipMeeting(locale, meeting, siteURL, timeZone);
      } else if (CrmTypeConstants.CALL.equals(type)) {
        CallService service = ApplicationContextUtil.getSpringBean(CallService.class);
        SimpleCall call = service.findById(Integer.parseInt(typeId), sAccountId);
        html = CrmTooltipGenerator.generateToolTipCall(locale, call, siteURL, timeZone);
      } else if (CrmTypeConstants.TASK.equals(type)) {
        TaskService service = ApplicationContextUtil.getSpringBean(TaskService.class);
        com.esofthead.mycollab.module.crm.domain.SimpleTask crmTask =
            service.findById(Integer.parseInt(typeId), sAccountId);
        html = CrmTooltipGenerator.generateToolTipCrmTask(locale, crmTask, siteURL, timeZone);
      } else if ("User".equals(type)) {
        UserService service = ApplicationContextUtil.getSpringBean(UserService.class);
        SimpleUser user = service.findUserByUserNameInAccount(username, sAccountId);
        html = CommonTooltipGenerator.generateTooltipUser(locale, user, siteURL, timeZone);
      } else {
        LOG.error("Can not generate tooltip for item has type " + type);
      }

      response.setCharacterEncoding("UTF-8");
      response.setContentType("text/html;charset=UTF-8");
      PrintWriter out = response.getWriter();
      out.println(html);
      return;
    } catch (Exception e) {
      LOG.error("Error while get html tooltip attachForm TooltipGeneratorServletRequestHandler", e);
      String html = null;
      PrintWriter out = response.getWriter();
      out.println(html);
      return;
    }
  }