Process the timephased resource assignment data to work out the
split structure of the task.

@param task parent task
@param timephasedComplete completed resource assignment work
@param timephasedPlanned planned resource assignment work
12968
public void processSplitData(Task task, List<TimephasedWork> timephasedComplete, List<TimephasedWork> timephasedPlanned)
   {
      Date splitsComplete = null;
      TimephasedWork lastComplete = null;
      TimephasedWork firstPlanned = null;
      if (!timephasedComplete.isEmpty())
      {
         lastComplete = timephasedComplete.get(timephasedComplete.size() - 1);
         splitsComplete = lastComplete.getFinish();
      }

      if (!timephasedPlanned.isEmpty())
      {
         firstPlanned = timephasedPlanned.get(0);
      }

      LinkedList<DateRange> splits = new LinkedList<DateRange>();
      TimephasedWork lastAssignment = null;
      DateRange lastRange = null;
      for (TimephasedWork assignment : timephasedComplete)
      {
         if (lastAssignment != null && lastRange != null && lastAssignment.getTotalAmount().getDuration() != 0 && assignment.getTotalAmount().getDuration() != 0)
         {
            splits.removeLast();
            lastRange = new DateRange(lastRange.getStart(), assignment.getFinish());
         }
         else
         {
            lastRange = new DateRange(assignment.getStart(), assignment.getFinish());
         }
         splits.add(lastRange);
         lastAssignment = assignment;
      }

      //
      // We may not have a split, we may just have a partially
      // complete split.
      //
      Date splitStart = null;
      if (lastComplete != null && firstPlanned != null && lastComplete.getTotalAmount().getDuration() != 0 && firstPlanned.getTotalAmount().getDuration() != 0)
      {
         lastRange = splits.removeLast();
         splitStart = lastRange.getStart();
      }

      lastAssignment = null;
      lastRange = null;
      for (TimephasedWork assignment : timephasedPlanned)
      {
         if (splitStart == null)
         {
            if (lastAssignment != null && lastRange != null && lastAssignment.getTotalAmount().getDuration() != 0 && assignment.getTotalAmount().getDuration() != 0)
            {
               splits.removeLast();
               lastRange = new DateRange(lastRange.getStart(), assignment.getFinish());
            }
            else
            {
               lastRange = new DateRange(assignment.getStart(), assignment.getFinish());
            }
         }
         else
         {
            lastRange = new DateRange(splitStart, assignment.getFinish());
         }
         splits.add(lastRange);
         splitStart = null;
         lastAssignment = assignment;
      }

      //
      // We must have a minimum of 3 entries for this to be a valid split task
      //
      if (splits.size() > 2)
      {
         task.getSplits().addAll(splits);
         task.setSplitCompleteDuration(splitsComplete);
      }
      else
      {
         task.setSplits(null);
         task.setSplitCompleteDuration(null);
      }
   }
36782
@Override
    public void afterCompletion(int status) {
        if (status == Status.STATUS_COMMITTED) {
            Boolean previous = persistentExecutor.inMemoryTaskIds.put(taskId, Boolean.TRUE);
            if (previous == null) {
                long delay = expectedExecTime - new Date().getTime();
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    Tr.debug(this, tc, "Schedule " + taskId + " for " + delay + "ms from now");
                persistentExecutor.scheduledExecutor.schedule(this, delay, TimeUnit.MILLISECONDS);
            } else {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    Tr.debug(this, tc, "Found task " + taskId + " already scheduled");
            }
        }
    }
1371297
public void schedule(BackoffTask task, long initialDelay, long fixedDelay) {
    	synchronized (queue) {
	    	start();
	        queue.put(new DelayedTimerTask(task, initialDelay, fixedDelay));
    	}
    }
1249327
protected void putPhase(Map<String, DevelopmentPhase> map, String key, DevelopmentPhase phase) {

    String newKey = key.toLowerCase(Locale.US);
    while (newKey != null) {
      DevelopmentPhase existingPhase = map.get(newKey);
      if ((existingPhase != null) && (existingPhase != phase)) {
        throw new IllegalStateException("Development phase '" + phase + "' has key '" + newKey + "' that is already mapped to '" + existingPhase + "'.");
      }
      map.put(newKey, phase);
      if (newKey.contains("-")) {
        newKey = newKey.replace("-", "");
      } else {
        newKey = null;
      }
    }
  }
1016540
public void addChildTaskBefore(Task child, Task previousSibling)
   {
      int index = m_children.indexOf(previousSibling);
      if (index == -1)
      {
         m_children.add(child);
      }
      else
      {
         m_children.add(index, child);
      }

      child.m_parent = this;
      setSummary(true);

      if (getParentFile().getProjectConfig().getAutoOutlineLevel() == true)
      {
         child.setOutlineLevel(Integer.valueOf(NumberHelper.getInt(getOutlineLevel()) + 1));
      }
   }
