/*
(non-Javadoc)

@see org.activiti.engine.impl.history.HistoryManagerInterface# recordTaskDueDateChange(java.lang.String, java.util.Date)
166544
@Override
  public void recordTaskDueDateChange(String taskId, Date dueDate) {
    if (isHistoryLevelAtLeast(HistoryLevel.AUDIT)) {
      HistoricTaskInstanceEntity historicTaskInstance = getHistoricTaskInstanceEntityManager().findById(taskId);
      if (historicTaskInstance != null) {
        historicTaskInstance.setDueDate(dueDate);
      }
    }
  }
542567
public void setDate(Date date) {
		for (int i = 0; i < 4; i++) {
			((JDateChooser) components[i]).setDate(date);
		}
	}
1302131
public void schedule(TimerTask task, boolean checkIfAlreadyPresent) {
		
		final TimerTaskData taskData = task.getData(); 
		final Serializable taskID = taskData.getTaskID();
		task.setScheduler(this);
		
		if (logger.isDebugEnabled()) {
			logger.debug("Scheduling task with id " + taskID);
		}
		
		// store the task and data
		final TimerTaskCacheData timerTaskCacheData = new TimerTaskCacheData(taskID, baseFqn, cluster);
		if (timerTaskCacheData.create()) {
			timerTaskCacheData.setTaskData(taskData);
		} else if(checkIfAlreadyPresent) {
            throw new IllegalStateException("timer task " + taskID + " already scheduled");
		}
				
		// schedule task
		final SetTimerAfterTxCommitRunnable setTimerAction = new SetTimerAfterTxCommitRunnable(task, this);
		if (txManager != null) {
			try {
				Transaction tx = txManager.getTransaction();
				if (tx != null) {
					TransactionContext txContext = TransactionContextThreadLocal.getTransactionContext();
					if (txContext == null) {
						txContext = new TransactionContext();
						tx.registerSynchronization(new TransactionSynchronization(txContext));
					}
					txContext.put(taskID, setTimerAction);					
					task.setSetTimerTransactionalAction(setTimerAction);
				}
				else {
					setTimerAction.run();
				}
			}
			catch (Throwable e) {
				remove(taskID,true);
				throw new RuntimeException("Unable to register tx synchronization object",e);
			}
		}
		else {
			setTimerAction.run();
		}		
	}
361774
protected void setDate(Date date, boolean firePropertyChange) {
		Date oldDate = this.date;
		this.date = date;

		if (date == null) {
			setText("");
		} else {
			String formattedDate = dateFormatter.format(date);
			try {
				setText(formattedDate);
			} catch (RuntimeException e) {
				e.printStackTrace();
			}
		}
		if (date != null && dateUtil.checkDate(date)) {
			setForeground(Color.BLACK);

		}

		if (firePropertyChange) {
			firePropertyChange("date", oldDate, date);
		}
	}
134713
void onDateGroupChanged(@Observes DataSetGroupDateChanged event) {
        ColumnGroup columnGroup = event.getColumnGroup();
        DataSetGroup groupOp = getFirstGroupOp();
        if (groupOp != null) {
            groupOp.setColumnGroup(columnGroup);

            changeEvent.fire(new DataSetLookupChangedEvent(dataSetLookup));
        }
    }
1327615
private void updateDates(Task parentTask)
   {
      if (parentTask.hasChildTasks())
      {
         int finished = 0;
         Date startDate = parentTask.getStart();
         Date finishDate = parentTask.getFinish();
         Date actualStartDate = parentTask.getActualStart();
         Date actualFinishDate = parentTask.getActualFinish();
         Date earlyStartDate = parentTask.getEarlyStart();
         Date earlyFinishDate = parentTask.getEarlyFinish();
         Date lateStartDate = parentTask.getLateStart();
         Date lateFinishDate = parentTask.getLateFinish();

         for (Task task : parentTask.getChildTasks())
         {
            updateDates(task);

            startDate = DateHelper.min(startDate, task.getStart());
            finishDate = DateHelper.max(finishDate, task.getFinish());
            actualStartDate = DateHelper.min(actualStartDate, task.getActualStart());
            actualFinishDate = DateHelper.max(actualFinishDate, task.getActualFinish());
            earlyStartDate = DateHelper.min(earlyStartDate, task.getEarlyStart());
            earlyFinishDate = DateHelper.max(earlyFinishDate, task.getEarlyFinish());
            lateStartDate = DateHelper.min(lateStartDate, task.getLateStart());
            lateFinishDate = DateHelper.max(lateFinishDate, task.getLateFinish());

            if (task.getActualFinish() != null)
            {
               ++finished;
            }
         }

         parentTask.setStart(startDate);
         parentTask.setFinish(finishDate);
         parentTask.setActualStart(actualStartDate);
         parentTask.setEarlyStart(earlyStartDate);
         parentTask.setEarlyFinish(earlyFinishDate);
         parentTask.setLateStart(lateStartDate);
         parentTask.setLateFinish(lateFinishDate);

         //
         // Only if all child tasks have actual finish dates do we
         // set the actual finish date on the parent task.
         //
         if (finished == parentTask.getChildTasks().size())
         {
            parentTask.setActualFinish(actualFinishDate);
         }
      }
   }
314613
private void writeCalendar(ProjectCalendar record) throws IOException
   {
      //
      // Test used to ensure that we don't write the default calendar used for the "Unassigned" resource
      //
      if (record.getParent() == null || record.getResource() != null)
      {
         m_buffer.setLength(0);

         if (record.getParent() == null)
         {
            m_buffer.append(MPXConstants.BASE_CALENDAR_RECORD_NUMBER);
            m_buffer.append(m_delimiter);
            if (record.getName() != null)
            {
               m_buffer.append(record.getName());
            }
         }
         else
         {
            m_buffer.append(MPXConstants.RESOURCE_CALENDAR_RECORD_NUMBER);
            m_buffer.append(m_delimiter);
            m_buffer.append(record.getParent().getName());
         }

         for (DayType day : record.getDays())
         {
            if (day == null)
            {
               day = DayType.DEFAULT;
            }
            m_buffer.append(m_delimiter);
            m_buffer.append(day.getValue());
         }

         m_buffer.append(MPXConstants.EOL);
         m_writer.write(m_buffer.toString());

         ProjectCalendarHours[] hours = record.getHours();
         for (int loop = 0; loop < hours.length; loop++)
         {
            if (hours[loop] != null)
            {
               writeCalendarHours(record, hours[loop]);
            }
         }

         if (!record.getCalendarExceptions().isEmpty())
         {
            //
            // A quirk of MS Project is that these exceptions must be
            // in date order in the file, otherwise they are ignored.
            // The getCalendarExceptions method now guarantees that
            // the exceptions list is sorted when retrieved.
            //
            for (ProjectCalendarException ex : record.getCalendarExceptions())
            {
               writeCalendarException(record, ex);
            }
         }

         m_eventManager.fireCalendarWrittenEvent(record);
      }
   }
1265083
private void writeCalendarException(ProjectCalendar parentCalendar, ProjectCalendarException record) throws IOException
   {
      m_buffer.setLength(0);
      Calendar stepDay = DateHelper.popCalendar(record.getFromDate()); // Start at From Date, then step through days...
      Calendar lastDay = DateHelper.popCalendar(record.getToDate()); // last day in this exception

      m_buffer.append("HOLI ");
      m_buffer.append(SDEFmethods.lset(parentCalendar.getUniqueID().toString(), 2));

      while (stepDay.compareTo(lastDay) <= 0)
      {
         m_buffer.append(m_formatter.format(stepDay.getTime()).toUpperCase() + " ");
         stepDay.add(Calendar.DAY_OF_MONTH, 1);
      }
      m_writer.println(m_buffer.toString());
      
      DateHelper.pushCalendar(stepDay);
      DateHelper.pushCalendar(lastDay);
   }
55548
private void writeTaskPredecessors(Task record)
   {
      m_buffer.setLength(0);
      //
      // Write the task predecessor
      //
      if (!record.getSummary() && !record.getPredecessors().isEmpty())
      { // I don't use summary tasks for SDEF
         m_buffer.append("PRED ");
         List<Relation> predecessors = record.getPredecessors();

         for (Relation pred : predecessors)
         {
            m_buffer.append(SDEFmethods.rset(pred.getSourceTask().getUniqueID().toString(), 10) + " ");
            m_buffer.append(SDEFmethods.rset(pred.getTargetTask().getUniqueID().toString(), 10) + " ");
            String type = "C"; // default finish-to-start
            if (!pred.getType().toString().equals("FS"))
            {
               type = pred.getType().toString().substring(0, 1);
            }
            m_buffer.append(type + " ");

            Duration dd = pred.getLag();
            double duration = dd.getDuration();
            if (dd.getUnits() != TimeUnit.DAYS)
            {
               dd = Duration.convertUnits(duration, dd.getUnits(), TimeUnit.DAYS, m_minutesPerDay, m_minutesPerWeek, m_daysPerMonth);
            }
            Double days = Double.valueOf(dd.getDuration() + 0.5); // Add 0.5 so half day rounds up upon truncation
            Integer est = Integer.valueOf(days.intValue());
            m_buffer.append(SDEFmethods.rset(est.toString(), 4) + " "); // task duration in days required by USACE
         }
         m_writer.println(m_buffer.toString());
      }
   }
191435
public Calendar adjustDate(final Calendar startDate, final int increment, final NonWorkingDayChecker<Calendar> checker) {
        final Calendar cal = (Calendar) startDate.clone();

        while (checker.isNonWorkingDay(cal)) {
            cal.add(Calendar.DAY_OF_MONTH, increment);
        }

        return cal;
    }
113617
@Override
  public void recordTaskDescriptionChange(String taskId, String description) {
    if (isHistoryLevelAtLeast(HistoryLevel.AUDIT)) {
      HistoricTaskInstanceEntity historicTaskInstance = getHistoricTaskInstanceEntityManager().findById(taskId);
      if (historicTaskInstance != null) {
        historicTaskInstance.setDescription(description);
      }
    }
  }
218262
private void populateTask(Record record, Task task) throws MPXJException
   {
      String falseText = LocaleData.getString(m_locale, LocaleData.NO);

      int mpxFieldID = 0;
      String field;

      int i = 0;
      int length = record.getLength();
      int[] model = m_taskModel.getModel();

      while (i < length)
      {
         mpxFieldID = model[i];

         if (mpxFieldID == -1)
         {
            break;
         }

         field = record.getString(i++);

         if ((field == null) || (field.length() == 0))
         {
            continue;
         }

         TaskField taskField = MPXTaskField.getMpxjField(mpxFieldID);
         if (taskField == null)
         {
            System.out.println("Null Task Field " + mpxFieldID);
            continue;
         }

         switch (taskField)
         {
            case PREDECESSORS:
            case UNIQUE_ID_PREDECESSORS:
            {
               populateRelationList(task, taskField, field);
               break;
            }

            case PERCENT_COMPLETE:
            case PERCENT_WORK_COMPLETE:
            {
               try
               {
                  task.set(taskField, m_formats.getPercentageDecimalFormat().parse(field));
               }

               catch (ParseException ex)
               {
                  throw new MPXJException("Failed to parse percentage", ex);
               }
               break;
            }

            case ACTUAL_COST:
            case BASELINE_COST:
            case BCWP:
            case BCWS:
            case COST:
            case COST1:
            case COST2:
            case COST3:
            case COST_VARIANCE:
            case CV:
            case FIXED_COST:
            case REMAINING_COST:
            case SV:
            {
               try
               {
                  task.set(taskField, m_formats.getCurrencyFormat().parse(field));
               }

               catch (ParseException ex)
               {
                  throw new MPXJException("Failed to parse currency", ex);
               }
               break;
            }

            case ACTUAL_DURATION:
            case ACTUAL_WORK:
            case BASELINE_DURATION:
            case BASELINE_WORK:
            case DURATION:
            case DURATION1:
            case DURATION2:
            case DURATION3:
            case DURATION_VARIANCE:
            case FINISH_VARIANCE:
            case FREE_SLACK:
            case REMAINING_DURATION:
            case REMAINING_WORK:
            case START_VARIANCE:
            case TOTAL_SLACK:
            case WORK:
            case WORK_VARIANCE:
            case LEVELING_DELAY:
            {
               task.set(taskField, DurationUtility.getInstance(field, m_formats.getDurationDecimalFormat(), m_locale));
               break;
            }

            case ACTUAL_FINISH:
            case ACTUAL_START:
            case BASELINE_FINISH:
            case BASELINE_START:
            case CONSTRAINT_DATE:
            case CREATED:
            case EARLY_FINISH:
            case EARLY_START:
            case FINISH:
            case FINISH1:
            case FINISH2:
            case FINISH3:
            case FINISH4:
            case FINISH5:
            case LATE_FINISH:
            case LATE_START:
            case RESUME:
            case START:
            case START1:
            case START2:
            case START3:
            case START4:
            case START5:
            case STOP:
            {
               try
               {
                  task.set(taskField, m_formats.getDateTimeFormat().parse(field));
               }

               catch (ParseException ex)
               {
                  throw new MPXJException("Failed to parse date time", ex);
               }
               break;
            }

            case CONFIRMED:
            case CRITICAL:
            case FLAG1:
            case FLAG2:
            case FLAG3:
            case FLAG4:
            case FLAG5:
            case FLAG6:
            case FLAG7:
            case FLAG8:
            case FLAG9:
            case FLAG10:
            case HIDE_BAR:
            case LINKED_FIELDS:
            case MARKED:
            case MILESTONE:
            case ROLLUP:
            case SUMMARY:
            case UPDATE_NEEDED:
            {
               task.set(taskField, ((field.equalsIgnoreCase(falseText) == true) ? Boolean.FALSE : Boolean.TRUE));
               break;
            }

            case CONSTRAINT_TYPE:
            {
               task.set(taskField, ConstraintTypeUtility.getInstance(m_locale, field));
               break;
            }

            case OBJECTS:
            case OUTLINE_LEVEL:
            {
               task.set(taskField, Integer.valueOf(field));
               break;
            }

            case ID:
            {
               task.setID(Integer.valueOf(field));
               break;
            }

            case UNIQUE_ID:
            {
               task.setUniqueID(Integer.valueOf(field));
               break;
            }

            case NUMBER1:
            case NUMBER2:
            case NUMBER3:
            case NUMBER4:
            case NUMBER5:
            {
               try
               {
                  task.set(taskField, m_formats.getDecimalFormat().parse(field));
               }

               catch (ParseException ex)
               {
                  throw new MPXJException("Failed to parse number", ex);
               }

               break;
            }

            case PRIORITY:
            {
               task.set(taskField, PriorityUtility.getInstance(m_locale, field));
               break;
            }

            case TYPE:
            {
               boolean fixed = !field.equalsIgnoreCase(falseText);
               task.setType(fixed ? TaskType.FIXED_DURATION : TaskType.FIXED_UNITS);
               break;
            }

            default:
            {
               task.set(taskField, field);
               break;
            }
         }
      }

      if (m_projectConfig.getAutoWBS() == true)
      {
         task.generateWBS(null);
      }

      if (m_projectConfig.getAutoOutlineNumber() == true)
      {
         task.generateOutlineNumber(null);
      }

      if (m_projectConfig.getAutoOutlineLevel() == true)
      {
         task.setOutlineLevel(Integer.valueOf(1));
      }

      if (m_projectConfig.getAutoTaskUniqueID() == true)
      {
         task.setUniqueID(Integer.valueOf(m_projectConfig.getNextTaskUniqueID()));
      }

      if (task.getID() == null || m_projectConfig.getAutoTaskID() == true)
      {
         task.setID(Integer.valueOf(m_projectConfig.getNextTaskID()));
      }

      //
      // Handle malformed MPX files - ensure we have a unique ID
      //
      if (task.getUniqueID() == null)
      {
         task.setUniqueID(task.getID());
      }

      //
      // Some applications (I'm looking at you SureTrak) don't write start and finish
      // attributes. If you open an MPX file like this in MS Project, it will use
      // the early start and early finish values (if present) to populate
      // the start and finish attributes.

      if (task.getStart() == null && task.getEarlyStart() != null)
      {
         task.setStart(task.getEarlyStart());
      }

      if (task.getFinish() == null && task.getEarlyFinish() != null)
      {
         task.setFinish(task.getEarlyFinish());
      }
   }
831567
@Override
    public void changed(@NonNull DatabaseChange change) {
        synchronized (lock) {
            if (willUpdate) {
                return; // Already a pending update scheduled
            }

            if (!observing) { return; }

            // Schedule an update, respecting the updateInterval:
            long updateDelay = lastUpdatedAt + DEFAULT_LIVE_QUERY_UPDATE_INTERVAL - System.currentTimeMillis();
            updateDelay = Math.max(0, Math.min(DEFAULT_LIVE_QUERY_UPDATE_INTERVAL, updateDelay));
            update(updateDelay);
        }
    }
580190
@UiHandler("m_dateCreatedStartDateBox")
    protected void onDateCreatedStartChange(ValueChangeEvent<Date> event) {

        if (event.getValue() != null) {
            m_tabHandler.setDateCreatedStart(event.getValue().getTime());
        } else {
            // if the field is empty take the min value
            m_tabHandler.setDateCreatedStart(-1L);
        }
    }
182507
@Override
  public void recordTaskEnd(String taskId, String deleteReason) {
    if (isHistoryLevelAtLeast(HistoryLevel.AUDIT)) {
      HistoricTaskInstanceEntity historicTaskInstance = getHistoricTaskInstanceEntityManager().findById(taskId);
      if (historicTaskInstance != null) {
        historicTaskInstance.markEnded(deleteReason);
      }
    }
  }
568561
public boolean surveyDates(boolean bDisplayOption)
    {
        if (m_recDetail == null)
        {
            RecordOwner recordOwner = this.getRecordOwner();
            m_recDetail = new ProjectTask(recordOwner);
            if (recordOwner != null)
                recordOwner.removeRecord(m_recDetail);
            m_recDetail.addListener(new SubFileFilter(this, true));
        }
        Date startDate = null;
        Date endDate = null;
        try {
            m_recDetail.close();
            while (m_recDetail.hasNext())
            {
                m_recDetail.next();
                Date thisStartDate = null;
                if (!m_recDetail.getField(ProjectTask.START_DATE_TIME).isNull())
                    thisStartDate = ((DateTimeField)m_recDetail.getField(ProjectTask.START_DATE_TIME)).getDateTime();
                if (thisStartDate != null)
                    if ((startDate == null)
                        || (thisStartDate.before(startDate)))
                            startDate = thisStartDate;
                Date thisEndDate = null;
                if (!m_recDetail.getField(ProjectTask.END_DATE_TIME).isNull())
                    thisEndDate = ((DateTimeField)m_recDetail.getField(ProjectTask.END_DATE_TIME)).getDateTime();
                if (thisEndDate != null)
                    if ((endDate == null)
                        || (thisEndDate.after(endDate)))
                            endDate = thisEndDate;
            }
            this.getListener(UpdateChildrenHandler.class).setEnabledListener(false);
            this.edit();
            int iMoveMode = DBConstants.SCREEN_MOVE;
            if (startDate != null)
                ((DateTimeField)this.getField(ProjectTask.START_DATE_TIME)).setDateTime(startDate, bDisplayOption, iMoveMode);
            if (endDate != null)
                ((DateTimeField)this.getField(ProjectTask.END_DATE_TIME)).setDateTime(endDate, bDisplayOption, iMoveMode);
            boolean bHasChildren = true;
            if ((startDate == null) && (endDate == null))
                bHasChildren = false;
            this.getField(ProjectTask.HAS_CHILDREN).setState(bHasChildren);
            if (this.isModified())
            {
                Object bookmark = this.getHandle(DBConstants.BOOKMARK_HANDLE);
                this.set();
                this.setHandle(bookmark, DBConstants.BOOKMARK_HANDLE);
                return true;    // Record updated
            }
        } catch (DBException ex) {
            ex.printStackTrace();
        } finally {
            this.getListener(UpdateChildrenHandler.class).setEnabledListener(true);
        }
        return false;   // No update required
    }
205096
public Date adjustDate(final Date startDate, final int increment, final NonWorkingDayChecker<Date> checker) {
        final Calendar cal = Utils.getCal(startDate);

        while (checker.isNonWorkingDay(cal.getTime())) {
            if (increment < 0) {
                cal.add(Calendar.DAY_OF_MONTH, -1);
            } else {
                cal.add(Calendar.DAY_OF_MONTH, 1);
            }
        }

        return cal.getTime();
    }