code
stringlengths
73
34.1k
label
stringclasses
1 value
private List<MapRow> sort(List<MapRow> rows, final String attribute) { Collections.sort(rows, new Comparator<MapRow>() { @Override public int compare(MapRow o1, MapRow o2) { String value1 = o1.getString(attribute); String value2 = o2.getString(attribute); return value1.compareTo(value2); } }); return rows; }
java
private void updateDates(Task parentTask) { if (parentTask.hasChildTasks()) { Date plannedStartDate = null; Date plannedFinishDate = null; for (Task task : parentTask.getChildTasks()) { updateDates(task); plannedStartDate = DateHelper.min(plannedStartDate, task.getStart()); plannedFinishDate = DateHelper.max(plannedFinishDate, task.getFinish()); } parentTask.setStart(plannedStartDate); parentTask.setFinish(plannedFinishDate); } }
java
protected Date parseNonNullDate(String str, ParsePosition pos) { Date result = null; for (int index = 0; index < m_formats.length; index++) { result = m_formats[index].parse(str, pos); if (pos.getIndex() != 0) { break; } result = null; } return result; }
java
public void renumberIDs() { if (!isEmpty()) { Collections.sort(this); T firstEntity = get(0); int id = NumberHelper.getInt(firstEntity.getID()); if (id != 0) { id = 1; } for (T entity : this) { entity.setID(Integer.valueOf(id++)); } } }
java
public static Priority getInstance(int priority) { Priority result; if (priority >= LOWEST && priority <= DO_NOT_LEVEL && (priority % 100 == 0)) { result = VALUE[(priority / 100) - 1]; } else { result = new Priority(priority); } return (result); }
java
private void processFile(InputStream is) throws MPXJException { try { InputStreamReader reader = new InputStreamReader(is, CharsetHelper.UTF8); Tokenizer tk = new ReaderTokenizer(reader) { @Override protected boolean startQuotedIsValid(StringBuilder buffer) { return buffer.length() == 1 && buffer.charAt(0) == '<'; } }; tk.setDelimiter(DELIMITER); ArrayList<String> columns = new ArrayList<String>(); String nextTokenPrefix = null; while (tk.getType() != Tokenizer.TT_EOF) { columns.clear(); TableDefinition table = null; while (tk.nextToken() == Tokenizer.TT_WORD) { String token = tk.getToken(); if (columns.size() == 0) { if (token.charAt(0) == '#') { int index = token.lastIndexOf(':'); if (index != -1) { String headerToken; if (token.endsWith("-") || token.endsWith("=")) { headerToken = token; token = null; } else { headerToken = token.substring(0, index); token = token.substring(index + 1); } RowHeader header = new RowHeader(headerToken); table = m_tableDefinitions.get(header.getType()); columns.add(header.getID()); } } else { if (token.charAt(0) == 0) { processFileType(token); } } } if (table != null && token != null) { if (token.startsWith("<\"") && !token.endsWith("\">")) { nextTokenPrefix = token; } else { if (nextTokenPrefix != null) { token = nextTokenPrefix + DELIMITER + token; nextTokenPrefix = null; } columns.add(token); } } } if (table != null && columns.size() > 1) { // System.out.println(table.getName() + " " + columns.size()); // ColumnDefinition[] columnDefs = table.getColumns(); // int unknownIndex = 1; // for (int xx = 0; xx < columns.size(); xx++) // { // String x = columns.get(xx); // String columnName = xx < columnDefs.length ? (columnDefs[xx] == null ? "UNKNOWN" + (unknownIndex++) : columnDefs[xx].getName()) : "?"; // System.out.println(columnName + ": " + x + ", "); // } // System.out.println(); TextFileRow row = new TextFileRow(table, columns, m_epochDateFormat); List<Row> rows = m_tables.get(table.getName()); if (rows == null) { rows = new LinkedList<Row>(); m_tables.put(table.getName(), rows); } rows.add(row); } } } catch (Exception ex) { throw new MPXJException(MPXJException.READ_ERROR, ex); } }
java
private void processFileType(String token) throws MPXJException { String version = token.substring(2).split(" ")[0]; //System.out.println(version); Class<? extends AbstractFileFormat> fileFormatClass = FILE_VERSION_MAP.get(Integer.valueOf(version)); if (fileFormatClass == null) { throw new MPXJException("Unsupported PP file format version " + version); } try { AbstractFileFormat format = fileFormatClass.newInstance(); m_tableDefinitions = format.tableDefinitions(); m_epochDateFormat = format.epochDateFormat(); } catch (Exception ex) { throw new MPXJException("Failed to configure file format", ex); } }
java
private void processCalendars() throws SQLException { List<Row> rows = getTable("EXCEPTIONN"); Map<Integer, DayType> exceptionMap = m_reader.createExceptionTypeMap(rows); rows = getTable("WORK_PATTERN"); Map<Integer, Row> workPatternMap = m_reader.createWorkPatternMap(rows); rows = new LinkedList<Row>();// getTable("WORK_PATTERN_ASSIGNMENT"); // Need to generate an example Map<Integer, List<Row>> workPatternAssignmentMap = m_reader.createWorkPatternAssignmentMap(rows); rows = getTable("EXCEPTION_ASSIGNMENT"); Map<Integer, List<Row>> exceptionAssignmentMap = m_reader.createExceptionAssignmentMap(rows); rows = getTable("TIME_ENTRY"); Map<Integer, List<Row>> timeEntryMap = m_reader.createTimeEntryMap(rows); rows = getTable("CALENDAR"); Collections.sort(rows, CALENDAR_COMPARATOR); for (Row row : rows) { m_reader.processCalendar(row, workPatternMap, workPatternAssignmentMap, exceptionAssignmentMap, timeEntryMap, exceptionMap); } // // Update unique counters at this point as we will be generating // resource calendars, and will need to auto generate IDs // m_reader.getProject().getProjectConfig().updateUniqueCounters(); }
java
private List<Row> join(List<Row> leftRows, String leftColumn, String rightTable, List<Row> rightRows, String rightColumn) { List<Row> result = new LinkedList<Row>(); RowComparator leftComparator = new RowComparator(new String[] { leftColumn }); RowComparator rightComparator = new RowComparator(new String[] { rightColumn }); Collections.sort(leftRows, leftComparator); Collections.sort(rightRows, rightComparator); ListIterator<Row> rightIterator = rightRows.listIterator(); Row rightRow = rightIterator.hasNext() ? rightIterator.next() : null; for (Row leftRow : leftRows) { Integer leftValue = leftRow.getInteger(leftColumn); boolean match = false; while (rightRow != null) { Integer rightValue = rightRow.getInteger(rightColumn); int comparison = leftValue.compareTo(rightValue); if (comparison == 0) { match = true; break; } if (comparison < 0) { if (rightIterator.hasPrevious()) { rightRow = rightIterator.previous(); } break; } rightRow = rightIterator.next(); } if (match && rightRow != null) { Map<String, Object> newMap = new HashMap<String, Object>(((MapRow) leftRow).getMap()); for (Entry<String, Object> entry : ((MapRow) rightRow).getMap().entrySet()) { String key = entry.getKey(); if (newMap.containsKey(key)) { key = rightTable + "." + key; } newMap.put(key, entry.getValue()); } result.add(new MapRow(newMap)); } } return result; }
java
private List<Row> getTable(String name) { List<Row> result = m_tables.get(name); if (result == null) { result = Collections.emptyList(); } return result; }
java
private void readProjectProperties(Project ganttProject) { ProjectProperties mpxjProperties = m_projectFile.getProjectProperties(); mpxjProperties.setName(ganttProject.getName()); mpxjProperties.setCompany(ganttProject.getCompany()); mpxjProperties.setDefaultDurationUnits(TimeUnit.DAYS); String locale = ganttProject.getLocale(); if (locale == null) { locale = "en_US"; } m_localeDateFormat = DateFormat.getDateInstance(DateFormat.SHORT, new Locale(locale)); }
java
private void readCalendars(Project ganttProject) { m_mpxjCalendar = m_projectFile.addCalendar(); m_mpxjCalendar.setName(ProjectCalendar.DEFAULT_BASE_CALENDAR_NAME); Calendars gpCalendar = ganttProject.getCalendars(); setWorkingDays(m_mpxjCalendar, gpCalendar); setExceptions(m_mpxjCalendar, gpCalendar); m_eventManager.fireCalendarReadEvent(m_mpxjCalendar); }
java
private void setWorkingDays(ProjectCalendar mpxjCalendar, Calendars gpCalendar) { DayTypes dayTypes = gpCalendar.getDayTypes(); DefaultWeek defaultWeek = dayTypes.getDefaultWeek(); if (defaultWeek == null) { mpxjCalendar.setWorkingDay(Day.SUNDAY, false); mpxjCalendar.setWorkingDay(Day.MONDAY, true); mpxjCalendar.setWorkingDay(Day.TUESDAY, true); mpxjCalendar.setWorkingDay(Day.WEDNESDAY, true); mpxjCalendar.setWorkingDay(Day.THURSDAY, true); mpxjCalendar.setWorkingDay(Day.FRIDAY, true); mpxjCalendar.setWorkingDay(Day.SATURDAY, false); } else { mpxjCalendar.setWorkingDay(Day.MONDAY, isWorkingDay(defaultWeek.getMon())); mpxjCalendar.setWorkingDay(Day.TUESDAY, isWorkingDay(defaultWeek.getTue())); mpxjCalendar.setWorkingDay(Day.WEDNESDAY, isWorkingDay(defaultWeek.getWed())); mpxjCalendar.setWorkingDay(Day.THURSDAY, isWorkingDay(defaultWeek.getThu())); mpxjCalendar.setWorkingDay(Day.FRIDAY, isWorkingDay(defaultWeek.getFri())); mpxjCalendar.setWorkingDay(Day.SATURDAY, isWorkingDay(defaultWeek.getSat())); mpxjCalendar.setWorkingDay(Day.SUNDAY, isWorkingDay(defaultWeek.getSun())); } for (Day day : Day.values()) { if (mpxjCalendar.isWorkingDay(day)) { ProjectCalendarHours hours = mpxjCalendar.addCalendarHours(day); hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING); hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON); } } }
java
private void setExceptions(ProjectCalendar mpxjCalendar, Calendars gpCalendar) { List<net.sf.mpxj.ganttproject.schema.Date> dates = gpCalendar.getDate(); for (net.sf.mpxj.ganttproject.schema.Date date : dates) { addException(mpxjCalendar, date); } }
java
private void addException(ProjectCalendar mpxjCalendar, net.sf.mpxj.ganttproject.schema.Date date) { String year = date.getYear(); if (year == null || year.isEmpty()) { // In order to process recurring exceptions using MPXJ, we need a start and end date // to constrain the number of dates we generate. // May need to pre-process the tasks in order to calculate a start and finish date. // TODO: handle recurring exceptions } else { Calendar calendar = DateHelper.popCalendar(); calendar.set(Calendar.YEAR, Integer.parseInt(year)); calendar.set(Calendar.MONTH, NumberHelper.getInt(date.getMonth())); calendar.set(Calendar.DAY_OF_MONTH, NumberHelper.getInt(date.getDate())); Date exceptionDate = calendar.getTime(); DateHelper.pushCalendar(calendar); ProjectCalendarException exception = mpxjCalendar.addCalendarException(exceptionDate, exceptionDate); // TODO: not sure how NEUTRAL should be handled if ("WORKING_DAY".equals(date.getType())) { exception.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING); exception.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON); } } }
java
private void readResources(Project ganttProject) { Resources resources = ganttProject.getResources(); readResourceCustomPropertyDefinitions(resources); readRoleDefinitions(ganttProject); for (net.sf.mpxj.ganttproject.schema.Resource gpResource : resources.getResource()) { readResource(gpResource); } }
java
private void readResourceCustomPropertyDefinitions(Resources gpResources) { CustomField field = m_projectFile.getCustomFields().getCustomField(ResourceField.TEXT1); field.setAlias("Phone"); for (CustomPropertyDefinition definition : gpResources.getCustomPropertyDefinition()) { // // Find the next available field of the correct type. // String type = definition.getType(); FieldType fieldType = RESOURCE_PROPERTY_TYPES.get(type).getField(); // // If we have run out of fields of the right type, try using a text field. // if (fieldType == null) { fieldType = RESOURCE_PROPERTY_TYPES.get("text").getField(); } // // If we actually have a field available, set the alias to match // the name used in GanttProject. // if (fieldType != null) { field = m_projectFile.getCustomFields().getCustomField(fieldType); field.setAlias(definition.getName()); String defaultValue = definition.getDefaultValue(); if (defaultValue != null && defaultValue.isEmpty()) { defaultValue = null; } m_resourcePropertyDefinitions.put(definition.getId(), new Pair<FieldType, String>(fieldType, defaultValue)); } } }
java
private void readTaskCustomPropertyDefinitions(Tasks gpTasks) { for (Taskproperty definition : gpTasks.getTaskproperties().getTaskproperty()) { // // Ignore everything but custom values // if (!"custom".equals(definition.getType())) { continue; } // // Find the next available field of the correct type. // String type = definition.getValuetype(); FieldType fieldType = TASK_PROPERTY_TYPES.get(type).getField(); // // If we have run out of fields of the right type, try using a text field. // if (fieldType == null) { fieldType = TASK_PROPERTY_TYPES.get("text").getField(); } // // If we actually have a field available, set the alias to match // the name used in GanttProject. // if (fieldType != null) { CustomField field = m_projectFile.getCustomFields().getCustomField(fieldType); field.setAlias(definition.getName()); String defaultValue = definition.getDefaultvalue(); if (defaultValue != null && defaultValue.isEmpty()) { defaultValue = null; } m_taskPropertyDefinitions.put(definition.getId(), new Pair<FieldType, String>(fieldType, defaultValue)); } } }
java
private void readRoleDefinitions(Project gpProject) { m_roleDefinitions.put("Default:1", "project manager"); for (Roles roles : gpProject.getRoles()) { if ("Default".equals(roles.getRolesetName())) { continue; } for (Role role : roles.getRole()) { m_roleDefinitions.put(role.getId(), role.getName()); } } }
java
private void readResource(net.sf.mpxj.ganttproject.schema.Resource gpResource) { Resource mpxjResource = m_projectFile.addResource(); mpxjResource.setUniqueID(Integer.valueOf(NumberHelper.getInt(gpResource.getId()) + 1)); mpxjResource.setName(gpResource.getName()); mpxjResource.setEmailAddress(gpResource.getContacts()); mpxjResource.setText(1, gpResource.getPhone()); mpxjResource.setGroup(m_roleDefinitions.get(gpResource.getFunction())); net.sf.mpxj.ganttproject.schema.Rate gpRate = gpResource.getRate(); if (gpRate != null) { mpxjResource.setStandardRate(new Rate(gpRate.getValueAttribute(), TimeUnit.DAYS)); } readResourceCustomFields(gpResource, mpxjResource); m_eventManager.fireResourceReadEvent(mpxjResource); }
java
private void readResourceCustomFields(net.sf.mpxj.ganttproject.schema.Resource gpResource, Resource mpxjResource) { // // Populate custom field default values // Map<FieldType, Object> customFields = new HashMap<FieldType, Object>(); for (Pair<FieldType, String> definition : m_resourcePropertyDefinitions.values()) { customFields.put(definition.getFirst(), definition.getSecond()); } // // Update with custom field actual values // for (CustomResourceProperty property : gpResource.getCustomProperty()) { Pair<FieldType, String> definition = m_resourcePropertyDefinitions.get(property.getDefinitionId()); if (definition != null) { // // Retrieve the value. If it is empty, use the default. // String value = property.getValueAttribute(); if (value.isEmpty()) { value = null; } // // If we have a value,convert it to the correct type // if (value != null) { Object result; switch (definition.getFirst().getDataType()) { case NUMERIC: { if (value.indexOf('.') == -1) { result = Integer.valueOf(value); } else { result = Double.valueOf(value); } break; } case DATE: { try { result = m_localeDateFormat.parse(value); } catch (ParseException ex) { result = null; } break; } case BOOLEAN: { result = Boolean.valueOf(value.equals("true")); break; } default: { result = value; break; } } if (result != null) { customFields.put(definition.getFirst(), result); } } } } for (Map.Entry<FieldType, Object> item : customFields.entrySet()) { if (item.getValue() != null) { mpxjResource.set(item.getKey(), item.getValue()); } } }
java
private void readTaskCustomFields(net.sf.mpxj.ganttproject.schema.Task gpTask, Task mpxjTask) { // // Populate custom field default values // Map<FieldType, Object> customFields = new HashMap<FieldType, Object>(); for (Pair<FieldType, String> definition : m_taskPropertyDefinitions.values()) { customFields.put(definition.getFirst(), definition.getSecond()); } // // Update with custom field actual values // for (CustomTaskProperty property : gpTask.getCustomproperty()) { Pair<FieldType, String> definition = m_taskPropertyDefinitions.get(property.getTaskpropertyId()); if (definition != null) { // // Retrieve the value. If it is empty, use the default. // String value = property.getValueAttribute(); if (value.isEmpty()) { value = null; } // // If we have a value,convert it to the correct type // if (value != null) { Object result; switch (definition.getFirst().getDataType()) { case NUMERIC: { if (value.indexOf('.') == -1) { result = Integer.valueOf(value); } else { result = Double.valueOf(value); } break; } case DATE: { try { result = m_dateFormat.parse(value); } catch (ParseException ex) { result = null; } break; } case BOOLEAN: { result = Boolean.valueOf(value.equals("true")); break; } default: { result = value; break; } } if (result != null) { customFields.put(definition.getFirst(), result); } } } } for (Map.Entry<FieldType, Object> item : customFields.entrySet()) { if (item.getValue() != null) { mpxjTask.set(item.getKey(), item.getValue()); } } }
java
private void readTasks(Project gpProject) { Tasks tasks = gpProject.getTasks(); readTaskCustomPropertyDefinitions(tasks); for (net.sf.mpxj.ganttproject.schema.Task task : tasks.getTask()) { readTask(m_projectFile, task); } }
java
private void readTask(ChildTaskContainer mpxjParent, net.sf.mpxj.ganttproject.schema.Task gpTask) { Task mpxjTask = mpxjParent.addTask(); mpxjTask.setUniqueID(Integer.valueOf(NumberHelper.getInt(gpTask.getId()) + 1)); mpxjTask.setName(gpTask.getName()); mpxjTask.setPercentageComplete(gpTask.getComplete()); mpxjTask.setPriority(getPriority(gpTask.getPriority())); mpxjTask.setHyperlink(gpTask.getWebLink()); Duration duration = Duration.getInstance(NumberHelper.getDouble(gpTask.getDuration()), TimeUnit.DAYS); mpxjTask.setDuration(duration); if (duration.getDuration() == 0) { mpxjTask.setMilestone(true); } else { mpxjTask.setStart(gpTask.getStart()); mpxjTask.setFinish(m_mpxjCalendar.getDate(gpTask.getStart(), mpxjTask.getDuration(), false)); } mpxjTask.setConstraintDate(gpTask.getThirdDate()); if (mpxjTask.getConstraintDate() != null) { // TODO: you don't appear to be able to change this setting in GanttProject // task.getThirdDateConstraint() mpxjTask.setConstraintType(ConstraintType.START_NO_EARLIER_THAN); } readTaskCustomFields(gpTask, mpxjTask); m_eventManager.fireTaskReadEvent(mpxjTask); // TODO: read custom values // // Process child tasks // for (net.sf.mpxj.ganttproject.schema.Task childTask : gpTask.getTask()) { readTask(mpxjTask, childTask); } }
java
private Priority getPriority(Integer gpPriority) { int result; if (gpPriority == null) { result = Priority.MEDIUM; } else { int index = gpPriority.intValue(); if (index < 0 || index >= PRIORITY.length) { result = Priority.MEDIUM; } else { result = PRIORITY[index]; } } return Priority.getInstance(result); }
java
private void readRelationships(Project gpProject) { for (net.sf.mpxj.ganttproject.schema.Task gpTask : gpProject.getTasks().getTask()) { readRelationships(gpTask); } }
java
private void readRelationships(net.sf.mpxj.ganttproject.schema.Task gpTask) { for (Depend depend : gpTask.getDepend()) { Task task1 = m_projectFile.getTaskByUniqueID(Integer.valueOf(NumberHelper.getInt(gpTask.getId()) + 1)); Task task2 = m_projectFile.getTaskByUniqueID(Integer.valueOf(NumberHelper.getInt(depend.getId()) + 1)); if (task1 != null && task2 != null) { Duration lag = Duration.getInstance(NumberHelper.getInt(depend.getDifference()), TimeUnit.DAYS); Relation relation = task2.addPredecessor(task1, getRelationType(depend.getType()), lag); m_eventManager.fireRelationReadEvent(relation); } } }
java
private RelationType getRelationType(Integer gpType) { RelationType result = null; if (gpType != null) { int index = NumberHelper.getInt(gpType); if (index > 0 && index < RELATION.length) { result = RELATION[index]; } } if (result == null) { result = RelationType.FINISH_START; } return result; }
java
private void readResourceAssignments(Project gpProject) { Allocations allocations = gpProject.getAllocations(); if (allocations != null) { for (Allocation allocation : allocations.getAllocation()) { readResourceAssignment(allocation); } } }
java
private void readResourceAssignment(Allocation gpAllocation) { Integer taskID = Integer.valueOf(NumberHelper.getInt(gpAllocation.getTaskId()) + 1); Integer resourceID = Integer.valueOf(NumberHelper.getInt(gpAllocation.getResourceId()) + 1); Task task = m_projectFile.getTaskByUniqueID(taskID); Resource resource = m_projectFile.getResourceByUniqueID(resourceID); if (task != null && resource != null) { ResourceAssignment mpxjAssignment = task.addResourceAssignment(resource); mpxjAssignment.setUnits(gpAllocation.getLoad()); m_eventManager.fireAssignmentReadEvent(mpxjAssignment); } }
java
private void writeCustomFields() throws IOException { m_writer.writeStartList("custom_fields"); for (CustomField field : m_projectFile.getCustomFields()) { writeCustomField(field); } m_writer.writeEndList(); }
java
private void writeCustomField(CustomField field) throws IOException { if (field.getAlias() != null) { m_writer.writeStartObject(null); m_writer.writeNameValuePair("field_type_class", field.getFieldType().getFieldTypeClass().name().toLowerCase()); m_writer.writeNameValuePair("field_type", field.getFieldType().name().toLowerCase()); m_writer.writeNameValuePair("field_alias", field.getAlias()); m_writer.writeEndObject(); } }
java
private void writeProperties() throws IOException { writeAttributeTypes("property_types", ProjectField.values()); writeFields("property_values", m_projectFile.getProjectProperties(), ProjectField.values()); }
java
private void writeResources() throws IOException { writeAttributeTypes("resource_types", ResourceField.values()); m_writer.writeStartList("resources"); for (Resource resource : m_projectFile.getResources()) { writeFields(null, resource, ResourceField.values()); } m_writer.writeEndList(); }
java
private void writeTasks() throws IOException { writeAttributeTypes("task_types", TaskField.values()); m_writer.writeStartList("tasks"); for (Task task : m_projectFile.getChildTasks()) { writeTask(task); } m_writer.writeEndList(); }
java
private void writeTask(Task task) throws IOException { writeFields(null, task, TaskField.values()); for (Task child : task.getChildTasks()) { writeTask(child); } }
java
private void writeAssignments() throws IOException { writeAttributeTypes("assignment_types", AssignmentField.values()); m_writer.writeStartList("assignments"); for (ResourceAssignment assignment : m_projectFile.getResourceAssignments()) { writeFields(null, assignment, AssignmentField.values()); } m_writer.writeEndList(); }
java
private void writeAttributeTypes(String name, FieldType[] types) throws IOException { m_writer.writeStartObject(name); for (FieldType field : types) { m_writer.writeNameValuePair(field.name().toLowerCase(), field.getDataType().getValue()); } m_writer.writeEndObject(); }
java
private void writeFields(String objectName, FieldContainer container, FieldType[] fields) throws IOException { m_writer.writeStartObject(objectName); for (FieldType field : fields) { Object value = container.getCurrentValue(field); if (value != null) { writeField(field, value); } } m_writer.writeEndObject(); }
java
private void writeIntegerField(String fieldName, Object value) throws IOException { int val = ((Number) value).intValue(); if (val != 0) { m_writer.writeNameValuePair(fieldName, val); } }
java
private void writeDoubleField(String fieldName, Object value) throws IOException { double val = ((Number) value).doubleValue(); if (val != 0) { m_writer.writeNameValuePair(fieldName, val); } }
java
private void writeBooleanField(String fieldName, Object value) throws IOException { boolean val = ((Boolean) value).booleanValue(); if (val) { m_writer.writeNameValuePair(fieldName, val); } }
java
private void writeDurationField(String fieldName, Object value) throws IOException { if (value instanceof String) { m_writer.writeNameValuePair(fieldName + "_text", (String) value); } else { Duration val = (Duration) value; if (val.getDuration() != 0) { Duration minutes = val.convertUnits(TimeUnit.MINUTES, m_projectFile.getProjectProperties()); long seconds = (long) (minutes.getDuration() * 60.0); m_writer.writeNameValuePair(fieldName, seconds); } } }
java
private void writeDateField(String fieldName, Object value) throws IOException { if (value instanceof String) { m_writer.writeNameValuePair(fieldName + "_text", (String) value); } else { Date val = (Date) value; m_writer.writeNameValuePair(fieldName, val); } }
java
private void writeTimeUnitsField(String fieldName, Object value) throws IOException { TimeUnit val = (TimeUnit) value; if (val != m_projectFile.getProjectProperties().getDefaultDurationUnits()) { m_writer.writeNameValuePair(fieldName, val.toString()); } }
java
private void writePriorityField(String fieldName, Object value) throws IOException { m_writer.writeNameValuePair(fieldName, ((Priority) value).getValue()); }
java
private void writeMap(String fieldName, Object value) throws IOException { @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) value; m_writer.writeStartObject(fieldName); for (Map.Entry<String, Object> entry : map.entrySet()) { Object entryValue = entry.getValue(); if (entryValue != null) { DataType type = TYPE_MAP.get(entryValue.getClass().getName()); if (type == null) { type = DataType.STRING; entryValue = entryValue.toString(); } writeField(entry.getKey(), type, entryValue); } } m_writer.writeEndObject(); }
java
private void writeStringField(String fieldName, Object value) throws IOException { String val = value.toString(); if (!val.isEmpty()) { m_writer.writeNameValuePair(fieldName, val); } }
java
private void writeRelationList(String fieldName, Object value) throws IOException { @SuppressWarnings("unchecked") List<Relation> list = (List<Relation>) value; if (!list.isEmpty()) { m_writer.writeStartList(fieldName); for (Relation relation : list) { m_writer.writeStartObject(null); writeIntegerField("task_unique_id", relation.getTargetTask().getUniqueID()); writeDurationField("lag", relation.getLag()); writeStringField("type", relation.getType()); m_writer.writeEndObject(); } m_writer.writeEndList(); } }
java
public static ResourceField getMpxjField(int value) { ResourceField result = null; if (value >= 0 && value < MPX_MPXJ_ARRAY.length) { result = MPX_MPXJ_ARRAY[value]; } return (result); }
java
public boolean evaluate(FieldContainer container, Map<GenericCriteriaPrompt, Object> promptValues) { boolean result = true; if (m_criteria != null) { result = m_criteria.evaluate(container, promptValues); // // If this row has failed, but it is a summary row, and we are // including related summary rows, then we need to recursively test // its children // if (!result && m_showRelatedSummaryRows && container instanceof Task) { for (Task task : ((Task) container).getChildTasks()) { if (evaluate(task, promptValues)) { result = true; break; } } } } return (result); }
java
public void parseRawValue(String value) { int valueIndex = 0; int elementIndex = 0; m_elements.clear(); while (valueIndex < value.length() && elementIndex < m_elements.size()) { int elementLength = m_lengths.get(elementIndex).intValue(); if (elementIndex > 0) { m_elements.add(m_separators.get(elementIndex - 1)); } int endIndex = valueIndex + elementLength; if (endIndex > value.length()) { endIndex = value.length(); } String element = value.substring(valueIndex, endIndex); m_elements.add(element); valueIndex += elementLength; elementIndex++; } }
java
public String getFormattedParentValue() { String result = null; if (m_elements.size() > 2) { result = joinElements(m_elements.size() - 2); } return result; }
java
private String joinElements(int length) { StringBuilder sb = new StringBuilder(); for (int index = 0; index < length; index++) { sb.append(m_elements.get(index)); } return sb.toString(); }
java
private void addTasks(MpxjTreeNode parentNode, ChildTaskContainer parent) { for (Task task : parent.getChildTasks()) { final Task t = task; MpxjTreeNode childNode = new MpxjTreeNode(task, TASK_EXCLUDED_METHODS) { @Override public String toString() { return t.getName(); } }; parentNode.add(childNode); addTasks(childNode, task); } }
java
private void addResources(MpxjTreeNode parentNode, ProjectFile file) { for (Resource resource : file.getResources()) { final Resource r = resource; MpxjTreeNode childNode = new MpxjTreeNode(resource) { @Override public String toString() { return r.getName(); } }; parentNode.add(childNode); } }
java
private void addCalendars(MpxjTreeNode parentNode, ProjectFile file) { for (ProjectCalendar calendar : file.getCalendars()) { addCalendar(parentNode, calendar); } }
java
private void addCalendar(MpxjTreeNode parentNode, final ProjectCalendar calendar) { MpxjTreeNode calendarNode = new MpxjTreeNode(calendar, CALENDAR_EXCLUDED_METHODS) { @Override public String toString() { return calendar.getName(); } }; parentNode.add(calendarNode); MpxjTreeNode daysFolder = new MpxjTreeNode("Days"); calendarNode.add(daysFolder); for (Day day : Day.values()) { addCalendarDay(daysFolder, calendar, day); } MpxjTreeNode exceptionsFolder = new MpxjTreeNode("Exceptions"); calendarNode.add(exceptionsFolder); for (ProjectCalendarException exception : calendar.getCalendarExceptions()) { addCalendarException(exceptionsFolder, exception); } }
java
private void addCalendarDay(MpxjTreeNode parentNode, ProjectCalendar calendar, final Day day) { MpxjTreeNode dayNode = new MpxjTreeNode(day) { @Override public String toString() { return day.name(); } }; parentNode.add(dayNode); addHours(dayNode, calendar.getHours(day)); }
java
private void addHours(MpxjTreeNode parentNode, ProjectCalendarDateRanges hours) { for (DateRange range : hours) { final DateRange r = range; MpxjTreeNode rangeNode = new MpxjTreeNode(range) { @Override public String toString() { return m_timeFormat.format(r.getStart()) + " - " + m_timeFormat.format(r.getEnd()); } }; parentNode.add(rangeNode); } }
java
private void addCalendarException(MpxjTreeNode parentNode, final ProjectCalendarException exception) { MpxjTreeNode exceptionNode = new MpxjTreeNode(exception, CALENDAR_EXCEPTION_EXCLUDED_METHODS) { @Override public String toString() { return m_dateFormat.format(exception.getFromDate()); } }; parentNode.add(exceptionNode); addHours(exceptionNode, exception); }
java
private void addGroups(MpxjTreeNode parentNode, ProjectFile file) { for (Group group : file.getGroups()) { final Group g = group; MpxjTreeNode childNode = new MpxjTreeNode(group) { @Override public String toString() { return g.getName(); } }; parentNode.add(childNode); } }
java
private void addCustomFields(MpxjTreeNode parentNode, ProjectFile file) { for (CustomField field : file.getCustomFields()) { final CustomField c = field; MpxjTreeNode childNode = new MpxjTreeNode(field) { @Override public String toString() { FieldType type = c.getFieldType(); return type == null ? "(unknown)" : type.getFieldTypeClass() + "." + type.toString(); } }; parentNode.add(childNode); } }
java
private void addViews(MpxjTreeNode parentNode, ProjectFile file) { for (View view : file.getViews()) { final View v = view; MpxjTreeNode childNode = new MpxjTreeNode(view) { @Override public String toString() { return v.getName(); } }; parentNode.add(childNode); } }
java
private void addTables(MpxjTreeNode parentNode, ProjectFile file) { for (Table table : file.getTables()) { final Table t = table; MpxjTreeNode childNode = new MpxjTreeNode(table, TABLE_EXCLUDED_METHODS) { @Override public String toString() { return t.getName(); } }; parentNode.add(childNode); addColumns(childNode, table); } }
java
private void addColumns(MpxjTreeNode parentNode, Table table) { for (Column column : table.getColumns()) { final Column c = column; MpxjTreeNode childNode = new MpxjTreeNode(column) { @Override public String toString() { return c.getTitle(); } }; parentNode.add(childNode); } }
java
private void addFilters(MpxjTreeNode parentNode, List<Filter> filters) { for (Filter field : filters) { final Filter f = field; MpxjTreeNode childNode = new MpxjTreeNode(field) { @Override public String toString() { return f.getName(); } }; parentNode.add(childNode); } }
java
private void addAssignments(MpxjTreeNode parentNode, ProjectFile file) { for (ResourceAssignment assignment : file.getResourceAssignments()) { final ResourceAssignment a = assignment; MpxjTreeNode childNode = new MpxjTreeNode(a) { @Override public String toString() { Resource resource = a.getResource(); String resourceName = resource == null ? "(unknown resource)" : resource.getName(); Task task = a.getTask(); String taskName = task == null ? "(unknown task)" : task.getName(); return resourceName + "->" + taskName; } }; parentNode.add(childNode); } }
java
public void saveFile(File file, String type) { try { Class<? extends ProjectWriter> fileClass = WRITER_MAP.get(type); if (fileClass == null) { throw new IllegalArgumentException("Cannot write files of type: " + type); } ProjectWriter writer = fileClass.newInstance(); writer.write(m_projectFile, file); } catch (Exception ex) { throw new RuntimeException(ex); } }
java
private static Set<String> excludedMethods(String... methodNames) { Set<String> set = new HashSet<String>(MpxjTreeNode.DEFAULT_EXCLUDED_METHODS); set.addAll(Arrays.asList(methodNames)); return set; }
java
@Override public void close() throws IOException { long skippedLast = 0; if (m_remaining > 0) { skippedLast = skip(m_remaining); while (m_remaining > 0 && skippedLast > 0) { skippedLast = skip(m_remaining); } } }
java
public static void setLocale(ProjectProperties properties, Locale locale) { properties.setMpxDelimiter(LocaleData.getChar(locale, LocaleData.FILE_DELIMITER)); properties.setMpxProgramName(LocaleData.getString(locale, LocaleData.PROGRAM_NAME)); properties.setMpxCodePage((CodePage) LocaleData.getObject(locale, LocaleData.CODE_PAGE)); properties.setCurrencySymbol(LocaleData.getString(locale, LocaleData.CURRENCY_SYMBOL)); properties.setSymbolPosition((CurrencySymbolPosition) LocaleData.getObject(locale, LocaleData.CURRENCY_SYMBOL_POSITION)); properties.setCurrencyDigits(LocaleData.getInteger(locale, LocaleData.CURRENCY_DIGITS)); properties.setThousandsSeparator(LocaleData.getChar(locale, LocaleData.CURRENCY_THOUSANDS_SEPARATOR)); properties.setDecimalSeparator(LocaleData.getChar(locale, LocaleData.CURRENCY_DECIMAL_SEPARATOR)); properties.setDateOrder((DateOrder) LocaleData.getObject(locale, LocaleData.DATE_ORDER)); properties.setTimeFormat((ProjectTimeFormat) LocaleData.getObject(locale, LocaleData.TIME_FORMAT)); properties.setDefaultStartTime(DateHelper.getTimeFromMinutesPastMidnight(LocaleData.getInteger(locale, LocaleData.DEFAULT_START_TIME))); properties.setDateSeparator(LocaleData.getChar(locale, LocaleData.DATE_SEPARATOR)); properties.setTimeSeparator(LocaleData.getChar(locale, LocaleData.TIME_SEPARATOR)); properties.setAMText(LocaleData.getString(locale, LocaleData.AM_TEXT)); properties.setPMText(LocaleData.getString(locale, LocaleData.PM_TEXT)); properties.setDateFormat((ProjectDateFormat) LocaleData.getObject(locale, LocaleData.DATE_FORMAT)); properties.setBarTextDateFormat((ProjectDateFormat) LocaleData.getObject(locale, LocaleData.DATE_FORMAT)); }
java
public String getTitle(Locale locale) { String result = null; if (m_title != null) { result = m_title; } else { if (m_fieldType != null) { result = m_project.getCustomFields().getCustomField(m_fieldType).getAlias(); if (result == null) { result = m_fieldType.getName(locale); } } } return (result); }
java
public static AccrueType getInstance(String type, Locale locale) { AccrueType result = null; String[] typeNames = LocaleData.getStringArray(locale, LocaleData.ACCRUE_TYPES); for (int loop = 0; loop < typeNames.length; loop++) { if (typeNames[loop].equalsIgnoreCase(type) == true) { result = AccrueType.getInstance(loop + 1); break; } } if (result == null) { result = AccrueType.PRORATED; } return (result); }
java
public void process(Connection connection, String directory) throws Exception { connection.setAutoCommit(true); // // Retrieve meta data about the connection // DatabaseMetaData dmd = connection.getMetaData(); String[] types = { "TABLE" }; FileWriter fw = new FileWriter(directory); PrintWriter pw = new PrintWriter(fw); pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); pw.println(); pw.println("<database>"); ResultSet tables = dmd.getTables(null, null, null, types); while (tables.next() == true) { processTable(pw, connection, tables.getString("TABLE_NAME")); } pw.println("</database>"); pw.close(); tables.close(); }
java
private String escapeText(StringBuilder sb, String text) { int length = text.length(); char c; sb.setLength(0); for (int loop = 0; loop < length; loop++) { c = text.charAt(loop); switch (c) { case '<': { sb.append("&lt;"); break; } case '>': { sb.append("&gt;"); break; } case '&': { sb.append("&amp;"); break; } default: { if (validXMLCharacter(c)) { if (c > 127) { sb.append("&#" + (int) c + ";"); } else { sb.append(c); } } break; } } } return (sb.toString()); }
java
public static String rset(String input, int width) { String result; // result to return StringBuilder pad = new StringBuilder(); if (input == null) { for (int i = 0; i < width - 1; i++) { pad.append(' '); // put blanks into buffer } result = " " + pad; // one short to use + overload } else { if (input.length() >= width) { result = input.substring(0, width); // when input is too long, truncate } else { int padLength = width - input.length(); // number of blanks to add for (int i = 0; i < padLength; i++) { pad.append(' '); // actually put blanks into buffer } result = pad + input; // concatenate } } return result; }
java
public static String workDays(ProjectCalendar input) { StringBuilder result = new StringBuilder(); DayType[] test = input.getDays(); // get the array from MPXJ ProjectCalendar for (DayType i : test) { // go through every day in the given array if (i == DayType.NON_WORKING) { result.append("N"); // only put N for non-working day of the week } else { result.append("Y"); // Assume WORKING day unless NON_WORKING } } return result.toString(); // According to USACE specs., exceptions will be specified in HOLI records }
java
public static File writeStreamToTempFile(InputStream inputStream, String tempFileSuffix) throws IOException { FileOutputStream outputStream = null; try { File file = File.createTempFile("mpxj", tempFileSuffix); outputStream = new FileOutputStream(file); byte[] buffer = new byte[1024]; while (true) { int bytesRead = inputStream.read(buffer); if (bytesRead == -1) { break; } outputStream.write(buffer, 0, bytesRead); } return file; } finally { if (outputStream != null) { outputStream.close(); } } }
java
public static Record getRecord(String text) { Record root; try { root = new Record(text); } // // I've come across invalid calendar data in an otherwise fine Primavera // database belonging to a customer. We deal with this gracefully here // rather than propagating an exception. // catch (Exception ex) { root = null; } return root; }
java
public Record getChild(String key) { Record result = null; if (key != null) { for (Record record : m_records) { if (key.equals(record.getField())) { result = record; break; } } } return result; }
java
private int getClosingParenthesisPosition(String text, int opening) { if (text.charAt(opening) != '(') { return -1; } int count = 0; for (int i = opening; i < text.length(); i++) { char c = text.charAt(i); switch (c) { case '(': { ++count; break; } case ')': { --count; if (count == 0) { return i; } break; } } } return -1; }
java
public static final long getLong(byte[] data, int offset) { if (data.length != 8) { throw new UnexpectedStructureException(); } long result = 0; int i = offset; for (int shiftBy = 0; shiftBy < 64; shiftBy += 8) { result |= ((long) (data[i] & 0xff)) << shiftBy; ++i; } return result; }
java
public static final TimeUnit getTimeUnit(int value) { TimeUnit result = null; switch (value) { case 1: { // Appears to mean "use the document format" result = TimeUnit.ELAPSED_DAYS; break; } case 2: { result = TimeUnit.HOURS; break; } case 4: { result = TimeUnit.DAYS; break; } case 6: { result = TimeUnit.WEEKS; break; } case 8: case 10: { result = TimeUnit.MONTHS; break; } case 12: { result = TimeUnit.YEARS; break; } default: { break; } } return result; }
java
public static int skipToNextMatchingShort(byte[] buffer, int offset, int value) { int nextOffset = offset; while (getShort(buffer, nextOffset) != value) { ++nextOffset; } nextOffset += 2; return nextOffset; }
java
public static final String hexdump(byte[] buffer, int offset, int length, boolean ascii, int columns, String prefix) { StringBuilder sb = new StringBuilder(); if (buffer != null) { int index = offset; DecimalFormat df = new DecimalFormat("00000"); while (index < (offset + length)) { if (index + columns > (offset + length)) { columns = (offset + length) - index; } sb.append(prefix); sb.append(df.format(index - offset)); sb.append(":"); sb.append(hexdump(buffer, index, columns, ascii)); sb.append('\n'); index += columns; } } return (sb.toString()); }
java
public void generateWBS(Task parent) { String wbs; if (parent == null) { if (NumberHelper.getInt(getUniqueID()) == 0) { wbs = "0"; } else { wbs = Integer.toString(getParentFile().getChildTasks().size() + 1); } } else { wbs = parent.getWBS(); // // Apparently I added the next lines to support MPX files generated by Artemis, back in 2005 // Unfortunately I have no test data which exercises this code, and it now breaks // otherwise valid WBS values read (in this case) from XER files. So it's commented out // until someone complains about their 2005-era Artemis MPX files not working! // // int index = wbs.lastIndexOf(".0"); // if (index != -1) // { // wbs = wbs.substring(0, index); // } int childTaskCount = parent.getChildTasks().size() + 1; if (wbs.equals("0")) { wbs = Integer.toString(childTaskCount); } else { wbs += ("." + childTaskCount); } } setWBS(wbs); }
java
public void generateOutlineNumber(Task parent) { String outline; if (parent == null) { if (NumberHelper.getInt(getUniqueID()) == 0) { outline = "0"; } else { outline = Integer.toString(getParentFile().getChildTasks().size() + 1); } } else { outline = parent.getOutlineNumber(); int index = outline.lastIndexOf(".0"); if (index != -1) { outline = outline.substring(0, index); } int childTaskCount = parent.getChildTasks().size() + 1; if (outline.equals("0")) { outline = Integer.toString(childTaskCount); } else { outline += ("." + childTaskCount); } } setOutlineNumber(outline); }
java
@Override public Task addTask() { ProjectFile parent = getParentFile(); Task task = new Task(parent, this); m_children.add(task); parent.getTasks().add(task); setSummary(true); return (task); }
java
public void addChildTask(Task child, int childOutlineLevel) { int outlineLevel = NumberHelper.getInt(getOutlineLevel()); if ((outlineLevel + 1) == childOutlineLevel) { m_children.add(child); setSummary(true); } else { if (m_children.isEmpty() == false) { (m_children.get(m_children.size() - 1)).addChildTask(child, childOutlineLevel); } } }
java
public void addChildTask(Task child) { child.m_parent = this; m_children.add(child); setSummary(true); if (getParentFile().getProjectConfig().getAutoOutlineLevel() == true) { child.setOutlineLevel(Integer.valueOf(NumberHelper.getInt(getOutlineLevel()) + 1)); } }
java
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)); } }
java
public void removeChildTask(Task child) { if (m_children.remove(child)) { child.m_parent = null; } setSummary(!m_children.isEmpty()); }
java
public ResourceAssignment addResourceAssignment(Resource resource) { ResourceAssignment assignment = getExistingResourceAssignment(resource); if (assignment == null) { assignment = new ResourceAssignment(getParentFile(), this); m_assignments.add(assignment); getParentFile().getResourceAssignments().add(assignment); assignment.setTaskUniqueID(getUniqueID()); assignment.setWork(getDuration()); assignment.setUnits(ResourceAssignment.DEFAULT_UNITS); if (resource != null) { assignment.setResourceUniqueID(resource.getUniqueID()); resource.addResourceAssignment(assignment); } } return (assignment); }
java
public void addResourceAssignment(ResourceAssignment assignment) { if (getExistingResourceAssignment(assignment.getResource()) == null) { m_assignments.add(assignment); getParentFile().getResourceAssignments().add(assignment); Resource resource = assignment.getResource(); if (resource != null) { resource.addResourceAssignment(assignment); } } }
java
private ResourceAssignment getExistingResourceAssignment(Resource resource) { ResourceAssignment assignment = null; Integer resourceUniqueID = null; if (resource != null) { Iterator<ResourceAssignment> iter = m_assignments.iterator(); resourceUniqueID = resource.getUniqueID(); while (iter.hasNext() == true) { assignment = iter.next(); Integer uniqueID = assignment.getResourceUniqueID(); if (uniqueID != null && uniqueID.equals(resourceUniqueID) == true) { break; } assignment = null; } } return assignment; }
java
@SuppressWarnings("unchecked") public Relation addPredecessor(Task targetTask, RelationType type, Duration lag) { // // Ensure that we have a valid lag duration // if (lag == null) { lag = Duration.getInstance(0, TimeUnit.DAYS); } // // Retrieve the list of predecessors // List<Relation> predecessorList = (List<Relation>) getCachedValue(TaskField.PREDECESSORS); // // Ensure that there is only one predecessor relationship between // these two tasks. // Relation predecessorRelation = null; Iterator<Relation> iter = predecessorList.iterator(); while (iter.hasNext() == true) { predecessorRelation = iter.next(); if (predecessorRelation.getTargetTask() == targetTask) { if (predecessorRelation.getType() != type || predecessorRelation.getLag().compareTo(lag) != 0) { predecessorRelation = null; } break; } predecessorRelation = null; } // // If necessary, create a new predecessor relationship // if (predecessorRelation == null) { predecessorRelation = new Relation(this, targetTask, type, lag); predecessorList.add(predecessorRelation); } // // Retrieve the list of successors // List<Relation> successorList = (List<Relation>) targetTask.getCachedValue(TaskField.SUCCESSORS); // // Ensure that there is only one successor relationship between // these two tasks. // Relation successorRelation = null; iter = successorList.iterator(); while (iter.hasNext() == true) { successorRelation = iter.next(); if (successorRelation.getTargetTask() == this) { if (successorRelation.getType() != type || successorRelation.getLag().compareTo(lag) != 0) { successorRelation = null; } break; } successorRelation = null; } // // If necessary, create a new successor relationship // if (successorRelation == null) { successorRelation = new Relation(targetTask, this, type, lag); successorList.add(successorRelation); } return (predecessorRelation); }
java
@Override public void setID(Integer val) { ProjectFile parent = getParentFile(); Integer previous = getID(); if (previous != null) { parent.getTasks().unmapID(previous); } parent.getTasks().mapID(val, this); set(TaskField.ID, val); }
java
public Duration getBaselineDuration() { Object result = getCachedValue(TaskField.BASELINE_DURATION); if (result == null) { result = getCachedValue(TaskField.BASELINE_ESTIMATED_DURATION); } if (!(result instanceof Duration)) { result = null; } return (Duration) result; }
java
public String getBaselineDurationText() { Object result = getCachedValue(TaskField.BASELINE_DURATION); if (result == null) { result = getCachedValue(TaskField.BASELINE_ESTIMATED_DURATION); } if (!(result instanceof String)) { result = null; } return (String) result; }
java