Reads timephased assignment data.

@param calendar current calendar
@param assignment assignment data
@param type flag indicating if this is planned or complete work
@return list of timephased resource assignment instances
513351
private LinkedList<TimephasedWork> readTimephasedAssignment(ProjectCalendar calendar, Project.Assignments.Assignment assignment, int type)
   {
      LinkedList<TimephasedWork> result = new LinkedList<TimephasedWork>();

      for (TimephasedDataType item : assignment.getTimephasedData())
      {
         if (NumberHelper.getInt(item.getType()) != type)
         {
            continue;
         }

         Date startDate = item.getStart();
         Date finishDate = item.getFinish();

         // Exclude ranges which don't have a start and end date.
         // These seem to be generated by Synchro and have a zero duration.
         if (startDate == null && finishDate == null)
         {
            continue;
         }

         Duration work = DatatypeConverter.parseDuration(m_projectFile, TimeUnit.MINUTES, item.getValue());
         if (work == null)
         {
            work = Duration.getInstance(0, TimeUnit.MINUTES);
         }
         else
         {
            work = Duration.getInstance(NumberHelper.round(work.getDuration(), 2), TimeUnit.MINUTES);
         }

         TimephasedWork tra = new TimephasedWork();
         tra.setStart(startDate);
         tra.setFinish(finishDate);
         tra.setTotalAmount(work);

         result.add(tra);
      }

      return result;
   }
664961
private void readCalendar(Calendar calendar)
   {
      ProjectCalendar mpxjCalendar = m_projectFile.addCalendar();
      mpxjCalendar.setName(calendar.getName());
      m_calendarMap.put(calendar.getID(), mpxjCalendar);

      for (WeekDay day : calendar.getWeekDays().getWeekDay())
      {
         readWeekDay(mpxjCalendar, day);
      }

      for (ExceptedDay day : calendar.getExceptedDays().getExceptedDay())
      {
         readExceptionDay(mpxjCalendar, day);
      }
   }
387982
private void readCalendars(Storepoint phoenixProject)
   {
      Calendars calendars = phoenixProject.getCalendars();
      if (calendars != null)
      {
         for (Calendar calendar : calendars.getCalendar())
         {
            readCalendar(calendar);
         }

         ProjectCalendar defaultCalendar = m_projectFile.getCalendarByName(phoenixProject.getDefaultCalendar());
         if (defaultCalendar != null)
         {
            m_projectFile.getProjectProperties().setDefaultCalendarName(defaultCalendar.getName());
         }
      }
   }