1088253
private void populateTask(Row row, Task task)
   {
      task.setUniqueID(row.getInteger("Z_PK"));
      task.setName(row.getString("ZTITLE"));
      task.setPriority(Priority.getInstance(row.getInt("ZPRIORITY")));
      task.setMilestone(row.getBoolean("ZISMILESTONE"));
      task.setActualFinish(row.getTimestamp("ZGIVENACTUALENDDATE_"));
      task.setActualStart(row.getTimestamp("ZGIVENACTUALSTARTDATE_"));
      task.setNotes(row.getString("ZOBJECTDESCRIPTION"));
      task.setDuration(row.getDuration("ZGIVENDURATION_"));
      task.setOvertimeWork(row.getWork("ZGIVENWORKOVERTIME_"));
      task.setWork(row.getWork("ZGIVENWORK_"));
      task.setLevelingDelay(row.getDuration("ZLEVELINGDELAY_"));
      task.setActualOvertimeWork(row.getWork("ZGIVENACTUALWORKOVERTIME_"));
      task.setActualWork(row.getWork("ZGIVENACTUALWORK_"));
      task.setRemainingWork(row.getWork("ZGIVENACTUALWORK_"));
      task.setGUID(row.getUUID("ZUNIQUEID"));

      Integer calendarID = row.getInteger("ZGIVENCALENDAR");
      if (calendarID != null)
      {
         ProjectCalendar calendar = m_project.getCalendarByUniqueID(calendarID);
         if (calendar != null)
         {
            task.setCalendar(calendar);
         }
      }

      populateConstraints(row, task);

      // Percent complete is calculated bottom up from assignments and actual work vs. planned work

      m_eventManager.fireTaskReadEvent(task);
   }
766951
@Override
    public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period) {
        ScheduledExecutorService executor = getScheduledExecutor();
        try {
            return executor.scheduleAtFixedRate(errorHandlingTask(task, true), 0, period, TimeUnit.MILLISECONDS);
        } catch (RejectedExecutionException ex) {
            throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, ex);
        }
    }
1039227
public void cancel(TimerTask task) {
        //CANCEL needs to remove the shceduled timer see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6602600
        //to improve perf

        ScheduledFuture<?> future = null;
        Object[] array = super.getQueue().toArray();
        for(int i = 0; i<array.length; i++) {
            if(array[i] instanceof ScheduledFuture<?>){
                future = (ScheduledFuture<?>)array[i];
                try {

                    Field callableField = future.getClass().getDeclaredField("callable");
                    callableField.setAccessible(true);
                    Object callable = callableField.get(future);
                    callableField.setAccessible(false);

                    if(callable!=null){
                        Field taskField = callable.getClass().getDeclaredField("task");
                        taskField.setAccessible(true);
                        TimerTask scheduledTask = null;
                        if(taskField.get(callable) instanceof TimerTask){
                             scheduledTask = (TimerTask) taskField.get(callable);
                        }
                        taskField.setAccessible(false);

                        if(scheduledTask!=null && scheduledTask.equals(task)){
                            break;
                        }
                    }
                } catch (Exception e) {
                    logger.warn("Couldn't clean the timer from the JVM GC ", e);
                }
            }
        }

        if(future != null) {
            boolean removed = super.remove((Runnable) future);
            if(logger.isDebugEnabled()) {
                logger.debug("expiration timer on sip proxy task" + task + " removed : " + removed);
            }
            boolean cancelled = future.cancel(true);
            if(logger.isDebugEnabled()) {
                logger.debug("expiration timer on sip proxy task" + task + " Cancelled : " + cancelled);
            }

            future = null;
            // Purge is expensive when called frequently, only call it every now and then.
            // We do not sync the numCancelled variable. We dont care about correctness of
            // the number, and we will still call purge rought once on every 25 cancels.
            numCancelled++;
            if(numCancelled % 100 == 0) {
                super.purge();
            }
        } else {
            if(logger.isDebugEnabled()) {
                logger.debug("expiration timer future is null, thus cannot be Cancelled");
            }
        }
    }
1210207
protected void taskDone(int taskId, int rebalanceAsyncId) {
        String durationString = "";
        if(taskCompletionTimeMs >= 0) {
            long durationMs = System.currentTimeMillis() - taskCompletionTimeMs;
            taskCompletionTimeMs = -1;
            durationString = " in " + TimeUnit.MILLISECONDS.toSeconds(durationMs) + " seconds.";
        }
        taskLog("[TaskId : " + taskId + " ] Successfully finished rebalance of "
                + partitionStoreCount
                + " for async operation id " + rebalanceAsyncId + durationString);

        progressBar.completeTask(taskId, partitionStoreCount);
    }
