/** restore a state from file for resuming an MCMC chain * */ public void restoreFromFile() throws Exception { Log.info.println("Restoring from file"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document doc = factory.newDocumentBuilder().parse(new File(stateFileName)); doc.normalize(); final NodeList nodes = doc.getElementsByTagName("*"); final Node topNode = nodes.item(0); final NodeList children = topNode.getChildNodes(); for (int childIndex = 0; childIndex < children.getLength(); childIndex++) { final Node child = children.item(childIndex); if (child.getNodeType() == Node.ELEMENT_NODE) { final String id = child.getAttributes().getNamedItem("id").getNodeValue(); int stateNodeIndex = 0; // An init node without ID - should not bring the house down, does it? // I have not checked if the state is restored correctly or not (JH) while (stateNode[stateNodeIndex].getID() != null && !stateNode[stateNodeIndex].getID().equals(id)) { stateNodeIndex++; if (stateNodeIndex >= stateNode.length) { Log.warning.println("Cannot restore statenode id"); break; } } if (stateNodeIndex < stateNode.length) { final StateNode stateNode2 = stateNode[stateNodeIndex].copy(); stateNode2.fromXML(child); stateNode[stateNodeIndex].assignFromFragile(stateNode2); } } } }
private void ReaderPeriodoDemonstracaoFinanceira(File fileXML) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docbuilder = builderfactory.newDocumentBuilder(); Document document = docbuilder.parse(fileXML); document.normalize(); Element elementAOPDF = getSubtag(document, "ArrayOfPeriodoDemonstracaoFinanceira"); NodeList nodelistNIP = getNodeList(elementAOPDF, "NumeroIdentificacaoPeriodo"); NodeList nodelistDIP = getNodeList(elementAOPDF, "DataInicioPeriodo"); NodeList nodelistDFP = getNodeList(elementAOPDF, "DataFimPeriodo"); NIP = new String[nodelistNIP.getLength()]; I_DATAINICIOPERIODO = new String[nodelistDIP.getLength()]; I_DATAFIMPERIODO = new String[nodelistDFP.getLength()]; for (int i = 0; i < nodelistNIP.getLength(); i++) { Node nodeNIP = nodelistNIP.item(i); Node nodeDIP = nodelistDIP.item(i); Node nodeDFP = nodelistDFP.item(i); Element elementNIP = (Element) nodeNIP; Element elementDIP = (Element) nodeDIP; Element elementDFP = (Element) nodeDFP; NIP[i] = elementNIP.getTextContent(); I_DATAINICIOPERIODO[i] = elementDIP.getTextContent(); I_DATAFIMPERIODO[i] = elementDFP.getTextContent(); } }
/** Restore state from an XML fragment * */ public void fromXML(final String xml) { try { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final Document doc = factory.newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes())); doc.normalize(); final NodeList nodes = doc.getElementsByTagName("*"); final Node topNode = nodes.item(0); final NodeList children = topNode.getChildNodes(); for (int childIndex = 0; childIndex < children.getLength(); childIndex++) { final Node child = children.item(childIndex); if (child.getNodeType() == Node.ELEMENT_NODE) { final String id = child.getAttributes().getNamedItem("id").getNodeValue(); int stateNodeIndex = 0; while (!stateNode[stateNodeIndex].getID().equals(id)) { stateNodeIndex++; } final StateNode stateNode2 = stateNode[stateNodeIndex].copy(); stateNode2.fromXML(child); stateNode[stateNodeIndex].assignFromFragile(stateNode2); } } } catch (Exception e) { e.printStackTrace(); System.exit(1); } }
/** * @param parseDDPath * @return */ public static Map<String, List<String>> getClusterAndServerFromPropXML(String parseDDPath) { List<String> serverList = null; String clusterName = ""; String serverName = ""; try { Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(parseDDPath); document.normalize(); NodeList propNodeList = document.getElementsByTagName("propertyfile"); for (int i = 0; i < propNodeList.getLength(); i++) { Node propNode = propNodeList.item(i); if (propNode.getNodeType() == Node.ELEMENT_NODE) { Element propElement = (Element) propNode; NodeList propChildNodeList = propElement.getElementsByTagName("property"); for (int j = 0; j < propChildNodeList.getLength(); j++) { Node propChildNode = propChildNodeList.item(j); if (propChildNode.getNodeType() == Node.ELEMENT_NODE) { Element propChildElement = (Element) propChildNode; } } } } } catch (Exception ex) { ex.printStackTrace(); } log.info("Cluster Map Size Before returning the Method " + clusterMapInit.size()); storeHashMap(clusterMapInit); return clusterMapInit; }
protected Document wbxmlStream2Doc(InputStream in, boolean event) throws Exception { XMLStreamReader xmlStreamReader = null; XMLEventReader xmlEventReader = null; try { if (event) { xmlEventReader = inFact.createXMLEventReader(in); } else { xmlStreamReader = inFact.createXMLStreamReader(in); } Transformer xformer = TransformerFactory.newInstance().newTransformer(); StAXSource staxSource = event ? new StAXSource(xmlEventReader) : new StAXSource(xmlStreamReader); DOMResult domResult = new DOMResult(); xformer.transform(staxSource, domResult); Document doc = (Document) domResult.getNode(); doc.normalize(); return doc; } finally { if (xmlStreamReader != null) { try { xmlStreamReader.close(); } catch (Exception e) { } } if (xmlEventReader != null) { try { xmlEventReader.close(); } catch (Exception e) { } } } }
public static String linksFromWebsite2(String url, String[] idlist) throws Exception { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(new URL(url).openStream()); doc.normalize(); String text = ""; NodeList list = doc.getElementsByTagName("finance"); for (String id : idlist) { for (int i = 0; i < list.getLength(); i++) { String tag = ((Element) ((Element) list.item(i)).getElementsByTagName("symbol").item(0)) .getAttribute("data"); if (tag.equalsIgnoreCase(id)) { Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; Element courseTag = (Element) element.getElementsByTagName("last").item(0); text += courseTag.getAttribute("data") + "\n"; } } } } return text; }
public static String linksFromWebsite(String url) throws Exception { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(new URL(url).openStream()); doc.normalize(); String text = "Id,"; NodeList list = doc.getElementsByTagName("finance"); Node node = list.item(0); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; Element idTag = (Element) element.getElementsByTagName("company").item(0); String id = idTag.getAttribute("data"); Element courseTag = (Element) element.getElementsByTagName("last").item(0); String course = courseTag.getAttribute("data"); Element closeTag = (Element) element.getElementsByTagName("y_close").item(0); String prevClose = closeTag.getAttribute("data"); Element percentTag = (Element) element.getElementsByTagName("perc_change").item(0); String percent = percentTag.getAttribute("data"); if (!percent.startsWith("-")) { percent = "+" + (percent.equalsIgnoreCase("") ? "0" : percent) + "%"; } text = String.format("%s,,%s,,%s,,%s", id, course, prevClose, percent); } return text; }
public static void importSources() { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); InputStream inputStream = null; try { DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); inputStream = new URL(Settings.GENERATOR_SOURCE).openStream(); Document document = documentBuilder.parse(inputStream); document.normalize(); Node root = document.getElementsByTagName("generator").item(0); for (Node source : new IterableNodeList(root.getChildNodes())) { if (Objects.equals(source.getNodeName(), "strings")) { StoredData.strings.putAll(getStringData(source)); } else if (source.getChildNodes().getLength() >= 1) { StoredData.sources.add(source.getNodeName()); StoredData.data.putAll(getChildMultidata(source)); } } } catch (Exception e) { System.err.println("Unable to import sources from internet."); e.printStackTrace(); } finally { try { assert inputStream != null : "Input Stream mustn't be null!"; inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
public static String getStringFromDocument(Document doc) { try { doc.normalize(); DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); // transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); int indent = 2; if (indent > 0) { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", Integer.toString(indent)); } // transformer.transform(domSource, result); return writer.toString(); } catch (TransformerException ex) { ex.printStackTrace(); return null; } }
/** * Parses the XML stored in the given file and returns a Document object that represents the * parsed XML file * * @param xml * @return */ public static Document parseXML(File file) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { // Using factory get an instance of document builder DocumentBuilder db = dbf.newDocumentBuilder(); // parse using builder to get DOM representation of the XML file FileInputStream fis = new FileInputStream(file); Document domDoc = db.parse(fis); domDoc.normalize(); fis.close(); return domDoc; } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (FileNotFoundException e) { System.err.println("File not found: " + e.getMessage()); } catch (IOException e) { e.printStackTrace(); } // default for exceptions return null; }
private void ReaderComposicaoCapitalSocialDemonstracaoFinanceiraNegocios(File fileXML) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docbuilder = builderfactory.newDocumentBuilder(); Document document = docbuilder.parse(fileXML); document.normalize(); Element elementCCSDF = getSubtag( document, "ComposicaoCapitalSocialDemonstracaoFinanceira"); // ComposicaoCapitalSocialDemonstracaoFinanceira Element elementNICCS = (Element) elementCCSDF .getElementsByTagName("NumeroIdentificacaoComposicaoCapitalSocial") .item(0); // NumeroIdentificacaoComposicaoCapitalSocial Element elementQAOCI = (Element) elementCCSDF .getElementsByTagName("QuantidadeAcaoOrdinariaCapitalIntegralizado") .item(0); // QuantidadeAcaoOrdinariaCapitalIntegralizado Element elementQAFCI = (Element) elementCCSDF .getElementsByTagName("QuantidadeAcaoPreferencialCapitalIntegralizado") .item(0); // QuantidadeAcaoPreferencialCapitalIntegralizado Element elementQTACI = (Element) elementCCSDF .getElementsByTagName("QuantidadeTotalAcaoCapitalIntegralizado") .item(0); // QuantidadeTotalAcaoCapitalIntegralizado Element elementQAOT = (Element) elementCCSDF .getElementsByTagName("QuantidadeAcaoOrdinariaTesouraria") .item(0); // QuantidadeAcaoOrdinariaTesouraria Element elementQAPT = (Element) elementCCSDF .getElementsByTagName("QuantidadeAcaoPreferencialTesouraria") .item(0); // QuantidadeAcaoPreferencialTesouraria Element elementQTAT = (Element) elementCCSDF .getElementsByTagName("QuantidadeTotalAcaoTesouraria") .item(0); // QuantidadeTotalAcaoTesouraria NICCS = elementNICCS.getTextContent(); QAOCI = elementQAOCI.getTextContent(); QAFCI = elementQAFCI.getTextContent(); QTACI = elementQTACI.getTextContent(); QAOT = elementQAOT.getTextContent(); QAPT = elementQAPT.getTextContent(); QTAT = elementQTAT.getTextContent(); }
/** * Test case 2 for relevance selection of submitted instance data. * * @throws Exception if any error occurred during the test. */ public void testSelectRelevant2() throws Exception { Instance instance = this.chibaBean.getContainer().getDefaultModel().getDefaultInstance(); Document document = RelevanceSelector.selectRelevant(instance, "/root/paragraph"); document.normalize(); JXPathContext context = JXPathContext.newContext(document); assertTrue( "name(/*[1]) = 'paragraph'", context.getValue("name(/*[1])").toString().equals("paragraph")); assertTrue( "/paragraph/@xmlns = ''", context.getValue("/paragraph/@xmlns").toString().equals("")); assertTrue( "/paragraph/@xmlns:test = 'http://test.org/ns'", context.getValue("/paragraph/@xmlns:test").toString().equals("http://test.org/ns")); assertTrue( "/paragraph/@id = 'p-1'", context.getValue("/paragraph/@id").toString().equals("p-1")); assertTrue( "count(/paragraph/*) = 1", context.getValue("count(/paragraph/*)", Integer.class).toString().equals("1")); assertTrue( "name(/paragraph/*[1]) = 'content'", context.getValue("name(/paragraph/*[1])").toString().equals("content")); assertTrue( "/paragraph/content/@id = 'c-1'", context.getValue("/paragraph/content/@id").toString().equals("c-1")); assertTrue( "/paragraph/content/text()[1] = 'some mixed content 1'", context.getValue("/paragraph/content/text()[1]").toString().equals("some mixed content 1")); assertTrue( "/paragraph/content/text()[2] = 'some more mixed content 1'", context .getValue("/paragraph/content/text()[2]") .toString() .equals("some more mixed content 1")); assertTrue( "count(/paragraph/content/*) = 1", context.getValue("count(/paragraph/content/*)", Integer.class).toString().equals("1")); assertTrue( "name(/paragraph/content/*[1]) = 'input'", context.getValue("name(/paragraph/content/*[1])").toString().equals("input")); assertTrue( "/paragraph/content/input/@id = 'i-1'", context.getValue("/paragraph/content/input/@id").toString().equals("i-1")); assertTrue( "/paragraph/content/input/text()[1] = 'input 1'", context.getValue("/paragraph/content/input/text()[1]").toString().equals("input 1")); assertTrue( "count(/paragraph/content/input/*) = 0", context .getValue("count(/paragraph/content/input/*)", Integer.class) .toString() .equals("0")); }
public static Document getRoot(String filePathName) throws Exception { Document doc = null; // 建立一个解析器工厂 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 获得一个DocumentBuilder对象,这个对象代表了具体的DOM解析器 DocumentBuilder builder = factory.newDocumentBuilder(); // 得到一个表示XML文档的Document对象 doc = builder.parse(filePathName); // 去掉XML文档中作为格式化内容的空白而映射在DOM树中的不必要的Text Node对象 doc.normalize(); return doc; }
/** * Sign an ResponseType at the root * * @param response * @param keypair Key Pair * @param digestMethod (Example: DigestMethod.SHA1) * @param signatureMethod (Example: SignatureMethod.DSA_SHA1) * @return * @throws ParserConfigurationException * @throws XMLSignatureException * @throws MarshalException * @throws GeneralSecurityException */ public Document sign(ResponseType response, KeyPair keypair) throws ParserConfigurationException, GeneralSecurityException, MarshalException, XMLSignatureException { SAML2Response saml2Request = new SAML2Response(); Document doc = saml2Request.convert(response); doc.normalize(); Node theSibling = getNextSiblingOfIssuer(doc); if (theSibling != null) { this.sibling = theSibling; } return sign(doc, response.getID(), keypair); }
/** * Sign an assertion whose id value is provided in the response type * * @param response * @param idValueOfAssertion * @param keypair * @param referenceURI * @return * @throws ParserConfigurationException * @throws TransformerException * @throws TransformerFactoryConfigurationError * @throws XPathException * @throws XMLSignatureException * @throws MarshalException * @throws GeneralSecurityException */ public Document sign( ResponseType response, String idValueOfAssertion, KeyPair keypair, String referenceURI) throws ParserConfigurationException, XPathException, TransformerFactoryConfigurationError, TransformerException, GeneralSecurityException, MarshalException, XMLSignatureException { SAML2Response saml2Response = new SAML2Response(); Document doc = saml2Response.convert(response); doc.normalize(); Node theSibling = getNextSiblingOfIssuer(doc); if (theSibling != null) { this.sibling = theSibling; } return sign(doc, idValueOfAssertion, keypair, referenceURI); }
/** * * Returns a section as a complete htmlform, including the three required encounter tags. * * @param htmlForm * @param sectionIndex * @return * @throws Exception */ public static String getSectionAsFormXml(HtmlForm htmlForm, Integer sectionIndex) throws Exception{ Document doc = HtmlFormEntryUtil.stringToDocument(htmlForm.getXmlData()); NodeList nl = doc.getElementsByTagName("section"); Node sectionNode = null; try { sectionNode = nl.item(sectionIndex); } catch (Exception ex){ throw new RuntimeException("The section index that you've passed in is out of range. There are only " + nl.getLength() + " section tags in the document and you requested section tag " + sectionIndex); } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc2 = db.newDocument(); Node formRoot = doc2.createElement("htmlform"); doc2.appendChild(formRoot); formRoot.appendChild(doc2.importNode(sectionNode, true)); if (doc2.getElementsByTagName("encounterLocation").getLength() == 0){ Node encLoc = doc2.createElement("encounterLocation"); formRoot.appendChild(encLoc); } if (doc2.getElementsByTagName("encounterDate").getLength() == 0){ Node encDate = doc2.createElement("encounterDate"); formRoot.appendChild(encDate); } if (doc2.getElementsByTagName("encounterProvider").getLength() == 0){ Node encDate = doc2.createElement("encounterProvider"); Element encDateElement = (Element) encDate; encDateElement.setAttribute("role","Provider"); formRoot.appendChild(encDate); } doc2.normalize(); try { DOMSource domSource = new DOMSource(doc2); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); return writer.toString(); } catch(TransformerException ex) { ex.printStackTrace(); return null; } }
/** * Look up database accessibility information for specified unit. * * @param u The unit which should get accessibility info assigned to it. * @param form The AccessibilityDatabaseFilterForm to fetch the language id to use. */ public void assignAccessibilityDatabaseInfo(Unit u, AccessibilityDatabaseFilterForm form) { if (this.useAccessibilityDatabaseIntegration) { // First find out the accessibility database id if (assignAccessibilityDatabaseId(u)) { int languageId = Integer.parseInt(form.getLanguageId()); String url = accessibilityDatabaseIntegrationGetInfoUrl + languageId + "&facilityId=" + u.getAccessibilityDatabaseId(); String content = httpFetcher.fetchUrl(url); // Now read the content and get accessibility info Document doc = DocumentHelper.getDocumentFromString(content); doc.normalize(); // Get business object (there is only one) NodeList businessObjectNodeList = doc.getElementsByTagName("businessobject"); AccessibilityObject businessObject = null; for (int i = 0; i < businessObjectNodeList.getLength(); i++) { businessObject = AccessibilityObject.createAccessibilityObjectFromNode(businessObjectNodeList.item(i)); } // Get sub objects NodeList subObjectNodeList = doc.getElementsByTagName("subobject"); ArrayList<AccessibilityObject> subObjects = new ArrayList<AccessibilityObject>(); for (int i = 0; i < subObjectNodeList.getLength(); i++) { AccessibilityObject subObject = AccessibilityObject.createAccessibilityObjectFromNode(subObjectNodeList.item(i)); subObjects.add(subObject); } AccessibilityInformation accessibilityInformation = new AccessibilityInformation(businessObject, subObjects); u.setAccessibilityInformation(accessibilityInformation); } } }
/** * @param parseDDPath * @return */ public static Map<String, List<String>> getClusterAndServerFromXML(String parseDDPath) { List<String> serverList = null; String clusterName = ""; String serverName = ""; try { Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(parseDDPath); doc.normalize(); Element rootNode = doc.getDocumentElement(); log.info("Root Node Name :" + rootNode); NodeList nodeList = rootNode.getElementsByTagName("cluster"); for (int i = 0; i < nodeList.getLength(); i++) { Node clusterNode = nodeList.item(i); if (clusterNode.getNodeType() == Node.ELEMENT_NODE) { Element clusterElement = (Element) clusterNode; clusterName = clusterElement.getAttribute("name"); log.info( "cluster Node :" + clusterNode.getTextContent().trim() + " cluserName " + clusterName); NodeList serverNodes = clusterElement.getElementsByTagName("server"); serverList = new ArrayList<String>(); for (int j = 0; j < serverNodes.getLength(); j++) { Node serverNode = serverNodes.item(j); if (serverNode.getNodeType() == Node.ELEMENT_NODE) { Element serverElement = (Element) serverNode; serverName = serverElement.getAttribute("name"); log.info("server Element Name :" + serverName); serverList.add(serverName); } } } log.info("server list size before placing in map:" + serverList.size()); clusterMapInit.put(clusterName, serverList); } } catch (Exception ex) { ex.printStackTrace(); } log.info("Cluster Map Size Before returning the Method " + clusterMapInit.size()); storeHashMap(clusterMapInit); return clusterMapInit; }
private static void setMapping() throws Exception { InputStream myConfig = ResultValidatorFactory.class.getClassLoader().getResourceAsStream("validator-mapping.xml"); Document oConfigDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(myConfig); oConfigDocument.normalize(); Element oConfigRoot = oConfigDocument.getDocumentElement(); for (int u = 0; u < oConfigRoot.getElementsByTagName("validator").getLength(); u++) { Element cd = (Element) oConfigRoot.getElementsByTagName("validator").item(u); String aValue = cd.getElementsByTagName("view").item(0).getChildNodes().item(0).getNodeValue(); String aKey = cd.getElementsByTagName("exercise").item(0).getChildNodes().item(0).getNodeValue(); myMap.put(aKey.toLowerCase(), aValue); } }
public static List<String> getRssCurrency() { List<String> line = new ArrayList<String>(); try { javax.xml.parsers.DocumentBuilderFactory dbFac = javax.xml.parsers.DocumentBuilderFactory.newInstance(); javax.xml.parsers.DocumentBuilder db = dbFac.newDocumentBuilder(); org.w3c.dom.Document doc = db.parse("http://www.cbi.ir/ExRatesRss.aspx"); doc.normalize(); org.w3c.dom.NodeList nodes = doc.getElementsByTagName("item"); for (int i = 0; i < nodes.getLength(); i++) { org.w3c.dom.Node node = nodes.item(i); org.w3c.dom.Node descNode = node.getChildNodes().item(3); String desc = descNode.getTextContent(); String[] descParts = desc.split("="); for (int j = 0; j < descParts.length; j++) { line.add(descParts[j]); } } } catch (Exception ex) { } return line; }
/** create the whole new document */ public Document createDocument(String[] classPath) throws Exception { // Iterate over the classpath to identify reference classes classFiles = new Hashtable(); ClassPathLoader cpl = new ClassPathLoader(classPath); Enumeration e = cpl.loaders(); while (e.hasMoreElements()) { ClassPathLoader.FileLoader fl = (ClassPathLoader.FileLoader) e.nextElement(); ClassFile[] classes = fl.getClasses(); log("Processing " + classes.length + " classes in " + fl.getFile()); // process all classes for (int i = 0; i < classes.length; i++) { classFiles.put(classes[i].getFullName(), classes[i]); } } // Load the JProbe coverage XML report DocumentBuilder dbuilder = newBuilder(); InputSource is = new InputSource(new FileInputStream(file)); if (jprobeHome != null) { File dtdDir = new File(jprobeHome, "dtd"); is.setSystemId("file:///" + dtdDir.getAbsolutePath() + "/"); } report = dbuilder.parse(is); report.normalize(); // create maps for faster node access (also filters out unwanted nodes) createNodeMaps(); // Make sure each class from the reference path ends up in the report Enumeration classes = classFiles.elements(); while (classes.hasMoreElements()) { ClassFile cf = (ClassFile) classes.nextElement(); serializeClass(cf); } // update the document with the stats update(); return report; }
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { System.out.println("=========================="); System.out.println("JVM vendor: " + System.getProperty("java.vm.vendor")); System.out.println("JVM name: " + System.getProperty("java.vm.name")); String originalTransFactory = System.getProperty("javax.xml.transform.TransformerFactory"); System.out.println("TransformerFactory: " + originalTransFactory); System.out.println("documentBuilderFactory:" + documentBuilderFactory); String docFactory = System.getProperty("javax.xml.parsers.DocumentBuilderFactory"); System.out.println("docFactory:" + docFactory); DocumentBuilder db = documentBuilderFactory.newDocumentBuilder(); File file = new File("src/sample.xml"); System.out.println(file.getAbsolutePath()); System.out.println(db); // 这个Document就是一个XML文件在内存中的镜像 Document doc = db.parse(file); doc.normalize(); System.out.println(doc); System.out.println("=========================="); }
/** * Parses the XML passed in as an argument and returns a Document object that represents the * parsed XML * * @param xml * @return */ public static Document parseXML(String xml) throws SAXException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { // Using factory get an instance of document builder DocumentBuilder db = dbf.newDocumentBuilder(); // parse using builder to get DOM representation of the XML file Document domDoc = db.parse(new ByteArrayInputStream(xml.getBytes())); domDoc.normalize(); return domDoc; } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // default for exceptions return null; }
/** * Should return an array of store objects * * @throws ParserConfigurationException * @throws SAXException * @throws IOException */ private static World readXML() throws ParserConfigurationException, SAXException, IOException { File xml = new File(FILE_NAME); Document doc = getDocument(xml); doc.normalize(); // Get the gameTime and previous money long gameTime = Long.parseLong(readSingleElement(doc, "gametime")); float money = Float.parseFloat(readSingleElement(doc, "money")); Item[] itemsList = new Item[ItemFactory.ITEM_COUNT]; // Loop through the stores (there's only 1 so far) NodeList storeList = doc.getElementsByTagName("store"); for (int i = 0; i < storeList.getLength(); i++) { Element outterE = (Element) storeList.item(i); // Loop through the items in the stores NodeList items = outterE.getElementsByTagName("item"); for (int j = 0; j < items.getLength(); j++) { Element e = (Element) items.item(j); // Create and add the items to the store int itemID = Integer.parseInt(e.getAttribute("id")); int quantity = Integer.parseInt(readSingleElement(e, "quantity")); itemsList[itemID] = (ItemFactory.createItem(itemID, quantity)); } } System.out.println("SaveLoad:: Returning saved world."); // Create the store Store store = new Store(money, gameTime, itemsList); // Return the user's saved game return new World(gameTime, money, store); }
/** * This method is responsible for saving a macro as an XML document. The document follows the * structure of the macro tree. */ public static void saveMacro(final MacroDefinition macroDef, final String saveLocation) throws NullPointerException, IOException, ParserConfigurationException, DOMException, TransformerConfigurationException, TransformerException { MacroWriter.macro = macroDef; File macroFile = null; if (saveLocation.equals("")) { // test if macro save location exists File macroSaveLocation = new File(MacroManager.macroSaveLocation); if (!macroSaveLocation.exists()) macroSaveLocation.mkdir(); String macroPath = MacroManager.macroSaveLocation + MacroWriter.macro.getName() + ".xml"; macroFile = new File(macroPath); } else { macroFile = new File(saveLocation); } Document ptDOM = null; StreamSource xsltSource = null; Transformer transformer = null; try { // Build a PTML Document DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); ptDOM = builder.newDocument(); // PTML Element Element ptmlElement = ptDOM.createElement("ptml"); ptDOM.appendChild(ptmlElement); // Macro Element Element macroElement = ptDOM.createElement("macro"); macroElement.setAttribute("name", MacroWriter.macro.getName()); macroElement.setAttribute("description", MacroWriter.macro.getDescription()); macroElement.setAttribute("returntype", MacroWriter.macro.getReturnType()); ptmlElement.appendChild(macroElement); // put nodes into HashMap, so that we can check whether they have // been processed already // (in case of recursion when child nodes are processed) ArrayList<PerformanceTreeNode> nodesArray = MacroWriter.macro.getMacroNodes(); Iterator<PerformanceTreeNode> i = nodesArray.iterator(); while (i.hasNext()) { PerformanceTreeNode nodeNotProcessedYet = i.next(); String nodeID = nodeNotProcessedYet.getId(); MacroWriter.nodesProcessed.put(nodeID, "false"); } // serialise node and their arcs i = nodesArray.iterator(); while (i.hasNext()) { PerformanceTreeNode nodeToSerialise = i.next(); String nodeToSerialiseID = nodeToSerialise.getId(); boolean nodeProcessedAlready = false; if ((MacroWriter.nodesProcessed.get(nodeToSerialiseID)).equals("true")) { nodeProcessedAlready = true; } else if ((MacroWriter.nodesProcessed.get(nodeToSerialiseID)).equals("false")) { nodeProcessedAlready = false; } if (!nodeProcessedAlready) MacroWriter.createNodeElement(nodeToSerialise, macroElement, ptDOM); } // serialise state and action labels MacroWriter.serialiseStateAndActionLabels(macroElement, ptDOM); ptDOM.normalize(); // Create Transformer with XSL Source File xsltSource = new StreamSource( Thread.currentThread() .getContextClassLoader() .getResourceAsStream( "pipe" + System.getProperty("file.separator") + "modules" + System.getProperty("file.separator") + "queryeditor" + System.getProperty("file.separator") + "io" + System.getProperty("file.separator") + "WriteMacroXML.xsl")); transformer = TransformerFactory.newInstance().newTransformer(xsltSource); // Write file and do XSLT transformation to generate correct PTML File outputObjectArrayList = macroFile; DOMSource source = new DOMSource(ptDOM); StreamResult result = new StreamResult(outputObjectArrayList); transformer.transform(source, result); } catch (DOMException e) { System.out.println( "DOMException thrown in saveMacro()" + " : MacroWriter Class : modules.queryeditor.io Package" + " : filename=\"" + macroFile.getCanonicalPath() + "\" xslt=\"" + xsltSource.getSystemId() + "\" transformer=\"" + transformer.getURIResolver() + "\""); } catch (ParserConfigurationException e) { System.out.println( "ParserConfigurationException thrown in saveMacro()" + " : MacroWriter Class : modules.queryeditor.io Package" + " : filename=\"" + macroFile.getCanonicalPath() + "\" xslt=\"" + "\" transformer=\"" + "\""); } catch (TransformerConfigurationException e) { System.out.println( "TransformerConfigurationException thrown in saveMacro()" + " : MacroWriter Class : modules.queryeditor.io Package" + " : filename=\"" + macroFile.getCanonicalPath() + "\" xslt=\"" + xsltSource.getSystemId() + "\" transformer=\"" + transformer.getURIResolver() + "\""); } catch (TransformerException e) { System.out.println( "TransformerException thrown in saveMacro()" + " : MacroWriter Class : modules.queryeditor.io Package" + " : filename=\"" + macroFile.getCanonicalPath() + "\" xslt=\"" + xsltSource.getSystemId() + "\" transformer=\"" + transformer.getURIResolver() + "\""); } }
private void ReaderInfoFinaDemonstracaoFin(File fileXML) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docbuilder = builderfactory.newDocumentBuilder(); Document document = docbuilder.parse(fileXML); document.normalize(); Element elementAOIFDF = getSubtag(document, "ArrayOfInfoFinaDFin"); NodeList nodelistNIP = getNodeList(elementAOIFDF, "NumeroIdentificacaoPeriodo"); NodeList nodelistNC = getNodeList(elementAOIFDF, "NumeroConta"); NodeList nodelistNOC = getNodeList(elementAOIFDF, "NumeroOrdemConta"); NodeList nodelistDC = getNodeList(elementAOIFDF, "DescricaoConta1"); NodeList nodelistVC1 = getNodeList(elementAOIFDF, "ValorConta1"); NodeList nodelistVC2 = getNodeList(elementAOIFDF, "ValorConta2"); NodeList nodelistVC3 = getNodeList(elementAOIFDF, "ValorConta3"); NodeList nodelistVC4 = getNodeList(elementAOIFDF, "ValorConta4"); NodeList nodelistVC5 = getNodeList(elementAOIFDF, "ValorConta5"); NodeList nodelistVC6 = getNodeList(elementAOIFDF, "ValorConta6"); NodeList nodelistVC7 = getNodeList(elementAOIFDF, "ValorConta7"); NodeList nodelistVC8 = getNodeList(elementAOIFDF, "ValorConta8"); NodeList nodelistVC9 = getNodeList(elementAOIFDF, "ValorConta9"); NodeList nodelistVC10 = getNodeList(elementAOIFDF, "ValorConta10"); NodeList nodelistVC11 = getNodeList(elementAOIFDF, "ValorConta11"); NodeList nodelistVC12 = getNodeList(elementAOIFDF, "ValorConta12"); tamanho_vetor_conta = nodelistDC.getLength(); if (nodelistDC.getLength() == 0) { permissao_conta = false; return; } Numeroidenfperiodo = new String[nodelistDC.getLength()]; NUMEROCONTA = new String[nodelistDC.getLength()]; NUMEROORDEMCONTA = new String[nodelistDC.getLength()]; DESCRICAOCONTA = new String[nodelistDC.getLength()]; VALORCONTA1 = new String[nodelistDC.getLength()]; VALORCONTA2 = new String[nodelistDC.getLength()]; VALORCONTA3 = new String[nodelistDC.getLength()]; VALORCONTA4 = new String[nodelistDC.getLength()]; VALORCONTA5 = new String[nodelistDC.getLength()]; VALORCONTA6 = new String[nodelistDC.getLength()]; VALORCONTA7 = new String[nodelistDC.getLength()]; VALORCONTA8 = new String[nodelistDC.getLength()]; VALORCONTA9 = new String[nodelistDC.getLength()]; VALORCONTA10 = new String[nodelistDC.getLength()]; VALORCONTA11 = new String[nodelistDC.getLength()]; VALORCONTA12 = new String[nodelistDC.getLength()]; for (int i = 0; i < nodelistDC.getLength(); i++) { Node nodeNIP = nodelistNIP.item(i); Node nodeNC = nodelistNC.item(i); Node nodeNOC = nodelistNOC.item(i); Node nodeDC = nodelistDC.item(i); Node nodeVC1 = nodelistVC1.item(i); Node nodeVC2 = nodelistVC2.item(i); Node nodeVC3 = nodelistVC3.item(i); Node nodeVC4 = nodelistVC4.item(i); Node nodeVC5 = nodelistVC5.item(i); Node nodeVC6 = nodelistVC6.item(i); Node nodeVC7 = nodelistVC7.item(i); Node nodeVC8 = nodelistVC8.item(i); Node nodeVC9 = nodelistVC9.item(i); Node nodeVC10 = nodelistVC10.item(i); Node nodeVC11 = nodelistVC11.item(i); Node nodeVC12 = nodelistVC12.item(i); Element elementNIP = (Element) nodeNIP; Element elementNC = (Element) nodeNC; Element elementNOC = (Element) nodeNOC; Element elementDC = (Element) nodeDC; Element elementVC1 = (Element) nodeVC1; Element elementVC2 = (Element) nodeVC2; Element elementVC3 = (Element) nodeVC3; Element elementVC4 = (Element) nodeVC4; Element elementVC5 = (Element) nodeVC5; Element elementVC6 = (Element) nodeVC6; Element elementVC7 = (Element) nodeVC7; Element elementVC8 = (Element) nodeVC8; Element elementVC9 = (Element) nodeVC9; Element elementVC10 = (Element) nodeVC10; Element elementVC11 = (Element) nodeVC11; Element elementVC12 = (Element) nodeVC12; Numeroidenfperiodo[i] = elementNC.getTextContent(); NUMEROCONTA[i] = elementNC.getTextContent(); NUMEROORDEMCONTA[i] = elementNOC.getTextContent(); DESCRICAOCONTA[i] = elementDC.getTextContent(); VALORCONTA1[i] = elementVC1.getTextContent(); VALORCONTA2[i] = elementVC2.getTextContent(); VALORCONTA3[i] = elementVC3.getTextContent(); VALORCONTA4[i] = elementVC4.getTextContent(); VALORCONTA5[i] = elementVC5.getTextContent(); VALORCONTA6[i] = elementVC6.getTextContent(); VALORCONTA7[i] = elementVC7.getTextContent(); VALORCONTA8[i] = elementVC8.getTextContent(); VALORCONTA9[i] = elementVC9.getTextContent(); VALORCONTA10[i] = elementVC10.getTextContent(); VALORCONTA11[i] = elementVC11.getTextContent(); VALORCONTA12[i] = elementVC12.getTextContent(); } }
@Override public int compare(Document o1, Document o2) { o1.normalize(); o2.normalize(); return o1.isEqualNode(o2) ? 0 : 1; }
/** * Returns a Document instance that is normalized by parsing the filename represented by the * filename. * * @param file the File to parse. * @return the parsed Document */ public static Document parseAndNormalize(File file) { Document doc = parse(file).getOwnerDocument(); doc.normalize(); return doc; }
private void ReaderPagamentoProventoDinheiroDemonstracaoFinanceiraNegocios(File fileXML) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docbuilder = builderfactory.newDocumentBuilder(); Document document = docbuilder.parse(fileXML); document.normalize(); Element elementAOPPD = getSubtag(document, "ArrayOfPagamentoProventoDinheiroDemonstracaoFinanceira"); // AOPPD NodeList nodelistDAP = getNodeList(elementAOPPD, "DataAprovacaoProvento"); NodeList nodelistDIP = getNodeList(elementAOPPD, "DataInicioPagamento"); NodeList nodelistVPPA = getNodeList(elementAOPPD, "ValorProventoPorAcao"); NodeList nodelistTP = getNodeList(elementAOPPD, "TipoProvento"); NodeList nodelistCEA = getNodeList(elementAOPPD, "CodigoEspecieAcao"); NodeList nodelistCCEAP = getNodeList(elementAOPPD, "CodigoClasseAcaoPreferencial"); tamanho_vetor_provento = nodelistDIP.getLength(); if (nodelistDAP.getLength() == 0) { permissao_provento = false; return; } TipoProvento = new String[nodelistDAP.getLength()]; DataAprovacaoProvento = new String[nodelistDAP.getLength()]; DataInicioPagamento = new String[nodelistDAP.getLength()]; SiglaCodigoEspecie = new String[nodelistDAP.getLength()]; DescricaoCodigoEspecie = new String[nodelistDAP.getLength()]; SiglaCodigoClassePreferencial = new String[nodelistDAP.getLength()]; DescricaoCodigoClassePreferencial = new String[nodelistDAP.getLength()]; ValorProventoPorAcao = new String[nodelistDAP.getLength()]; for (int i = 0; i < nodelistDAP.getLength(); i++) { Node nodeDAP = nodelistDAP.item(i); Node nodeDIP = nodelistDIP.item(i); Node nodeVPPA = nodelistVPPA.item(i); Element elementDAP = (Element) nodeDAP; Element elementDIP = (Element) nodeDIP; Element elementVPPA = (Element) nodeVPPA; DataAprovacaoProvento[i] = elementDAP.getTextContent(); DataInicioPagamento[i] = elementDIP.getTextContent(); ValorProventoPorAcao[i] = elementVPPA.getTextContent(); } for (int i = 0; i < nodelistTP.getLength(); i++) { Node nodeTP = nodelistTP.item(i); Element elementTP = (Element) nodeTP; NodeList nodelistDOD = getNodeList(elementTP, "DescricaoOpcaoDominio"); Node nodeDOD = nodelistDOD.item(0); Element elementDOD = (Element) nodeDOD; TipoProvento[i] = elementDOD.getTextContent(); } for (int i = 0; i < nodelistCEA.getLength(); i++) { Node nodeCEA = nodelistCEA.item(i); Element elementCEA = (Element) nodeCEA; NodeList nodelistDOD = getNodeList(elementCEA, "DescricaoOpcaoDominio"); NodeList nodelistSOD = getNodeList(elementCEA, "SiglaOpcaoDominio"); Node nodeDOD = nodelistDOD.item(0); Element elementDOD = (Element) nodeDOD; DescricaoCodigoEspecie[i] = elementDOD.getTextContent(); Node nodeSOD = nodelistSOD.item(0); Element elementSOD = (Element) nodeSOD; SiglaCodigoEspecie[i] = elementSOD.getTextContent(); } for (int i = 0; i < nodelistCCEAP.getLength(); i++) { Node nodeCCEAP = nodelistCCEAP.item(i); Element elementCCEAP = (Element) nodeCCEAP; NodeList nodelistDOD = getNodeList(elementCCEAP, "DescricaoOpcaoDominio"); NodeList nodelistSOD = getNodeList(elementCCEAP, "SiglaOpcaoDominio"); Node nodeDOD = nodelistDOD.item(0); Element elementDOD = (Element) nodeDOD; DescricaoCodigoClassePreferencial[i] = elementDOD.getTextContent(); Node nodeSOD = nodelistSOD.item(0); Element elementSOD = (Element) nodeSOD; SiglaCodigoClassePreferencial[i] = elementSOD.getTextContent(); } }