/** * Method that reads a XML-file, and returns a Model that contains the information * * @param file * @return * @return */ public static Model readXML(String file) { // initialize table to be filled with content of XML file Model t = new Model(); try { // Create file to be parsed by document parser File xmlfile = new File(file); // create parser DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); // parse the file Document parsedfile = parser.parse(xmlfile); // normalize the parsed file (make it more user-friendly) parsedfile.getDocumentElement().normalize(); NodeList cells = parsedfile.getElementsByTagName("CELL"); for (int i = 0; i < cells.getLength(); i++) { // Get cell at list index i Node currentcell = cells.item(i); // read the elements "location" attributes row/column if (Node.ELEMENT_NODE == currentcell.getNodeType()) { Element cellinfo = (Element) currentcell; // get the row number from node attribute int row = Integer.parseInt(cellinfo.getAttribute("row")) - 1; // get the column number from the node attribute int col = Integer.parseInt(cellinfo.getAttribute("column")) - 1; // get content from node String content = cellinfo.getTextContent(); if (content != null) { content = content.replace("\n", ""); } // Make the content an Integer (if it is a number), easier // for // using it later on // put content in table, with row/column inserted as x/y t.setContent(row, col, (String) content); } } } catch (ParserConfigurationException e) { System.out.println("Fileparser could not be made"); } catch (IOException f) { System.out.println("File could not be parsed, did you enter the correct file name?"); } catch (SAXException g) { System.out.println("Something went wrong in parsing the file"); } return t; }
/** * Gets the definitions of a word, sets the main one if necessary, and returns it. * * @param overwrite if true, then function will attempt to retrieve from online even if the * definition is already set. * @return String containing the main definition of the word. */ public static Word[] getWordsFromFile(ByteArrayInputStream inputStream) { try { // now to parse the XML DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(inputStream); removeEmptyTextNodes(doc); NodeList wordList = doc.getElementsByTagName("WordDefinitions"); int wordCount = wordList.getLength(); Word[] returnWords = new Word[wordCount]; for (int wordi = 0; wordi < wordCount; wordi++) { NodeList list = ((Element) wordList.item(wordi)).getElementsByTagName("Definition"); Element wordElement = (Element) wordList.item(wordi); String word = wordElement.getAttribute("word"); String mainDefinition = wordElement.getAttribute("mainDefinition"); int numDefinitions = list.getLength(); Definition[] wordOtherDefinitions = new Definition[numDefinitions]; for (int i = 0; i < numDefinitions; i++) { Node node = list.item(i); NodeList children = node.getChildNodes(); // gets each child node of the definition // get all data String definition = children.item(XML_DEFINITION_LOC).getTextContent(); String theWord = children.item(XML_WORD_LOC).getTextContent(); NodeList dictionaryNode = children.item(XML_DICTIONARY_BRANCH_LOC).getChildNodes(); String dictionaryId = dictionaryNode.item(XML_DICTIONARY_ID_LOC).getTextContent(); String dictionaryName = dictionaryNode.item(XML_DICTIONARY_NAME_LOC).getTextContent(); // now we've got all the data lets add it to the array wordOtherDefinitions[i] = new Definition(dictionaryName, dictionaryId, definition, theWord); } if (wordOtherDefinitions.length == 0) { wordOtherDefinitions = new Definition[] {new Definition("nil", "nil", "NO DEFINITION FOUND", word)}; } Word currentWord = new Word(word, mainDefinition); currentWord.setOtherDefinitions(wordOtherDefinitions); returnWords[wordi] = currentWord; } return returnWords; } catch (Exception ex) { ex.printStackTrace(); return null; } }
/** * XML Circuit constructor * * @param file the file that contains the XML description of the circuit * @param g the graphics that will paint the node * @throws CircuitLoadingException if the internal circuit can not be loaded */ public CircuitUI(File file, Graphics g) throws CircuitLoadingException { this(""); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; Document doc; Element root; Hashtable<Integer, Link> linkstable = new Hashtable<Integer, Link>(); try { builder = factory.newDocumentBuilder(); doc = builder.parse(file); } catch (SAXException sxe) { throw new CircuitLoadingException("SAX exception raised, invalid XML file."); } catch (ParserConfigurationException pce) { throw new CircuitLoadingException( "Parser exception raised, parser configuration is invalid."); } catch (IOException ioe) { throw new CircuitLoadingException("I/O exception, file cannot be loaded."); } root = (Element) doc.getElementsByTagName("Circuit").item(0); this.setName(root.getAttribute("name")); NodeList nl = root.getElementsByTagName("Node"); Element e; Node n; Class cl; for (int i = 0; i < nl.getLength(); ++i) { e = (Element) nl.item(i); try { cl = Class.forName(e.getAttribute("class")); } catch (Exception exc) { System.err.println(exc.getMessage()); throw new RuntimeException("Circuit creation from xml."); } try { n = ((Node) cl.newInstance()); } catch (Exception exc) { System.err.println(exc.getMessage()); throw new RuntimeException("Circuit creation from xml."); } this.nodes.add(n); n.setLocation(new Integer(e.getAttribute("x")), new Integer(e.getAttribute("y"))); if (n instanceof giraffe.ui.Nameable) ((Nameable) n).setNodeName(e.getAttribute("node_name")); if (n instanceof giraffe.ui.CompositeNode) { try { ((CompositeNode) n) .load(new File(file.getParent() + "/" + e.getAttribute("file_name")), g); } catch (Exception exc) { /* try to load from the lib */ ((CompositeNode) n) .load(new File(giraffe.Giraffe.PATH + "/lib/" + e.getAttribute("file_name")), g); } } NodeList nlist = e.getElementsByTagName("Anchor"); Element el; for (int j = 0; j < nlist.getLength(); ++j) { el = (Element) nlist.item(j); Anchor a = n.getAnchor(new Integer(el.getAttribute("id"))); NodeList linklist = el.getElementsByTagName("Link"); Element link; Link l; for (int k = 0; k < linklist.getLength(); ++k) { link = (Element) linklist.item(k); int id = new Integer(link.getAttribute("id")); int index = new Integer(link.getAttribute("index")); if (id >= this.linkID) linkID = id + 1; if (linkstable.containsKey(id)) { l = linkstable.get(id); l.addLinkedAnchorAt(a, index); a.addLink(l); } else { l = new Link(id); l.addLinkedAnchorAt(a, index); this.links.add(l); linkstable.put(id, l); a.addLink(l); } } } } }
// ## operation readReactorOutputFile(ReactionModel) public SystemSnapshot readReactorOutputFile(ReactionModel p_reactionModel) { // #[ operation readReactorOutputFile(ReactionModel) try { // open output file and build the DOM tree String dir = System.getProperty("RMG.workingDirectory"); String filename = "chemkin/reactorOutput.xml"; File inputFile = new File(filename); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); // validate the document with the DTD factory.setIgnoringElementContentWhitespace(true); // ignore whitespace DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(inputFile); // get root element and its children Element root = doc.getDocumentElement(); NodeList rootchildren = root.getChildNodes(); // header is rootchildren.item(0) // get return message and check for successful run Element returnmessageElement = (Element) rootchildren.item(1); Text returnmessageText = (Text) returnmessageElement.getFirstChild(); String returnmessage = returnmessageText.toString(); returnmessage = returnmessage.trim(); if (!returnmessage.contains("SUCCESSFULLY COMPLETED RUN.")) { System.out.println("External reactor model failed!"); System.out.println("Reactor model error message: " + returnmessage); System.exit(0); } // get outputvalues element and its children Element outputvaluesElement = (Element) rootchildren.item(2); NodeList children = outputvaluesElement.getChildNodes(); // get time Element timeElement = (Element) children.item(0); Text timeText = (Text) timeElement.getFirstChild(); double time = Double.parseDouble(timeText.getData()); String timeUnits = timeElement.getAttribute("units"); // get systemstate element and its children Element systemstateElement = (Element) children.item(1); NodeList states = systemstateElement.getChildNodes(); // get temperature and its units Element temperatureElement = (Element) states.item(0); String tempUnits = temperatureElement.getAttribute("units"); Text temperatureText = (Text) temperatureElement.getFirstChild(); double temp = Double.parseDouble(temperatureText.getData()); Temperature T = new Temperature(temp, tempUnits); // get pressure and its units Element pressureElement = (Element) states.item(1); String presUnits = pressureElement.getAttribute("units"); Text pressureText = (Text) pressureElement.getFirstChild(); double pres = Double.parseDouble(pressureText.getData()); Pressure P = new Pressure(pres, presUnits); // get species amounts (e.g. concentrations) ArrayList speciesIDs = new ArrayList(); ArrayList amounts = new ArrayList(); ArrayList fluxes = new ArrayList(); String amountUnits = null; String fluxUnits = null; // loop thru all the species // begin at i=2, since T and P take already the first two position of states int nSpe = (states.getLength() - 2) / 2; int index = 0; LinkedHashMap inertGas = new LinkedHashMap(); for (int i = 2; i < nSpe + 2; i++) { // get amount element and the units Element amountElement = (Element) states.item(i); amountUnits = amountElement.getAttribute("units"); Element fluxElement = (Element) states.item(i + nSpe); fluxUnits = fluxElement.getAttribute("units"); // get speciesid and store in an array list String thisSpeciesID = amountElement.getAttribute("speciesid"); // get amount (e.g. concentraion) and store in an array list Text amountText = (Text) amountElement.getFirstChild(); double thisAmount = Double.parseDouble(amountText.getData()); if (thisAmount < 0) { double aTol = ReactionModelGenerator.getAtol(); // if (Math.abs(thisAmount) < aTol) thisAmount = 0; // else throw new NegativeConcentrationException("Negative concentration in // reactorOutput.xml: " + thisSpeciesID); if (thisAmount < -100.0 * aTol) throw new NegativeConcentrationException( "Species " + thisSpeciesID + " has negative concentration: " + String.valueOf(thisAmount)); } // get amount (e.g. concentraion) and store in an array list Text fluxText = (Text) fluxElement.getFirstChild(); double thisFlux = Double.parseDouble(fluxText.getData()); if (thisSpeciesID.compareToIgnoreCase("N2") == 0 || thisSpeciesID.compareToIgnoreCase("Ne") == 0 || thisSpeciesID.compareToIgnoreCase("Ar") == 0) { inertGas.put(thisSpeciesID, new Double(thisAmount)); } else { speciesIDs.add(index, thisSpeciesID); amounts.add(index, new Double(thisAmount)); fluxes.add(index, new Double(thisFlux)); index++; } } // print results for debugging purposes /** * System.out.println(returnmessage); System.out.println("Temp = " + temp + " " + tempUnits); * System.out.println("Pres = " + pres + " " + presUnits); for (int i = 0; i < amounts.size(); * i++) { System.out.println(speciesIDs.get(i) + " " + amounts.get(i) + " " + amountUnits); } */ ReactionTime rt = new ReactionTime(time, timeUnits); LinkedHashMap speStatus = generateSpeciesStatus(p_reactionModel, speciesIDs, amounts, fluxes); SystemSnapshot ss = new SystemSnapshot(rt, speStatus, T, P); ss.inertGas = inertGas; return ss; } catch (Exception e) { System.out.println("Error reading reactor model output: " + e.getMessage()); System.exit(0); return null; } // #] }
public boolean runTest(Test test) throws Exception { String filename = test.file.toString(); if (this.verbose) { System.out.println( "Running " + filename + " against " + this.host + ":" + this.port + " with " + this.browser); } this.document = parseDocument(filename); if (this.baseUrl == null) { NodeList links = this.document.getElementsByTagName("link"); if (links.getLength() != 0) { Element link = (Element) links.item(0); setBaseUrl(link.getAttribute("href")); } } if (this.verbose) { System.out.println("Base URL=" + this.baseUrl); } Node body = this.document.getElementsByTagName("body").item(0); Element resultContainer = document.createElement("div"); resultContainer.setTextContent("Result: "); Element resultElt = document.createElement("span"); resultElt.setAttribute("id", "result"); resultElt.setIdAttribute("id", true); resultContainer.appendChild(resultElt); body.insertBefore(resultContainer, body.getFirstChild()); Element executionLogContainer = document.createElement("div"); executionLogContainer.setTextContent("Execution Log:"); Element executionLog = document.createElement("div"); executionLog.setAttribute("id", "log"); executionLog.setIdAttribute("id", true); executionLog.setAttribute("style", "white-space: pre;"); executionLogContainer.appendChild(executionLog); body.appendChild(executionLogContainer); NodeList tableRows = document.getElementsByTagName("tr"); Element theadRow = (Element) tableRows.item(0); test.name = theadRow.getTextContent(); appendCellToRow(theadRow, "Result"); this.commandProcessor = new HtmlCommandProcessor(this.host, this.port, this.browser, this.baseUrl); String resultState; String resultLog; test.result = true; try { this.commandProcessor.start(); test.commands = new Command[tableRows.getLength() - 1]; for (int i = 1; i < tableRows.getLength(); i++) { Element stepRow = (Element) tableRows.item(i); Command command = executeStep(stepRow); appendCellToRow(stepRow, command.result); test.commands[i - 1] = command; if (command.error) { test.result = false; } if (command.failure) { test.result = false; // break; } } resultState = test.result ? "PASSED" : "FAILED"; resultLog = (test.result ? "Test Complete" : "Error"); this.commandProcessor.stop(); } catch (Exception e) { test.result = false; resultState = "ERROR"; resultLog = "Failed to initialize session\n" + e; e.printStackTrace(); } document.getElementById("result").setTextContent(resultState); Element log = document.getElementById("log"); log.setTextContent(log.getTextContent() + resultLog + "\n"); return test.result; }
public boolean runSuite(String filename) throws Exception { if (this.verbose) { System.out.println( "Running test suite " + filename + " against " + this.host + ":" + this.port + " with " + this.browser); } TestSuite suite = new TestSuite(); long start = System.currentTimeMillis(); suite.numTestPasses = 0; suite.file = new File(filename); File suiteDirectory = suite.file.getParentFile(); this.document = parseDocument(filename); Element table = (Element) this.document.getElementsByTagName("table").item(0); NodeList tableRows = table.getElementsByTagName("tr"); Element tableNameRow = (Element) tableRows.item(0); suite.name = tableNameRow.getTextContent(); suite.result = true; suite.tests = new Test[tableRows.getLength() - 1]; for (int i = 1; i < tableRows.getLength(); i++) { Element tableRow = (Element) tableRows.item(i); Element cell = (Element) tableRow.getElementsByTagName("td").item(0); Element link = (Element) cell.getElementsByTagName("a").item(0); Test test = new Test(); test.label = link.getTextContent(); test.file = new File(suiteDirectory, link.getAttribute("href")); SeleniumHtmlClient subclient = new SeleniumHtmlClient(); subclient.setHost(this.host); subclient.setPort(this.port); subclient.setBrowser(this.browser); // subclient.setResultsWriter(this.resultsWriter); subclient.setBaseUrl(this.baseUrl); subclient.setVerbose(this.verbose); subclient.runTest(test); if (test.result) { suite.numTestPasses++; } suite.result &= test.result; suite.tests[i - 1] = test; } long end = System.currentTimeMillis(); suite.totalTime = (end - start) / 1000; if (this.resultsWriter != null) { this.resultsWriter.write("<html><head>\n"); this.resultsWriter.write("<style type='text/css'>\n"); this.resultsWriter.write( "body, table {font-family: Verdana, Arial, sans-serif;font-size: 12;}\n"); this.resultsWriter.write("table {border-collapse: collapse;border: 1px solid #ccc;}\n"); this.resultsWriter.write("th, td {padding-left: 0.3em;padding-right: 0.3em;}\n"); this.resultsWriter.write("a {text-decoration: none;}\n"); this.resultsWriter.write(".title {font-style: italic;}"); this.resultsWriter.write(".selected {background-color: #ffffcc;}\n"); this.resultsWriter.write(".status_done {background-color: #eeffee;}\n"); this.resultsWriter.write(".status_passed {background-color: #ccffcc;}\n"); this.resultsWriter.write(".status_failed {background-color: #ffcccc;}\n"); this.resultsWriter.write( ".breakpoint {background-color: #cccccc;border: 1px solid black;}\n"); this.resultsWriter.write("</style>\n"); this.resultsWriter.write("<title>" + suite.name + "</title>\n"); this.resultsWriter.write("</head><body>\n"); this.resultsWriter.write("<h1>Test suite results </h1>\n\n"); this.resultsWriter.write("<table>\n"); this.resultsWriter.write( "<tr>\n<td>result:</td>\n<td>" + (suite.result ? "passed" : "failed") + "</td>\n</tr>\n"); this.resultsWriter.write( "<tr>\n<td>totalTime:</td>\n<td>" + suite.totalTime + "</td>\n</tr>\n"); this.resultsWriter.write( "<tr>\n<td>numTestTotal:</td>\n<td>" + suite.tests.length + "</td>\n</tr>\n"); this.resultsWriter.write( "<tr>\n<td>numTestPasses:</td>\n<td>" + suite.numTestPasses + "</td>\n</tr>\n"); int numTestFailures = suite.tests.length - suite.numTestPasses; this.resultsWriter.write( "<tr>\n<td>numTestFailures:</td>\n<td>" + numTestFailures + "</td>\n</tr>\n"); this.resultsWriter.write("<tr>\n<td>numCommandPasses:</td>\n<td>0</td>\n</tr>\n"); this.resultsWriter.write("<tr>\n<td>numCommandFailures:</td>\n<td>0</td>\n</tr>\n"); this.resultsWriter.write("<tr>\n<td>numCommandErrors:</td>\n<td>0</td>\n</tr>\n"); this.resultsWriter.write("<tr>\n<td>Selenium Version:</td>\n<td>2.24</td>\n</tr>\n"); this.resultsWriter.write("<tr>\n<td>Selenium Revision:</td>\n<td>.1</td>\n</tr>\n"); // test suite this.resultsWriter.write("<tr>\n<td>\n"); this.resultsWriter.write( "<table id=\"suiteTable\" class=\"selenium\" border=\"1\" cellpadding=\"1\" cellspacing=\"1\"><tbody>\n"); this.resultsWriter.write( "<tr class=\"title " + (suite.result ? "status_passed" : "status_failed") + "\"><td><b>Test Suite</b></td></tr>\n"); int i = 0; for (Test test : suite.tests) { this.resultsWriter.write( "<tr class=\"" + (test.result ? "status_passed" : "status_failed") + "\"><td><a href=\"#testresult" + i + "\">" + test.name + "</a></td></tr>"); i++; } this.resultsWriter.write( "</tbody></table>\n</td>\n<td> </td>\n</tr>\n</table>\n<table>"); int j = 0; for (Test test : suite.tests) { this.resultsWriter.write( "<tr><td><a name=\"testresult" + j + "\">" + test.file + "</a><br/><div>\n"); this.resultsWriter.write("<table border=\"1\" cellpadding=\"1\" cellspacing=\"1\">\n"); this.resultsWriter.write( "<thead>\n<tr class=\"title " + (test.result ? "status_passed" : "status_failed") + "\"><td rowspan=\"1\" colspan=\"3\">" + test.name + "</td></tr>"); this.resultsWriter.write("</thead><tbody>\n"); for (Command command : test.commands) { boolean result = command.result.startsWith("OK"); boolean isAssert = command.cmd.startsWith("assert") || command.cmd.startsWith("verify"); ; if (!isAssert) { this.resultsWriter.write( "<tr class=\"" + (result ? "status_done" : "") + "\">\n<td>\n"); } else { this.resultsWriter.write( "<tr class=\"" + (result ? "status_passed" : "status_failed") + "\">\n<td>\n"); } this.resultsWriter.write(command.cmd); this.resultsWriter.write("</td>\n"); if (command.args != null) { for (String arg : Arrays.asList(command.args)) { this.resultsWriter.write("<td>" + arg + "</td>\n"); } } } this.resultsWriter.write("</tr>\n"); this.resultsWriter.write("</tbody></table>\n"); this.resultsWriter.write("</div></td>\n<td> </td>\n</tr>"); j++; } int k = 0; for (Test test : suite.tests) { k++; } this.resultsWriter.write("</tbody></table>\n</td><td> </td>\n</tr>\n</table>\n"); this.resultsWriter.write("</body></html>"); } return suite.result; }
/** * Unmarshall a Chromosome instance from a given XML Element representation. * * @param a_activeConfiguration current Configuration object * @param a_xmlElement the XML Element representation of the Chromosome * @return a new Chromosome instance setup with the data from the XML Element representation * @throws ImproperXMLException if the given Element is improperly structured or missing data * @throws UnsupportedRepresentationException if the actively configured Gene implementation does * not support the string representation of the alleles used in the given XML document * @throws GeneCreationException if there is a problem creating or populating a Gene instance * @author Neil Rotstan * @since 1.0 */ public static Gene[] getGenesFromElement( Configuration a_activeConfiguration, Element a_xmlElement) throws ImproperXMLException, UnsupportedRepresentationException, GeneCreationException { // Do some sanity checking. Make sure the XML Element isn't null and // that it in fact represents a set of genes. // ----------------------------------------------------------------- if (a_xmlElement == null || !(a_xmlElement.getTagName().equals(GENES_TAG))) { throw new ImproperXMLException( "Unable to build Chromosome instance from XML Element: " + "given Element is not a 'genes' element."); } List genes = Collections.synchronizedList(new ArrayList()); // Extract the nested gene elements. // --------------------------------- NodeList geneElements = a_xmlElement.getElementsByTagName(GENE_TAG); if (geneElements == null) { throw new ImproperXMLException( "Unable to build Gene instances from XML Element: " + "'" + GENE_TAG + "'" + " sub-elements not found."); } // For each gene, get the class attribute so we know what class // to instantiate to represent the gene instance, and then find // the child text node, which is where the string representation // of the allele is located, and extract the representation. // ------------------------------------------------------------- int numberOfGeneNodes = geneElements.getLength(); for (int i = 0; i < numberOfGeneNodes; i++) { Element thisGeneElement = (Element) geneElements.item(i); thisGeneElement.normalize(); // Fetch the class attribute and create an instance of that // class to represent the current gene. // -------------------------------------------------------- String geneClassName = thisGeneElement.getAttribute(CLASS_ATTRIBUTE); Gene thisGeneObject; Class geneClass = null; try { geneClass = Class.forName(geneClassName); try { Constructor constr = geneClass.getConstructor(new Class[] {Configuration.class}); thisGeneObject = (Gene) constr.newInstance(new Object[] {a_activeConfiguration}); } catch (NoSuchMethodException nsme) { // Try it by calling method newGeneInternal. // ----------------------------------------- Constructor constr = geneClass.getConstructor(new Class[] {}); thisGeneObject = (Gene) constr.newInstance(new Object[] {}); thisGeneObject = (Gene) PrivateAccessor.invoke( thisGeneObject, "newGeneInternal", new Class[] {}, new Object[] {}); } } catch (Throwable e) { throw new GeneCreationException(geneClass, e); } // Find the text node and fetch the string representation of // the allele. // --------------------------------------------------------- NodeList children = thisGeneElement.getChildNodes(); int childrenSize = children.getLength(); String alleleRepresentation = null; for (int j = 0; j < childrenSize; j++) { Element alleleElem = (Element) children.item(j); if (alleleElem.getTagName().equals(ALLELE_TAG)) { alleleRepresentation = alleleElem.getAttribute("value"); } if (children.item(j).getNodeType() == Node.TEXT_NODE) { // We found the text node. Extract the representation. // --------------------------------------------------- alleleRepresentation = children.item(j).getNodeValue(); break; } } // Sanity check: Make sure the representation isn't null. // ------------------------------------------------------ if (alleleRepresentation == null) { throw new ImproperXMLException( "Unable to build Gene instance from XML Element: " + "value (allele) is missing representation."); } // Now set the value of the gene to that reflect the // string representation. // ------------------------------------------------- try { thisGeneObject.setValueFromPersistentRepresentation(alleleRepresentation); } catch (UnsupportedOperationException e) { throw new GeneCreationException( "Unable to build Gene because it does not support the " + "setValueFromPersistentRepresentation() method."); } // Finally, add the current gene object to the list of genes. // ---------------------------------------------------------- genes.add(thisGeneObject); } return (Gene[]) genes.toArray(new Gene[genes.size()]); }