322212
public static Date parseDate(TimeType timeType, String date) {
        SimpleDateFormat sdf = getDateFormat(timeType);
        try {
            return sdf.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
533249
public static <T> Position.ReadWrite<T> readWrite(final Class<T> type) {
        return readWrite((Type) type);
    }
1178783
public <T> T readToJson(Type type) {
        try {
            return JsonLookup.getInstance().lookup().unmarshal(body(), getCharset(), type);
        } catch (IOException e) {
            throw new RequestsException(e);
        } finally {
            close();
        }
    }
846006
public static synchronized PeriodType forFields(DurationFieldType[] types) {
        if (types == null || types.length == 0) {
            throw new IllegalArgumentException("Types array must not be null or empty");
        }
        for (int i = 0; i < types.length; i++) {
            if (types[i] == null) {
                throw new IllegalArgumentException("Types array must not contain null");
            }
        }
        Map<PeriodType, Object> cache = cTypes;
        if (cache.isEmpty()) {
            cache.put(standard(), standard());
            cache.put(yearMonthDayTime(), yearMonthDayTime());
            cache.put(yearMonthDay(), yearMonthDay());
            cache.put(yearWeekDayTime(), yearWeekDayTime());
            cache.put(yearWeekDay(), yearWeekDay());
            cache.put(yearDayTime(), yearDayTime());
            cache.put(yearDay(), yearDay());
            cache.put(dayTime(), dayTime());
            cache.put(time(), time());
            cache.put(years(), years());
            cache.put(months(), months());
            cache.put(weeks(), weeks());
            cache.put(days(), days());
            cache.put(hours(), hours());
            cache.put(minutes(), minutes());
            cache.put(seconds(), seconds());
            cache.put(millis(), millis());
        }
        PeriodType inPartType = new PeriodType(null, types, null);
        Object cached = cache.get(inPartType);
        if (cached instanceof PeriodType) {
            return (PeriodType) cached;
        }
        if (cached != null) {
            throw new IllegalArgumentException("PeriodType does not support fields: " + cached);
        }
        PeriodType type = standard();
        List<DurationFieldType> list = new ArrayList<DurationFieldType>(Arrays.asList(types));
        if (list.remove(DurationFieldType.years()) == false) {
            type = type.withYearsRemoved();
        }
        if (list.remove(DurationFieldType.months()) == false) {
            type = type.withMonthsRemoved();
        }
        if (list.remove(DurationFieldType.weeks()) == false) {
            type = type.withWeeksRemoved();
        }
        if (list.remove(DurationFieldType.days()) == false) {
            type = type.withDaysRemoved();
        }
        if (list.remove(DurationFieldType.hours()) == false) {
            type = type.withHoursRemoved();
        }
        if (list.remove(DurationFieldType.minutes()) == false) {
            type = type.withMinutesRemoved();
        }
        if (list.remove(DurationFieldType.seconds()) == false) {
            type = type.withSecondsRemoved();
        }
        if (list.remove(DurationFieldType.millis()) == false) {
            type = type.withMillisRemoved();
        }
        if (list.size() > 0) {
            cache.put(inPartType, list);
            throw new IllegalArgumentException("PeriodType does not support fields: " + list);
        }
        // recheck cache in case initial array order was wrong
        PeriodType checkPartType = new PeriodType(null, type.iTypes, null);
        PeriodType checkedType = (PeriodType) cache.get(checkPartType);
        if (checkedType != null) {
            cache.put(checkPartType, checkedType);
            return checkedType;
        }
        cache.put(checkPartType, type);
        return type;
    }
796861
private void readAssignment(Resource resource, Assignment assignment)
   {
      Task task = m_activityMap.get(assignment.getActivity());
      if (task != null)
      {
         task.addResourceAssignment(resource);
      }
   }
345711
private void writeAssignmentTimephasedData(ResourceAssignment mpx, Project.Assignments.Assignment xml)
   {
      if (m_writeTimphasedData && mpx.getHasTimephasedData())
      {
         List<TimephasedDataType> list = xml.getTimephasedData();
         ProjectCalendar calendar = mpx.getCalendar();
         BigInteger assignmentID = xml.getUID();

         List<TimephasedWork> complete = mpx.getTimephasedActualWork();
         List<TimephasedWork> planned = mpx.getTimephasedWork();

         if (m_splitTimephasedAsDays)
         {
            TimephasedWork lastComplete = null;
            if (complete != null && !complete.isEmpty())
            {
               lastComplete = complete.get(complete.size() - 1);
            }

            TimephasedWork firstPlanned = null;
            if (planned != null && !planned.isEmpty())
            {
               firstPlanned = planned.get(0);
            }

            if (planned != null)
            {
               planned = splitDays(calendar, mpx.getTimephasedWork(), null, lastComplete);
            }

            if (complete != null)
            {
               complete = splitDays(calendar, complete, firstPlanned, null);
            }
         }

         if (planned != null)
         {
            writeAssignmentTimephasedData(assignmentID, list, planned, 1);
         }

         if (complete != null)
         {
            writeAssignmentTimephasedData(assignmentID, list, complete, 2);
         }
      }
   }
376361
@ReadOperation
    public Map<String, Object> getSsoSessions(final String type) {
        val sessionsMap = new HashMap<String, Object>(1);
        val option = SsoSessionReportOptions.valueOf(type);
        val activeSsoSessions = getActiveSsoSessions(option);
        sessionsMap.put("activeSsoSessions", activeSsoSessions);
        val totalTicketGrantingTickets = new AtomicLong();
        val totalProxyGrantingTickets = new AtomicLong();
        val totalUsageCount = new AtomicLong();
        val uniquePrincipals = new HashSet<Object>();
        for (val activeSsoSession : activeSsoSessions) {
            if (activeSsoSession.containsKey(SsoSessionAttributeKeys.IS_PROXIED.toString())) {
                val isProxied = Boolean.valueOf(activeSsoSession.get(SsoSessionAttributeKeys.IS_PROXIED.toString()).toString());
                if (isProxied) {
                    totalProxyGrantingTickets.incrementAndGet();
                } else {
                    totalTicketGrantingTickets.incrementAndGet();
                    val principal = activeSsoSession.get(SsoSessionAttributeKeys.AUTHENTICATED_PRINCIPAL.toString()).toString();
                    uniquePrincipals.add(principal);
                }
            } else {
                totalTicketGrantingTickets.incrementAndGet();
                val principal = activeSsoSession.get(SsoSessionAttributeKeys.AUTHENTICATED_PRINCIPAL.toString()).toString();
                uniquePrincipals.add(principal);
            }
            val uses = Long.parseLong(activeSsoSession.get(SsoSessionAttributeKeys.NUMBER_OF_USES.toString()).toString());
            totalUsageCount.getAndAdd(uses);
        }
        sessionsMap.put("totalProxyGrantingTickets", totalProxyGrantingTickets);
        sessionsMap.put("totalTicketGrantingTickets", totalTicketGrantingTickets);
        sessionsMap.put("totalTickets", totalTicketGrantingTickets.longValue() + totalProxyGrantingTickets.longValue());
        sessionsMap.put("totalPrincipals", uniquePrincipals.size());
        sessionsMap.put("totalUsageCount", totalUsageCount);
        return sessionsMap;
    }
701045
@Override
    public void readExternal(ObjectInput in)
        throws IOException {

        byte header = in.readByte();

        switch (header) {
            case BAHAI:
                this.obj = this.readBahai(in);
                break;
            default:
                throw new InvalidObjectException("Unknown calendar type.");
        }

    }
1123692
private void processWorkingHours(ProjectCalendar mpxjCalendar, net.sf.mpxj.planner.schema.Calendar plannerCalendar) throws MPXJException
   {
      OverriddenDayTypes types = plannerCalendar.getOverriddenDayTypes();
      if (types != null)
      {
         List<OverriddenDayType> typeList = types.getOverriddenDayType();
         Iterator<OverriddenDayType> iter = typeList.iterator();
         OverriddenDayType odt = null;
         while (iter.hasNext())
         {
            odt = iter.next();
            if (getInt(odt.getId()) != 0)
            {
               odt = null;
               continue;
            }

            break;
         }

         if (odt != null)
         {
            List<Interval> intervalList = odt.getInterval();
            ProjectCalendarHours mondayHours = null;
            ProjectCalendarHours tuesdayHours = null;
            ProjectCalendarHours wednesdayHours = null;
            ProjectCalendarHours thursdayHours = null;
            ProjectCalendarHours fridayHours = null;
            ProjectCalendarHours saturdayHours = null;
            ProjectCalendarHours sundayHours = null;

            if (mpxjCalendar.isWorkingDay(Day.MONDAY))
            {
               mondayHours = mpxjCalendar.addCalendarHours(Day.MONDAY);
            }

            if (mpxjCalendar.isWorkingDay(Day.TUESDAY))
            {
               tuesdayHours = mpxjCalendar.addCalendarHours(Day.TUESDAY);
            }

            if (mpxjCalendar.isWorkingDay(Day.WEDNESDAY))
            {
               wednesdayHours = mpxjCalendar.addCalendarHours(Day.WEDNESDAY);
            }

            if (mpxjCalendar.isWorkingDay(Day.THURSDAY))
            {
               thursdayHours = mpxjCalendar.addCalendarHours(Day.THURSDAY);
            }

            if (mpxjCalendar.isWorkingDay(Day.FRIDAY))
            {
               fridayHours = mpxjCalendar.addCalendarHours(Day.FRIDAY);
            }

            if (mpxjCalendar.isWorkingDay(Day.SATURDAY))
            {
               saturdayHours = mpxjCalendar.addCalendarHours(Day.SATURDAY);
            }

            if (mpxjCalendar.isWorkingDay(Day.SUNDAY))
            {
               sundayHours = mpxjCalendar.addCalendarHours(Day.SUNDAY);
            }

            for (Interval interval : intervalList)
            {
               Date startTime = getTime(interval.getStart());
               Date endTime = getTime(interval.getEnd());

               m_defaultWorkingHours.add(new DateRange(startTime, endTime));

               if (mondayHours != null)
               {
                  mondayHours.addRange(new DateRange(startTime, endTime));
               }

               if (tuesdayHours != null)
               {
                  tuesdayHours.addRange(new DateRange(startTime, endTime));
               }

               if (wednesdayHours != null)
               {
                  wednesdayHours.addRange(new DateRange(startTime, endTime));
               }

               if (thursdayHours != null)
               {
                  thursdayHours.addRange(new DateRange(startTime, endTime));
               }

               if (fridayHours != null)
               {
                  fridayHours.addRange(new DateRange(startTime, endTime));
               }

               if (saturdayHours != null)
               {
                  saturdayHours.addRange(new DateRange(startTime, endTime));
               }

               if (sundayHours != null)
               {
                  sundayHours.addRange(new DateRange(startTime, endTime));
               }
            }
         }
      }
   }
1332424
public synchronized Object convertToDatetimeInterval(String s,
            DTIType type) {

        Object       value;
        IntervalType intervalType  = null;
        int          dateTimeToken = -1;
        int          errorCode     = type.isDateTimeType() ? ErrorCode.X_22007
                                                           : ErrorCode.X_22006;

        reset(s);
        resetState();
        scanToken();
        scanWhitespace();

        switch (token.tokenType) {

            case Tokens.INTERVAL :
            case Tokens.DATE :
            case Tokens.TIME :
            case Tokens.TIMESTAMP :
                dateTimeToken = token.tokenType;

                scanToken();

                if (token.tokenType != Tokens.X_VALUE
                        || token.dataType.typeCode != Types.SQL_CHAR) {

                    // error datetime bad literal
                    throw Error.error(errorCode);
                }

                s = token.tokenString;

                scanNext(ErrorCode.X_22007);

                if (type.isIntervalType()) {
                    intervalType = scanIntervalType();
                }

                if (token.tokenType != Tokens.X_ENDPARSE) {
                    throw Error.error(errorCode);
                }

            // $FALL-THROUGH$
            default :
        }

        switch (type.typeCode) {

            case Types.SQL_DATE :
                if (dateTimeToken != -1 && dateTimeToken != Tokens.DATE) {
                    throw Error.error(errorCode);
                }

                return newDate(s);

            case Types.SQL_TIME :
            case Types.SQL_TIME_WITH_TIME_ZONE : {
                if (dateTimeToken != -1 && dateTimeToken != Tokens.TIME) {
                    throw Error.error(errorCode);
                }

                return newTime(s);
            }
            case Types.SQL_TIMESTAMP :
            case Types.SQL_TIMESTAMP_WITH_TIME_ZONE : {
                if (dateTimeToken != -1 && dateTimeToken != Tokens.TIMESTAMP) {
                    throw Error.error(errorCode);
                }

                return newTimestamp(s);
            }
            default :
                if (dateTimeToken != -1 && dateTimeToken != Tokens.INTERVAL) {
                    throw Error.error(errorCode);
                }

                if (type.isIntervalType()) {
                    value = newInterval(s, (IntervalType) type);

                    if (intervalType != null) {
                        if (intervalType.startIntervalType != type
                                .startIntervalType || intervalType
                                .endIntervalType != type.endIntervalType) {
                            throw Error.error(errorCode);
                        }
                    }

                    return value;
                }

                throw Error.runtimeError(ErrorCode.U_S0500, "Scanner");
        }
    }
1214026
public static Date getInstance(final java.util.Date date, final Value type) {
        if (Value.DATE.equals(type)) {
            return new Date(date);
        }
        return new DateTime(date);
    }
1076573
public void processActivityCodes(List<Row> types, List<Row> typeValues, List<Row> assignments)
   {
      ActivityCodeContainer container = m_project.getActivityCodes();
      Map<Integer, ActivityCode> map = new HashMap<Integer, ActivityCode>();

      for (Row row : types)
      {
         ActivityCode code = new ActivityCode(row.getInteger("actv_code_type_id"), row.getString("actv_code_type"));
         container.add(code);
         map.put(code.getUniqueID(), code);
      }

      for (Row row : typeValues)
      {
         ActivityCode code = map.get(row.getInteger("actv_code_type_id"));
         if (code != null)
         {
            ActivityCodeValue value = code.addValue(row.getInteger("actv_code_id"), row.getString("short_name"), row.getString("actv_code_name"));
            m_activityCodeMap.put(value.getUniqueID(), value);
         }
      }

      for (Row row : assignments)
      {
         Integer taskID = row.getInteger("task_id");
         List<Integer> list = m_activityCodeAssignments.get(taskID);
         if (list == null)
         {
            list = new ArrayList<Integer>();
            m_activityCodeAssignments.put(taskID, list);
         }
         list.add(row.getInteger("actv_code_id"));
      }
   }
134863
private void readCalendars(Project project, HashMap<BigInteger, ProjectCalendar> map)
   {
      Project.Calendars calendars = project.getCalendars();
      if (calendars != null)
      {
         LinkedList<Pair<ProjectCalendar, BigInteger>> baseCalendars = new LinkedList<Pair<ProjectCalendar, BigInteger>>();
         for (Project.Calendars.Calendar cal : calendars.getCalendar())
         {
            readCalendar(cal, map, baseCalendars);
         }
         updateBaseCalendarNames(baseCalendars, map);
      }

      try
      {
         ProjectProperties properties = m_projectFile.getProjectProperties();
         BigInteger calendarID = new BigInteger(properties.getDefaultCalendarName());
         ProjectCalendar calendar = map.get(calendarID);
         m_projectFile.setDefaultCalendar(calendar);
      }

      catch (Exception ex)
      {
         // Ignore exceptions
      }
   }
20604
private List<TimephasedCost> getTimephasedCostFixedAmount()
   {
      List<TimephasedCost> result = new LinkedList<TimephasedCost>();

      ProjectCalendar cal = getCalendar();

      double remainingCost = getRemainingCost().doubleValue();

      if (remainingCost > 0)
      {
         AccrueType accrueAt = getResource().getAccrueAt();

         if (accrueAt == AccrueType.START)
         {
            result.add(splitCostStart(cal, remainingCost, getStart()));
         }
         else
            if (accrueAt == AccrueType.END)
            {
               result.add(splitCostEnd(cal, remainingCost, getFinish()));
            }
            else
            {
               //for prorated, we have to deal with it differently depending on whether or not
               //any actual has been entered, since we want to mimic the other timephased data
               //where planned and actual values do not overlap
               double numWorkingDays = cal.getWork(getStart(), getFinish(), TimeUnit.DAYS).getDuration();
               double standardAmountPerDay = getCost().doubleValue() / numWorkingDays;

               if (getActualCost().intValue() > 0)
               {
                  //need to get three possible blocks of data: one for the possible partial amount
                  //overlap with timephased actual cost; one with all the standard amount days
                  //that happen after the actual cost stops; and one with any remaining
                  //partial day cost amount

                  int numActualDaysUsed = (int) Math.ceil(getActualCost().doubleValue() / standardAmountPerDay);
                  Date actualWorkFinish = cal.getDate(getStart(), Duration.getInstance(numActualDaysUsed, TimeUnit.DAYS), false);

                  double partialDayActualAmount = getActualCost().doubleValue() % standardAmountPerDay;

                  if (partialDayActualAmount > 0)
                  {
                     double dayAmount = standardAmountPerDay < remainingCost ? standardAmountPerDay - partialDayActualAmount : remainingCost;

                     result.add(splitCostEnd(cal, dayAmount, actualWorkFinish));

                     remainingCost -= dayAmount;
                  }

                  //see if there's anything left to work with
                  if (remainingCost > 0)
                  {
                     //have to split up the amount into standard prorated amount days and whatever is left
                     result.addAll(splitCostProrated(cal, remainingCost, standardAmountPerDay, cal.getNextWorkStart(actualWorkFinish)));
                  }

               }
               else
               {
                  //no actual cost to worry about, so just a standard split from the beginning of the assignment
                  result.addAll(splitCostProrated(cal, remainingCost, standardAmountPerDay, getStart()));
               }
            }
      }

      return result;
   }