private void processApply(Node operation) throws ParserConfigurationException, TransformerConfigurationException { List<Node> targets = getChildNodes(operation, "target"); List<Node> scripts = getChildNodes(operation, "script"); for (int t = 0; t < targets.size(); t++) { String path = absolutePath(targets.get(t).getTextContent()); NodeList[] operations = new NodeList[scripts.size()]; for (int s = 0; s < scripts.size(); s++) { operations[s] = scripts.get(s).getChildNodes(); } apply(path, operations); } }
private NodeList getValueNodes(Node operation) { List<Node> valueNL = getChildNodes(operation, "value"); if (valueNL.isEmpty()) { return null; } return valueNL.get(0).getChildNodes(); }
public int getLength() { int length = 0; for (int i = 0; i < nodeLists.size(); i++) { NodeList nl = (NodeList) nodeLists.get(i); length += nl.getLength(); } return length; }
/** * @param sourceFile File to read from * @return List of String objects with the shas */ public static FileRequestFileContent readRequestFile(final File sourceFile) { if (!sourceFile.isFile() || !(sourceFile.length() > 0)) { return null; } Document d = null; try { d = XMLTools.parseXmlFile(sourceFile.getPath()); } catch (final Throwable t) { logger.log(Level.SEVERE, "Exception in readRequestFile, during XML parsing", t); return null; } if (d == null) { logger.log(Level.SEVERE, "Could'nt parse the request file"); return null; } final Element rootNode = d.getDocumentElement(); if (rootNode.getTagName().equals(TAG_FrostFileRequestFile) == false) { logger.severe( "Error: xml request file does not contain the root tag '" + TAG_FrostFileRequestFile + "'"); return null; } final String timeStampStr = XMLTools.getChildElementsTextValue(rootNode, TAG_timestamp); if (timeStampStr == null) { logger.severe("Error: xml file does not contain the tag '" + TAG_timestamp + "'"); return null; } final long timestamp = Long.parseLong(timeStampStr); final List<Element> nodelist = XMLTools.getChildElementsByTagName(rootNode, TAG_shaList); if (nodelist.size() != 1) { logger.severe("Error: xml request files must contain only one element '" + TAG_shaList + "'"); return null; } final Element rootShaNode = nodelist.get(0); final List<String> shaList = new LinkedList<String>(); final List<Element> xmlKeys = XMLTools.getChildElementsByTagName(rootShaNode, TAG_sha); for (final Element el : xmlKeys) { final Text txtname = (Text) el.getFirstChild(); if (txtname == null) { continue; } final String sha = txtname.getData(); shaList.add(sha); } final FileRequestFileContent content = new FileRequestFileContent(timestamp, shaList); return content; }
private void processXml(Node operation) throws ParserConfigurationException, TransformerConfigurationException { List<Node> targets = getChildNodes(operation, "target"); List<Node> appendOpNodes = getChildNodes(operation, "append"); List<Node> setOpNodes = getChildNodes(operation, "set"); List<Node> replaceOpNodes = getChildNodes(operation, "replace"); List<Node> removeOpNodes = getChildNodes(operation, "remove"); if (targets.isEmpty()) { return; } for (int t = 0; t < targets.size(); t++) { File target = new File(absolutePath(targets.get(t).getTextContent())); if (!target.exists()) { Utils.onError(new Error.FileNotFound(target.getPath())); return; } DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = null; try { doc = db.parse(target); } catch (Exception ex) { Utils.onError(new Error.FileParse(target.getPath())); return; } for (int i = 0; i < removeOpNodes.size(); i++) removeXmlEntry(doc, removeOpNodes.get(i)); for (int i = 0; i < replaceOpNodes.size(); i++) replaceXmlEntry(doc, replaceOpNodes.get(i)); for (int i = 0; i < setOpNodes.size(); i++) setXmlEntry(doc, setOpNodes.get(i)); for (int i = 0; i < appendOpNodes.size(); i++) appendXmlEntry(doc, appendOpNodes.get(i)); try { OutputFormat format = new OutputFormat(doc); format.setOmitXMLDeclaration(true); format.setLineWidth(65); format.setIndenting(true); format.setIndent(4); Writer out = new FileWriter(target); XMLSerializer serializer = new XMLSerializer(out, format); serializer.serialize(doc); } catch (IOException e) { Utils.onError(new Error.WriteXmlConfig(target.getPath())); } } }
public Node item(int index) { int relativeIndex = index; for (int i = 0; i < nodeLists.size(); i++) { NodeList nl = (NodeList) nodeLists.get(i); if (relativeIndex < nl.getLength()) { return nl.item(relativeIndex); } relativeIndex -= nl.getLength(); } return null; }
public static void echo(List annotationAttrs) { if (annotationAttrs.size() > 0) { for (int i = 0; i < annotationAttrs.size(); i++) { String[] annotationAttr = (String[]) annotationAttrs.get(i); System.out.println(annotationAttr[0]); System.out.println(annotationAttr[1]); System.out.println(annotationAttr[2]); } } }
private static void showDocument(Document doc) { StringBuffer content = new StringBuffer(); Node node = doc.getChildNodes().item(0); ApplicationNode appNode = new ApplicationNode(node); content.append("Application \n"); List<ClassNode> classes = appNode.getClasses(); for (int i = 0; i < classes.size(); i++) { ClassNode classNode = classes.get(i); content.append(SPACE + "Class: " + classNode.getName() + " \n"); List<MethodNode> methods = classNode.getMethods(); for (int j = 0; j < methods.size(); j++) { MethodNode methodNode = methods.get(j); content.append(SPACE + SPACE + "Method: " + methodNode.getName() + " \n"); } } System.out.println(content.toString()); }
@Override public void readPageFromXML(Element element) { NodeList nodes = element.getElementsByTagName("tooltype"); if (nodes != null) type = nodes.item(0).getTextContent(); nodes = element.getElementsByTagName("recipe"); if (nodes != null) { String recipe = nodes.item(0).getTextContent(); icons = MantleClientRegistry.getRecipeIcons(recipe); if (type.equals("travelmulti")) { List<ItemStack[]> stacks = new LinkedList<ItemStack[]>(); List<String> tools = new LinkedList<String>(); String[] suffixes = new String[] {"goggles", "vest", "wings", "boots", "glove", "belt"}; for (String suffix : suffixes) { ItemStack[] icons2 = MantleClientRegistry.getRecipeIcons(nodes.item(0).getTextContent() + suffix); if (icons2 != null) { stacks.add(icons2); tools.add(suffix); } } iconsMulti = new ItemStack[stacks.size()][]; toolMulti = new ItemStack[stacks.size()]; for (int i = 0; i < stacks.size(); i++) { iconsMulti[i] = stacks.get(i); toolMulti[i] = MantleClientRegistry.getManualIcon("travel" + tools.get(i)); } icons = iconsMulti[0]; lastUpdate = System.currentTimeMillis(); counter = 0; } } }
private void processCopy(Node operation) { List<Node> fromNode = getChildNodes(operation, "from"); List<Node> toNode = getChildNodes(operation, "to"); if (fromNode.isEmpty() || toNode.isEmpty()) { return; } String path = fromNode.get(0).getTextContent(); String fromPath = (new File(path).isAbsolute()) ? path : absolutePath(path); String toPath = absolutePath(toNode.get(0).getTextContent()); Boolean copyContents = fromPath.endsWith(File.separator + "*"); File from = new File((copyContents) ? fromPath.substring(0, fromPath.length() - 2) : fromPath); File to = new File(toPath); if (!from.exists()) { Utils.onError(new Error.FileNotFound(from.getPath())); return; } try { if (copyContents) { FileUtils.forceMkdir(to); FileUtils.copyDirectory(from, to); } else if (from.isDirectory()) { FileUtils.forceMkdir(to); FileUtils.copyDirectoryToDirectory(from, to); } else { if (to.isDirectory()) { FileUtils.forceMkdir(to); FileUtils.copyFileToDirectory(from, to); } else { File toDir = new File(Utils.getParentDir(to)); FileUtils.forceMkdir(toDir); FileUtils.copyFile(from, to); } } } catch (IOException ex) { Utils.onError(new Error.FileCopy(from.getPath(), to.getPath())); } }
public void getFilesFromFolder(List filesAndFolders, String savePath) { // create a File object for the parent directory File downloadsDirectory = new File(savePath); // create the folder if needed. downloadsDirectory.mkdir(); for (int i = 0; i < filesAndFolders.size(); i++) { Object links = filesAndFolders.get(i); List linksArray = (ArrayList) links; if (i == 0) { for (int j = 0; j < linksArray.size(); j += 2) { // We've got an array of file urls so download each one to a directory with the folder // name String fileURL = linksArray.get(j).toString(); String fileName = linksArray.get(j + 1).toString(); downloadFile(fileURL, savePath, fileName); progress++; Message msg = mHandler.obtainMessage(); msg.arg1 = progress; mHandler.sendMessage(msg); } } else if (i == 1) { // we've got an array of folders so recurse down the levels, extracting subfolders and files // until we've downloaded everything. for (int j = 0; j < linksArray.size(); j += 2) { String folderURL = linksArray.get(j).toString(); String folderName = linksArray.get(j + 1).toString(); String page = getData(folderURL); List newFilesAndFolders = parsePage(page); String dlDirPath = savePath + folderName + "/"; getFilesFromFolder(newFilesAndFolders, dlDirPath); } } } }
private static final Bone buildBone( byte index, Map bone_children_map, String bone_name, Map name_to_bone_map) { List children_list = (List) bone_children_map.get(bone_name); Bone[] children_array; if (children_list != null) { children_array = new Bone[children_list.size()]; for (int i = 0; i < children_array.length; i++) { String child_name = (String) children_list.get(i); Bone child_bone = buildBone(index, bone_children_map, child_name, name_to_bone_map); children_array[i] = child_bone; index = (byte) (child_bone.getIndex() + 1); } } else children_array = new Bone[0]; Bone bone = new Bone(bone_name, index, children_array); name_to_bone_map.put(bone_name, bone); return bone; }
/** Given an input string, level, and optionally a tag length, find a matching prefix. */ private PrefixMatch findPrefixMatch( String input, TagLengthList tagLength, LevelTypeList level_type) { List<PrefixMatch> match_list = new ArrayList<PrefixMatch>(); PrefixTree<PrefixMatch> tree = prefix_tree_map.get(level_type); assert tree != null; List<PrefixMatch> list = tree.search(input); if (!list.isEmpty()) { if (tagLength == null) match_list.addAll(list); else { for (PrefixMatch match : list) if (match.getScheme().getTagLength() == tagLength) match_list.add(match); } } if (match_list.isEmpty()) throw new TDTException("No schemes or levels matched the input value"); else if (match_list.size() > 1) throw new TDTException("More than one scheme/level matched the input value"); else return match_list.get(0); }
private NodeList findNodes(Document doc, Node operation) { List<Node> xpaths = getChildNodes(operation, "xpath"); if (xpaths.isEmpty()) { return null; } String xpathExpression = xpaths.get(0).getTextContent(); if (xpathExpression == null) { return null; } XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); NodeList nl = null; try { XPathExpression expr = xpath.compile(xpathExpression); nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); } catch (XPathExpressionException ex) { Utils.onError(new Error.WrongXpathExpression(xpathExpression)); } return nl; }
/** * Validate message with a XML schema. * * @param receivedMessage * @param validationContext */ protected void validateXMLSchema( Message receivedMessage, XmlMessageValidationContext validationContext) { if (receivedMessage.getPayload() == null || !StringUtils.hasText(receivedMessage.getPayload(String.class))) { return; } try { Document doc = XMLUtils.parseMessagePayload(receivedMessage.getPayload(String.class)); if (!StringUtils.hasText(doc.getFirstChild().getNamespaceURI())) { return; } log.info("Starting XML schema validation ..."); XmlValidator validator = null; XsdSchemaRepository schemaRepository = null; if (validationContext.getSchema() != null) { validator = applicationContext .getBean(validationContext.getSchema(), XsdSchema.class) .createValidator(); } else if (validationContext.getSchemaRepository() != null) { schemaRepository = applicationContext.getBean( validationContext.getSchemaRepository(), XsdSchemaRepository.class); } else if (schemaRepositories.size() == 1) { schemaRepository = schemaRepositories.get(0); } else if (schemaRepositories.size() > 0) { for (XsdSchemaRepository repository : schemaRepositories) { if (repository.canValidate(doc)) { schemaRepository = repository; } } if (schemaRepository == null) { throw new CitrusRuntimeException( String.format( "Failed to find proper schema repository in Spring bean context for validating element '%s(%s)'", doc.getFirstChild().getLocalName(), doc.getFirstChild().getNamespaceURI())); } } else { log.warn( "Neither schema instance nor schema repository defined - skipping XML schema validation"); return; } if (schemaRepository != null) { if (!schemaRepository.canValidate(doc)) { throw new CitrusRuntimeException( String.format( "Unable to find proper XML schema definition for element '%s(%s)' in schema repository '%s'", doc.getFirstChild().getLocalName(), doc.getFirstChild().getNamespaceURI(), schemaRepository.getName())); } List<Resource> schemas = new ArrayList<>(); for (XsdSchema xsdSchema : schemaRepository.getSchemas()) { if (xsdSchema instanceof XsdSchemaCollection) { for (Resource resource : ((XsdSchemaCollection) xsdSchema).getSchemaResources()) { schemas.add(resource); } } else if (xsdSchema instanceof WsdlXsdSchema) { for (Resource resource : ((WsdlXsdSchema) xsdSchema).getSchemaResources()) { schemas.add(resource); } } else { synchronized (transformerFactory) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { transformerFactory .newTransformer() .transform(xsdSchema.getSource(), new StreamResult(bos)); } catch (TransformerException e) { throw new CitrusRuntimeException( "Failed to read schema " + xsdSchema.getTargetNamespace(), e); } schemas.add(new ByteArrayResource(bos.toByteArray())); } } } validator = XmlValidatorFactory.createValidator( schemas.toArray(new Resource[schemas.size()]), WsdlXsdSchema.W3C_XML_SCHEMA_NS_URI); } SAXParseException[] results = validator.validate(new DOMSource(doc)); if (results.length == 0) { log.info("Schema of received XML validated OK"); } else { log.error( "Schema validation failed for message:\n" + XMLUtils.prettyPrint(receivedMessage.getPayload(String.class))); // Report all parsing errors log.debug("Found " + results.length + " schema validation errors"); StringBuilder errors = new StringBuilder(); for (SAXParseException e : results) { errors.append(e.toString()); errors.append("\n"); } log.debug(errors.toString()); throw new ValidationException("Schema validation failed:", results[0]); } } catch (IOException e) { throw new CitrusRuntimeException(e); } catch (SAXException e) { throw new CitrusRuntimeException(e); } }
public Node item(int index) { if (index < 0 || index >= getLength()) { return null; } return (Node) nodes.get(index); }
protected void init(Element root) { NodeList children = root.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeName().equals("meta")) { Element meta = (Element) child; String value = XMLUtil.getText(meta); this.metaAttributes.put(meta.getAttribute("name"), value); } } // handle registers - OPTIONAL Element r = XMLUtil.getChildElement(root, "registers"); if (r != null) { List registers = XMLUtil.getChildElements(r, "register"); for (int i = 0; i < registers.size(); i++) { Element register = (Element) registers.get(i); RegisterDescriptor registerDescriptor = DescriptorFactory.getFactory().createRegisterDescriptor(register); registerDescriptor.setParent(this); this.registers.add(registerDescriptor); } } // handle global-conditions - OPTIONAL Element globalConditionsElement = XMLUtil.getChildElement(root, "global-conditions"); if (globalConditionsElement != null) { Element globalConditions = XMLUtil.getChildElement(globalConditionsElement, "conditions"); ConditionsDescriptor conditionsDescriptor = DescriptorFactory.getFactory().createConditionsDescriptor(globalConditions); conditionsDescriptor.setParent(this); this.globalConditions = conditionsDescriptor; } // handle initial-steps - REQUIRED Element intialActionsElement = XMLUtil.getChildElement(root, "initial-actions"); List initialActions = XMLUtil.getChildElements(intialActionsElement, "action"); for (int i = 0; i < initialActions.size(); i++) { Element initialAction = (Element) initialActions.get(i); ActionDescriptor actionDescriptor = DescriptorFactory.getFactory().createActionDescriptor(initialAction); actionDescriptor.setParent(this); this.initialActions.add(actionDescriptor); } // handle global-actions - OPTIONAL Element globalActionsElement = XMLUtil.getChildElement(root, "global-actions"); if (globalActionsElement != null) { List globalActions = XMLUtil.getChildElements(globalActionsElement, "action"); for (int i = 0; i < globalActions.size(); i++) { Element globalAction = (Element) globalActions.get(i); ActionDescriptor actionDescriptor = DescriptorFactory.getFactory().createActionDescriptor(globalAction); actionDescriptor.setParent(this); this.globalActions.add(actionDescriptor); } } // handle common-actions - OPTIONAL // - Store actions in HashMap for now. When parsing Steps, we'll resolve // any common actions into local references. Element commonActionsElement = XMLUtil.getChildElement(root, "common-actions"); if (commonActionsElement != null) { List commonActions = XMLUtil.getChildElements(commonActionsElement, "action"); for (int i = 0; i < commonActions.size(); i++) { Element commonAction = (Element) commonActions.get(i); ActionDescriptor actionDescriptor = DescriptorFactory.getFactory().createActionDescriptor(commonAction); actionDescriptor.setParent(this); addCommonAction(actionDescriptor); } } // handle timer-functions - OPTIONAL Element timerFunctionsElement = XMLUtil.getChildElement(root, "trigger-functions"); if (timerFunctionsElement != null) { List timerFunctions = XMLUtil.getChildElements(timerFunctionsElement, "trigger-function"); for (int i = 0; i < timerFunctions.size(); i++) { Element timerFunction = (Element) timerFunctions.get(i); Integer id = new Integer(timerFunction.getAttribute("id")); FunctionDescriptor function = DescriptorFactory.getFactory() .createFunctionDescriptor(XMLUtil.getChildElement(timerFunction, "function")); function.setParent(this); this.timerFunctions.put(id, function); } } // handle steps - REQUIRED Element stepsElement = XMLUtil.getChildElement(root, "steps"); List steps = XMLUtil.getChildElements(stepsElement, "step"); for (int i = 0; i < steps.size(); i++) { Element step = (Element) steps.get(i); StepDescriptor stepDescriptor = DescriptorFactory.getFactory().createStepDescriptor(step, this); this.steps.add(stepDescriptor); } // handle splits - OPTIONAL Element splitsElement = XMLUtil.getChildElement(root, "splits"); if (splitsElement != null) { List split = XMLUtil.getChildElements(splitsElement, "split"); for (int i = 0; i < split.size(); i++) { Element s = (Element) split.get(i); SplitDescriptor splitDescriptor = DescriptorFactory.getFactory().createSplitDescriptor(s); splitDescriptor.setParent(this); this.splits.add(splitDescriptor); } } // handle joins - OPTIONAL: Element joinsElement = XMLUtil.getChildElement(root, "joins"); if (joinsElement != null) { List join = XMLUtil.getChildElements(joinsElement, "join"); for (int i = 0; i < join.size(); i++) { Element s = (Element) join.get(i); JoinDescriptor joinDescriptor = DescriptorFactory.getFactory().createJoinDescriptor(s); joinDescriptor.setParent(this); this.joins.add(joinDescriptor); } } }
public void writeXML(PrintWriter out, int indent) { XMLUtil.printIndent(out, indent++); out.println("<workflow>"); Iterator iter = metaAttributes.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); XMLUtil.printIndent(out, indent); out.print("<meta name=\""); out.print(XMLUtil.encode(entry.getKey())); out.print("\">"); out.print(XMLUtil.encode(entry.getValue())); out.println("</meta>"); } if (registers.size() > 0) { XMLUtil.printIndent(out, indent++); out.println("<registers>"); for (int i = 0; i < registers.size(); i++) { RegisterDescriptor register = (RegisterDescriptor) registers.get(i); register.writeXML(out, indent); } XMLUtil.printIndent(out, --indent); out.println("</registers>"); } if (timerFunctions.size() > 0) { XMLUtil.printIndent(out, indent++); out.println("<trigger-functions>"); Iterator iterator = timerFunctions.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); XMLUtil.printIndent(out, indent++); out.println("<trigger-function id=\"" + entry.getKey() + "\">"); FunctionDescriptor trigger = (FunctionDescriptor) entry.getValue(); trigger.writeXML(out, indent); XMLUtil.printIndent(out, --indent); out.println("</trigger-function>"); } while (iterator.hasNext()) {} XMLUtil.printIndent(out, --indent); out.println("</trigger-functions>"); } if (getGlobalConditions() != null) { XMLUtil.printIndent(out, indent++); out.println("<global-conditions>"); getGlobalConditions().writeXML(out, indent); out.println("</global-conditions>"); } XMLUtil.printIndent(out, indent++); out.println("<initial-actions>"); for (int i = 0; i < initialActions.size(); i++) { ActionDescriptor action = (ActionDescriptor) initialActions.get(i); action.writeXML(out, indent); } XMLUtil.printIndent(out, --indent); out.println("</initial-actions>"); if (globalActions.size() > 0) { XMLUtil.printIndent(out, indent++); out.println("<global-actions>"); for (int i = 0; i < globalActions.size(); i++) { ActionDescriptor action = (ActionDescriptor) globalActions.get(i); action.writeXML(out, indent); } XMLUtil.printIndent(out, --indent); out.println("</global-actions>"); } if (commonActions.size() > 0) { XMLUtil.printIndent(out, indent++); out.println("<common-actions>"); Iterator iterator = getCommonActions().values().iterator(); while (iterator.hasNext()) { ActionDescriptor action = (ActionDescriptor) iterator.next(); action.writeXML(out, indent); } XMLUtil.printIndent(out, --indent); out.println("</common-actions>"); } XMLUtil.printIndent(out, indent++); out.println("<steps>"); for (int i = 0; i < steps.size(); i++) { StepDescriptor step = (StepDescriptor) steps.get(i); step.writeXML(out, indent); } XMLUtil.printIndent(out, --indent); out.println("</steps>"); if (splits.size() > 0) { XMLUtil.printIndent(out, indent++); out.println("<splits>"); for (int i = 0; i < splits.size(); i++) { SplitDescriptor split = (SplitDescriptor) splits.get(i); split.writeXML(out, indent); } XMLUtil.printIndent(out, --indent); out.println("</splits>"); } if (joins.size() > 0) { XMLUtil.printIndent(out, indent++); out.println("<joins>"); for (int i = 0; i < joins.size(); i++) { JoinDescriptor join = (JoinDescriptor) joins.get(i); join.writeXML(out, indent); } XMLUtil.printIndent(out, --indent); out.println("</joins>"); } XMLUtil.printIndent(out, --indent); out.println("</workflow>"); }
private void processTxt(Node operation) { List<Node> targets = getChildNodes(operation, "target"); List<Node> optionNodes = getChildNodes(operation, "opt"); List<Node> separatorNode = getChildNodes(operation, "separator"); if (targets.isEmpty() || optionNodes.isEmpty()) { return; } String defaultSeparator = "="; String globalSeparator = defaultSeparator; if (!separatorNode.isEmpty()) { globalSeparator = separatorNode.get(0).getTextContent(); if (globalSeparator.length() != 1) { globalSeparator = defaultSeparator; } } Map<String, String> options = new HashMap<String, String>(); Map<String, String> processedOptions = new HashMap<String, String>(); for (int i = 0; i < optionNodes.size(); i++) { Node option = optionNodes.get(i); String name = option.getAttributes().getNamedItem("name").getNodeValue(); String value = option.getTextContent(); if (options.containsKey(name)) { options.remove(name); } options.put(name, value); } for (int t = 0; t < targets.size(); t++) { File target = new File(absolutePath(targets.get(t).getTextContent())); File tmpFile = new File(Utils.timestamp()); BufferedWriter bw = null; BufferedReader br = null; try { Node separatorAttr = targets.get(t).getAttributes().getNamedItem("separator"); String separator = (separatorAttr == null) ? globalSeparator : separatorAttr.getNodeValue(); if (separator.length() != 1) { separator = globalSeparator; } bw = new BufferedWriter(new FileWriter(tmpFile)); if (target.exists()) { br = new BufferedReader(new FileReader(target)); for (String line; (line = br.readLine()) != null; ) { String[] parts = line.split(separator); if (parts.length < 2) { bw.write(line); bw.newLine(); continue; } String optName = parts[0].trim(); if (options.containsKey(optName)) { String optValue = options.get(optName); bw.write(optName + " " + separator + " " + optValue); bw.newLine(); processedOptions.put(optName, optValue); options.remove(optName); } else if (processedOptions.containsKey(optName)) { bw.write(optName + " " + separator + " " + processedOptions.get(optName)); bw.newLine(); } else { bw.write(line); bw.newLine(); } } br.close(); } for (Map.Entry<String, String> entry : options.entrySet()) { bw.write(entry.getKey() + " " + separator + " " + entry.getValue()); bw.newLine(); } bw.close(); FileUtils.copyFile(tmpFile, target); FileUtils.forceDelete(tmpFile); } catch (IOException ex) { Utils.onError(new Error.WriteTxtConfig(target.getPath())); } } }
public void generateSubAwardLineItems(BudgetSubAwards subAward, Budget budget) { BudgetDecimal amountChargeFA = new BudgetDecimal(25000); String directLtCostElement = getParameterService() .getParameterValueAsString( BudgetDocument.class, Constants.SUBCONTRACTOR_DIRECT_LT_25K_PARAM); String directGtCostElement = getParameterService() .getParameterValueAsString( BudgetDocument.class, Constants.SUBCONTRACTOR_DIRECT_GT_25K_PARAM); String inDirectLtCostElement = getParameterService() .getParameterValueAsString( BudgetDocument.class, Constants.SUBCONTRACTOR_F_AND_A_LT_25K_PARAM); String inDirectGtCostElement = getParameterService() .getParameterValueAsString( BudgetDocument.class, Constants.SUBCONTRACTOR_F_AND_A_GT_25K_PARAM); for (BudgetSubAwardPeriodDetail detail : subAward.getBudgetSubAwardPeriodDetails()) { BudgetPeriod budgetPeriod = findBudgetPeriod(detail, budget); List<BudgetLineItem> currentLineItems = findSubAwardLineItems(budgetPeriod, subAward.getSubAwardNumber()); // zero out existing line items before recalculating for (BudgetLineItem item : currentLineItems) { item.setDirectCost(BudgetDecimal.ZERO); item.setCostSharingAmount(BudgetDecimal.ZERO); item.setSubAwardNumber(subAward.getSubAwardNumber()); item.setLineItemDescription(subAward.getOrganizationName()); } if (BudgetDecimal.returnZeroIfNull(detail.getDirectCost()).isNonZero() || hasBeenChanged(detail, true)) { BudgetDecimal ltValue = lesserValue(detail.getDirectCost(), amountChargeFA); BudgetDecimal gtValue = detail.getDirectCost().subtract(ltValue); if (ltValue.isNonZero()) { BudgetLineItem lt = findOrCreateLineItem( currentLineItems, detail, subAward, budgetPeriod, directLtCostElement); lt.setLineItemCost(ltValue); } if (gtValue.isNonZero()) { BudgetLineItem gt = findOrCreateLineItem( currentLineItems, detail, subAward, budgetPeriod, directGtCostElement); gt.setLineItemCost(gtValue); } amountChargeFA = amountChargeFA.subtract(ltValue); } if (BudgetDecimal.returnZeroIfNull(detail.getIndirectCost()).isNonZero() || hasBeenChanged(detail, false)) { BudgetDecimal ltValue = lesserValue(detail.getIndirectCost(), amountChargeFA); BudgetDecimal gtValue = detail.getIndirectCost().subtract(ltValue); if (ltValue.isNonZero()) { BudgetLineItem lt = findOrCreateLineItem( currentLineItems, detail, subAward, budgetPeriod, inDirectLtCostElement); lt.setLineItemCost(ltValue); } if (gtValue.isNonZero()) { BudgetLineItem gt = findOrCreateLineItem( currentLineItems, detail, subAward, budgetPeriod, inDirectGtCostElement); gt.setLineItemCost(gtValue); } amountChargeFA = amountChargeFA.subtract(ltValue); } Collections.sort( currentLineItems, new Comparator<BudgetLineItem>() { public int compare(BudgetLineItem arg0, BudgetLineItem arg1) { return arg0.getLineItemNumber().compareTo(arg1.getLineItemNumber()); } }); Iterator<BudgetLineItem> iter = currentLineItems.iterator(); while (iter.hasNext()) { BudgetLineItem lineItem = iter.next(); if (BudgetDecimal.returnZeroIfNull(lineItem.getLineItemCost()).isZero()) { budgetPeriod.getBudgetLineItems().remove(lineItem); iter.remove(); } else { if (!budgetPeriod.getBudgetLineItems().contains(lineItem)) { budgetPeriod.getBudgetLineItems().add(lineItem); } } } if (!currentLineItems.isEmpty() && BudgetDecimal.returnZeroIfNull(detail.getCostShare()).isNonZero()) { currentLineItems.get(0).setCostSharingAmount(detail.getCostShare()); } } }