1093944
@Override
    public void planOperation(Runnable operation) {
        operations.add(operation);

        if (operation instanceof AbstractOperation) {
            ExecutionEntity execution = ((AbstractOperation) operation).getExecution();
            if (execution != null) {
                commandContext.addInvolvedExecution(execution);
            }
        }

        logger.debug("Operation {} added to agenda", operation.getClass());
    }
778841
public static Object delayedValue(CompletionStage<Void> stage, Object syncValue, Throwable throwable) {
      if (throwable == null) {
         return delayedValue(stage, syncValue);
      }
      if (stage != null) {
         CompletableFuture<?> future = stage.toCompletableFuture();
         if (!future.isDone() || future.isCompletedExceptionally()) {
            return asyncValue(
                  stage.handle((ignore, t) -> {
                     if (t != null) {
                        throwable.addSuppressed(t);
                     }
                     return null;
                  }).thenCompose(ignore -> CompletableFutures.completedExceptionFuture(throwable))
            );
         }
      }
      return new SimpleAsyncInvocationStage(throwable);
   }
584381
public void process(Resource resource, int index, byte[] data)
   {
      CostRateTable result = new CostRateTable();

      if (data != null)
      {
         for (int i = 16; i + 44 <= data.length; i += 44)
         {
            Rate standardRate = new Rate(MPPUtility.getDouble(data, i), TimeUnit.HOURS);
            TimeUnit standardRateFormat = getFormat(MPPUtility.getShort(data, i + 8));
            Rate overtimeRate = new Rate(MPPUtility.getDouble(data, i + 16), TimeUnit.HOURS);
            TimeUnit overtimeRateFormat = getFormat(MPPUtility.getShort(data, i + 24));
            Double costPerUse = NumberHelper.getDouble(MPPUtility.getDouble(data, i + 32) / 100.0);
            Date endDate = MPPUtility.getTimestampFromTenths(data, i + 40);
            CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRateFormat, overtimeRate, overtimeRateFormat, costPerUse, endDate);
            result.add(entry);
         }
         Collections.sort(result);
      }
      else
      {
         //
         // MS Project economises by not actually storing the first cost rate
         // table if it doesn't need to, so we take this into account here.
         //
         if (index == 0)
         {
            Rate standardRate = resource.getStandardRate();
            Rate overtimeRate = resource.getOvertimeRate();
            Number costPerUse = resource.getCostPerUse();
            CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRate.getUnits(), overtimeRate, overtimeRate.getUnits(), costPerUse, CostRateTableEntry.DEFAULT_ENTRY.getEndDate());
            result.add(entry);
         }
         else
         {
            result.add(CostRateTableEntry.DEFAULT_ENTRY);
         }
      }

      resource.setCostRateTable(index, result);
   }
1295535
protected void transmitAtEndOfTask(final Task<Revision> task,
			final Task<Diff> result)
		throws TimeoutException
	{

		if (task.getTaskType() == TaskTypes.TASK_FULL
				|| task.getTaskType() == TaskTypes.TASK_PARTIAL_LAST) {

			if (this.partCounter > 1) {
				this.result.setTaskType(TaskTypes.TASK_PARTIAL_LAST);
				this.taskTransmitter.transmitPartialDiff(result);
			}
			else {
				this.result.setTaskType(TaskTypes.TASK_FULL);
				this.taskTransmitter.transmitDiff(result);
			}

			this.result = null;
		}
	}
195176
@Override
	protected void postProcessContent(Map<String, Object> content) {
		replaceValue(getNestedMap(content, "commit"), "time",
				getProperties().getCommitTime());
		replaceValue(getNestedMap(content, "build"), "time",
				getProperties().getInstant("build.time"));
	}
1024938
void reportTaskFinished(TaskAttemptID taskid, boolean commitPending) {
    TaskInProgress tip;
    synchronized (this) {
      tip = tasks.get(taskid);
    }
    if (tip != null) {
      tip.reportTaskFinished(commitPending);
    } else {
      LOG.warn("Unknown child task finished: "+taskid+". Ignored.");
    }
  }
600348
void setPhase(Phase phase){
    TaskStatus.Phase oldPhase = getPhase();
    if (oldPhase != phase){
      // sort phase started
      if (phase == TaskStatus.Phase.SORT){
        setShuffleFinishTime(JobTracker.getClock().getTime());
      } else if (phase == TaskStatus.Phase.REDUCE){
        setSortFinishTime(JobTracker.getClock().getTime());
      }
    }
    this.phase = phase; 
  }
752643
@Override
    public synchronized void deleteTask(Task task) throws TaskNotFoundException {
        if (!this.inprocess.contains(task)) {
            log.error("{} not found.", task);

            throw new TaskNotFoundException("task not found:" + task.toString());
        }

        this.inprocess.remove(task);
        this.completedCount++;
        log.info("{} complete", task);
    }