public apiParser(String sdkfile) { System.out.println(sdkfile); File file = new File(sdkfile); try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(file); NodeList apiList = doc.getElementsByTagName("n1:api"); NodeList inputList = doc.getElementsByTagName("n1:input"); NodeList typeList = doc.getElementsByTagName("n1:type"); for (int i = 0; i < apiList.getLength(); i++) { Node api_node = apiList.item(i); String api_id = api_node.getAttributes().getNamedItem("id").getNodeValue(); String api_name = api_node.getAttributes().getNamedItem("name").getNodeValue(); String input_type_id = inputList.item(i).getAttributes().getNamedItem("type_ref").getNodeValue(); // System.out.println(api_id + " : " + api_name + " : " + input_type_id); ArrayList<String> api_params = new ArrayList<String>(); for (int j = 0; j < typeList.getLength(); j++) { if (input_type_id.equalsIgnoreCase( typeList.item(j).getAttributes().getNamedItem("id").getNodeValue())) { Element e1 = (Element) typeList.item(j); NodeList param_l = e1.getElementsByTagName("n1:param"); for (int k = 0; k < param_l.getLength(); k++) { String param_name = param_l.item(k).getAttributes().getNamedItem("name").getNodeValue(); // String param_desc = // param_l.item(k).getAttributes().getNamedItem("desc").getNodeValue(); api_params.add(param_name); // System.out.println(param_name +":"+param_desc); } break; } } apiRoom s_room = new apiRoom(api_id, api_name, api_params); apiRooms.add(s_room); } } catch (Exception e) { e.printStackTrace(); } }
// Lee la configuracion que se encuentra en conf/RegistryConf private void readConfXml() { try { File inputFile = new File("src/java/Conf/RegistryConf.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(inputFile); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("RegistryConf"); for (int i = 0; i < nList.getLength(); i++) { Node nNode = nList.item(i); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; RegistryConf reg = new RegistryConf(); String aux; int idSensor; int value; aux = eElement.getElementsByTagName("idSensor").item(0).getTextContent(); idSensor = Integer.parseInt(aux); reg.setIdSensor(idSensor); aux = eElement.getElementsByTagName("saveType").item(0).getTextContent(); reg.setSaveTypeString(aux); aux = eElement.getElementsByTagName("value").item(0).getTextContent(); value = Integer.parseInt(aux); reg.setValue(value); registryConf.add(reg); lastRead.put(idSensor, 0); } } } catch (Exception e) { e.printStackTrace(); } }
public List parsePage(String pageCode) { List sections = new ArrayList(); List folders = new ArrayList(); List files = new ArrayList(); int start = pageCode.indexOf("<div id=\"list-view\" class=\"view\""); int end = pageCode.indexOf("<div id=\"gallery-view\" class=\"view\""); String usefulSection = ""; if (start != -1 && end != -1) { usefulSection = pageCode.substring(start, end); } else { debug("Could not parse page"); } try { DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(usefulSection)); Document doc = db.parse(is); NodeList divs = doc.getElementsByTagName("div"); for (int i = 0; i < divs.getLength(); i++) { Element div = (Element) divs.item(i); boolean isFolder = false; if (div.getAttribute("class").equals("filename")) { NodeList imgs = div.getElementsByTagName("img"); for (int j = 0; j < imgs.getLength(); j++) { Element img = (Element) imgs.item(j); if (img.getAttribute("class").indexOf("folder") > 0) { isFolder = true; } else { isFolder = false; // it's a file } } NodeList anchors = div.getElementsByTagName("a"); Element anchor = (Element) anchors.item(0); String attr = anchor.getAttribute("href"); String fileName = anchor.getAttribute("title"); String fileURL; if (isFolder && !attr.equals("#")) { folders.add(attr); folders.add(fileName); } else if (!isFolder && !attr.equals("#")) { // Dropbox uses ajax to get the file for download, so the url isn't enough. We must be // sneaky here. fileURL = "https://dl.dropbox.com" + attr.substring(23) + "?dl=1"; files.add(fileURL); files.add(fileName); } } } } catch (Exception e) { debug(e.toString()); } sections.add(files); sections.add(folders); return sections; }
public String getProperty(String pPropertyName) { String propertyValue = null; NodeList nodeList = mConfigFileDocument.getElementsByTagName(pPropertyName); int nodeListLength = nodeList.getLength(); if (nodeListLength > 0) { Node firstChildNode = nodeList.item(nodeListLength - 1).getFirstChild(); if (null != firstChildNode) { propertyValue = firstChildNode.getNodeValue(); } } return (propertyValue); }
public void read(Document doc) { try { Element root = doc.getDocumentElement(); NodeList nList = doc.getElementsByTagName("user"); for (int i = 0; i < nList.getLength(); i++) { Node node = nList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; } } // Element e1 = (Element) nList.item(0); } catch (Exception e) { } }
public void handleDocument(Document document) { /* Tutti i nodi contenuti in document che si chiamano "NodoCella" */ NodeList cas = document.getElementsByTagName("NodoCella"); Element casellona = (Element) cas.item(0); id = casellona.getElementsByTagName("id").item(0).getTextContent(); x = casellona.getElementsByTagName("XCOR").item(0).getTextContent(); y = casellona.getElementsByTagName("YCOR").item(0).getTextContent(); text = casellona.getElementsByTagName("text").item(0).getTextContent(); down = casellona.getElementsByTagName("down").item(0).getTextContent(); up = casellona.getElementsByTagName("up").item(0).getTextContent(); laterale = casellona.getElementsByTagName("laterale").item(0).getTextContent(); laterale1 = casellona.getElementsByTagName("laterale1").item(0).getTextContent(); laterale2 = casellona.getElementsByTagName("laterale2").item(0).getTextContent(); laterale3 = casellona.getElementsByTagName("laterale3").item(0).getTextContent(); laterale4 = casellona.getElementsByTagName("laterale4").item(0).getTextContent(); laterale5 = casellona.getElementsByTagName("laterale5").item(0).getTextContent(); laterale6 = casellona.getElementsByTagName("laterale6").item(0).getTextContent(); CasellaStart casella_start = new CasellaStart( id, text, x, y, down, up, laterale, laterale1, laterale2, laterale3, laterale4, laterale5, laterale6); GestioneCaselle.caselle.add(casella_start); for (int i = 0; i < cas.getLength(); i++) { Element casella = (Element) cas.item(i); id = casella.getElementsByTagName("id").item(0).getTextContent(); x = casella.getElementsByTagName("XCOR").item(0).getTextContent(); y = casella.getElementsByTagName("YCOR").item(0).getTextContent(); text = casella.getElementsByTagName("text").item(0).getTextContent(); down = casella.getElementsByTagName("down").item(0).getTextContent(); up = casella.getElementsByTagName("up").item(0).getTextContent(); laterale = casella.getElementsByTagName("laterale").item(0).getTextContent(); Casella nuova_casella = new Casella(id, text, x, y, down, up, laterale); GestioneCaselle.caselle.add(nuova_casella); } // this.caselle.remove(1); casella_start.setLaterali(); }
/** * 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; }
public static void main(String[] args) { System.out.println("--------Part 1-------------------------------"); Document xmlDoc = getDocument("SigmodRecord.xml"); int issue_length = xmlDoc.getElementsByTagName("issue").getLength(); NodeList issue_node = xmlDoc.getElementsByTagName("issue"); for (int i = 0; i < issue_length; i++) { Node nnode = issue_node.item(i); if (nnode.getNodeType() == Element.ELEMENT_NODE) { Element enode = (Element) nnode; String vol_element = enode.getElementsByTagName("volume").item(0).getTextContent(); String num_element = enode.getElementsByTagName("number").item(0).getTextContent(); if (vol_element.equals("13") && num_element.equals("4")) { NodeList article_node = xmlDoc.getElementsByTagName("article"); int article_length = xmlDoc.getElementsByTagName("article").getLength(); for (int j = 0; j < article_length; j++) { Node m = article_node.item(j); if (m.getNodeType() == Element.ELEMENT_NODE) { Element f = (Element) m; String auth = f.getElementsByTagName("author").item(0).getTextContent(); if (auth.equals("David Maier")) { String title = f.getElementsByTagName("title").item(0).getTextContent(); System.out.println("Title: " + title); } } } } } } // Part 2 of the Program (Print the author names off all articles whose title contains the word // "database" or "Database".) System.out.println("--------Part 2------------------------------- "); NodeList article_node = xmlDoc.getElementsByTagName("article"); int article_length = xmlDoc.getElementsByTagName("article").getLength(); for (int j = 0; j < article_length; j++) { Node m = article_node.item(j); if (m.getNodeType() == Element.ELEMENT_NODE) { Element f = (Element) m; String article = f.getElementsByTagName("title").item(0).getTextContent(); if (article.contains("Database") || article.contains("database")) { int length = f.getElementsByTagName("author").getLength(); for (int i = 0; i < length; i++) { String auth = f.getElementsByTagName("author").item(i).getTextContent(); System.out.println("Author: " + auth); } } } } // Part 3 of the Program (Print the volume/number and the init/end pages of the article titled // "Research in Knowledge Base Management Systems.".) System.out.println("--------Part 3------------------------------- "); vol(issue_length, issue_node); }
public XMLHelper(String filename, String root) { this(); try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); try { Document document = builder.parse(new File(filename)); setElement((Element) document.getElementsByTagName(root).item(0)); } catch (Exception e) { Document document = builder.newDocument(); setElement((Element) document.appendChild(document.createElement(root))); warning("Could not load XML file: " + e.getMessage()); } } catch (ParserConfigurationException e) { // Not quite sure when this would happen severe("Could not extantiate XML builder: " + e.getMessage()); } }
public ServiceMap parse(Document document) { Map<String, String> map = new HashMap<String, String>(); Map<String, String> publicMap = new HashMap<String, String>(); NodeList servicesNodes = document.getElementsByTagName("service"); for (int i = 0; i < servicesNodes.getLength(); i++) { Element node = (Element) servicesNodes.item(i); if (node.hasAttribute("class") && node.hasAttribute("id")) { map.put(node.getAttribute("id"), "\\" + node.getAttribute("class")); } if (!(node.hasAttribute("public") && node.getAttribute("public").equals("false"))) { publicMap.put(node.getAttribute("id"), "\\" + node.getAttribute("class")); } } // Support services whose class isn't specified populateMapWithDefaultServices(map); populateMapWithDefaultServices(publicMap); return new ServiceMap(map, publicMap); }
// http://www.java-tips.org/java-se-tips/javax.xml.parsers/how-to-read-xml-file-in-java.html private double my_ListParser(int itIs) { double[] my_list = new double[3]; try { File fXmlFile = new File("/Users/alexiaKourfali/NetBeansProjects/mav_project3_part2/web/my_list.xml"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(fXmlFile); doc.getDocumentElement().normalize(); // System.out.println("Root element " + doc.getDocumentElement().getNodeName()); NodeList nodeLst = doc.getElementsByTagName("Entry"); for (int s = 0; s < nodeLst.getLength(); s++) { Node fstNode = nodeLst.item(s); if (fstNode.getNodeType() == Node.ELEMENT_NODE) { Element fstElmnt = (Element) fstNode; NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("Price"); Element fstNmElmnt = (Element) fstNmElmntLst.item(0); NodeList fstNm = fstNmElmnt.getChildNodes(); Node nV = (Node) fstNm.item(0); /*not sureeeee*/ my_list[s] = Double.parseDouble(nV.getNodeValue()); } } } catch (Exception e) { } if (itIs == 0) return my_list[0]; if (itIs == 1) return my_list[1]; else return my_list[2]; }
private static void parseXML() { try { Document doc = DocumentBuilderFactory.newInstance() .newDocumentBuilder() .parse(CommandBuilder.class.getResourceAsStream("/CommandMap.xml")); NodeList nodes = doc.getElementsByTagName("CommandMap"); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); NamedNodeMap atts = n.getAttributes(); String rootCommand = atts.getNamedItem("rootCommand").getNodeValue(); rootNode = new Category(rootCommand, ""); NodeList children = n.getChildNodes(); for (int p = 0; p < children.getLength(); p++) { parseNode(children.item(p), rootNode); } } } catch (Exception e) { e.printStackTrace(); } }
public String getFolderName(String pageCode) { String usefulSection = pageCode.substring( pageCode.indexOf("<h3 id=\"breadcrumb\">"), pageCode.indexOf("<div id=\"list-view\" class=\"view\"")); String folderName; try { DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(usefulSection)); Document doc = db.parse(is); NodeList divs = doc.getElementsByTagName("h3"); for (int i = 0; i < divs.getLength(); i++) { Element div = (Element) divs.item(i); String a = div.getTextContent(); folderName = a.substring(a.indexOf("/>") + 2).trim(); return folderName; } } catch (Exception e) { debug(e.toString()); } return "Error!"; }
// ----------------------------------------------------- // Description: Determine if a template exists for the // given file and return true on success. // ----------------------------------------------------- boolean templateExistFor(String fileName, String destinationDirectory) { templateIdentified = false; // from template int intOriginX = 0; int intOriginY = 0; // from template int intX = 0; int intY = 0; int intWidth = 0; int intHeight = 0; // calculated int viaTemplateX = 0; int viaTemplateY = 0; int viaTemplatePlusWidth = 0; int viaTemplatePlusHeight = 0; String fileName_woext = fileName.substring(0, fileName.lastIndexOf('.')); String pathPlusFileName_woext = destinationDirectory + File.separator + fileName_woext + File.separator + fileName_woext; try { File folder = new File(templateLocation); File[] listOfFiles = folder.listFiles(); long startTime = System.currentTimeMillis(); for (File file : listOfFiles) { if (file.isFile()) { templateName = ""; DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(file); doc.getDocumentElement().normalize(); System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("condition"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String myX = getTagValue("x", eElement); String myY = getTagValue("y", eElement); String myWidth = getTagValue("width", eElement); String myHeight = getTagValue("height", eElement); String mySuffix = getTagValue("suffix", eElement); String myRequirements = getTagValue("required", eElement); intX = Integer.parseInt(myX); intY = Integer.parseInt(myY); intWidth = Integer.parseInt(myWidth); intHeight = Integer.parseInt(myHeight); viaTemplateX = intX - (intOriginX - pageX); viaTemplateY = intY - (intOriginY - pageY); viaTemplatePlusWidth = viaTemplateX + intWidth; viaTemplatePlusHeight = viaTemplateY + intHeight; Spawn.execute( Settings.Programs.CONVERT.path(), pathPlusFileName_woext + "_trim.png", "-crop", String.format("%dx%d+%d+%d", intWidth, intHeight, viaTemplateX, viaTemplateY), "+repage", pathPlusFileName_woext + "_" + mySuffix + ".png"); Spawn.execute( Settings.Programs.CONVERT.path(), pathPlusFileName_woext + "_trim.png", "-fill", "none", "-stroke", "red", "-strokewidth", "3", "-draw", String.format( "rectangle %d,%d %d,%d", viaTemplateX, viaTemplateY, viaTemplatePlusWidth, viaTemplatePlusHeight), "+repage", pathPlusFileName_woext + "_draw.png"); Spawn.execute( Settings.Programs.TESSERACT.path(), pathPlusFileName_woext + "_" + mySuffix + ".png", pathPlusFileName_woext + "_" + mySuffix); String line = ""; // String that holds current file line String accumulate = ""; try { FileReader input = new FileReader(pathPlusFileName_woext + "_" + mySuffix + ".txt"); BufferedReader bufRead = new BufferedReader(input); line = bufRead.readLine(); while (line != null) { accumulate += line; line = bufRead.readLine(); } bufRead.close(); input.close(); } catch (IOException e) { e.printStackTrace(); } String[] requirements = myRequirements.split("#"); for (String requirement : requirements) { if (requirement.equals(accumulate.trim())) { templateName = file.getName(); templateIdentified = true; return templateIdentified; } } } } } } // record end time long endTime = System.currentTimeMillis(); System.out.println( "Template Search [" + fileName + "] " + (endTime - startTime) / 1000 + " seconds"); } catch (Exception e) { e.printStackTrace(); } return templateIdentified; }
/** * 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); } } } } }
// ----------------------------------------------------- // Description: Using the specified template, create // csv records corresponding to the output xml criteria. // ----------------------------------------------------- void transformWithTemplate(String templateName, String fileName, String destinationDirectory) { System.out.println("fileName = " + fileName); String fileName_woext = fileName.substring(0, fileName.lastIndexOf('.')); try { File fXmlFile = new File(templateLocation, templateName); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("output"); // loop through all the output nodes for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String outputLine = getTagValue("line", eElement); FileWriter output = new FileWriter( destinationDirectory + File.separator + fileName_woext.substring(0, fileName.lastIndexOf('_')) + ".csv", true); BufferedWriter bufWrite = new BufferedWriter(output); System.out.println( destinationDirectory + File.separator + fileName_woext.substring(0, fileName.lastIndexOf("_")) + ".csv"); if (Settings.optionalIdentifier != null) { bufWrite.write("\"" + Settings.optionalIdentifier + "\""); } String[] outputItems = outputLine.split("#"); for (String outputItem : outputItems) { if ((temp == 0) && (Settings.optionalIdentifier == null)) { bufWrite.write( "\"" + interpretText(destinationDirectory, fileName_woext, outputItem) + "\""); } else { bufWrite.write( ",\"" + interpretText(destinationDirectory, fileName_woext, outputItem) + "\""); } } bufWrite.write("\r\n"); bufWrite.close(); output.close(); } } } catch (Exception e) { e.printStackTrace(); } }
void xml() { try { File file = new File("c:\\users\\jason\\desktop\\proxies.xml"); // Create instance of DocumentBuilderFactory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // Get the DocumentBuilder DocumentBuilder docBuilder = factory.newDocumentBuilder(); // Using existing XML Document Document doc = docBuilder.parse(file); // normalize the text doc.getDocumentElement().normalize(); // gets just the name of the root String simple_root = doc.getDocumentElement().getNodeName(); Element root = doc.getDocumentElement(); // gets the ip elements NodeList proxy = doc.getElementsByTagName("proxy"); // checks the make sure i got the ip elements by printing out the number of occurances int total = proxy.getLength(); NodeList list = doc.getElementsByTagName("*"); System.out.println("\nElements in the proxy file:"); int proxy_num = 1; for (int i = 0; i < list.getLength(); i++) { Node num2 = proxy.item(i); Element second = (Element) num2; Element element2 = (Element) list.item(i); NodeList text2 = element2.getChildNodes(); if (element2.getNodeName() != "proxies" && element2.getNodeName() != "proxy") { if (element2.getNodeName() == "ip") { System.out.println(""); System.out.println("Proxy #: " + proxy_num); proxy_num++; System.out.println( element2.getNodeName() + ": " + ((Node) text2.item(0)).getNodeValue().trim()); } else System.out.println( element2.getNodeName() + ": " + ((Node) text2.item(0)).getNodeValue().trim()); if (element2.getNodeName() == "source-ip") { ip = ((Node) text2.item(0)).getNodeValue().trim(); myArr.add(ip); jComboBox.addItem(ip); } } } // set up a transformer TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); // create string from xml tree StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(doc); trans.transform(source, result); String xmlString = sw.toString(); OutputStream f0; byte buf[] = xmlString.getBytes(); f0 = new FileOutputStream("c:\\users\\jason\\desktop\\connections.xml"); for (int i = 0; i < buf.length; i++) { f0.write(buf[i]); } f0.close(); buf = null; } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } }
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; }
// ----------------------------------------------------- // Description: Using the specified template, extract // the template sections into PNG and TXT corresponding // parts. // ----------------------------------------------------- void extractWithTemplate(String templateName, String fileName, String destinationDirectory) { // from template int intOriginX = 0; int intOriginY = 0; // from template int intX = 0; int intY = 0; int intWidth = 0; int intHeight = 0; // calculated int viaTemplateX = 0; int viaTemplateY = 0; int viaTemplatePlusWidth = 0; int viaTemplatePlusHeight = 0; System.out.println("fileName = " + fileName); String fileName_woext = fileName.substring(0, fileName.lastIndexOf('.')); String pathPlusFileName_woext = destinationDirectory + File.separator + fileName_woext + File.separator + fileName_woext; System.out.println("pathPlusFileName_woext = " + pathPlusFileName_woext); try { File fXmlFile = new File(templateLocation, templateName); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("section"); Node nNode; for (int temp = 0; temp < nList.getLength(); temp++) { nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String myX = getTagValue("x", eElement); String myY = getTagValue("y", eElement); String myWidth = getTagValue("width", eElement); String myHeight = getTagValue("height", eElement); String mySuffix = getTagValue("suffix", eElement); intX = Integer.parseInt(myX); intY = Integer.parseInt(myY); intWidth = Integer.parseInt(myWidth); intHeight = Integer.parseInt(myHeight); viaTemplateX = intX - (intOriginX - pageX); viaTemplateY = intY - (intOriginY - pageY); viaTemplatePlusWidth = viaTemplateX + intWidth; viaTemplatePlusHeight = viaTemplateY + intHeight; Spawn.execute( Settings.Programs.CONVERT.path(), pathPlusFileName_woext + "_trim.png", "-crop", String.format("%dx%d+%d+%d", intWidth, intHeight, viaTemplateX, viaTemplateY), "+repage", pathPlusFileName_woext + "_" + mySuffix + ".png"); Spawn.execute( Settings.Programs.CONVERT.path(), pathPlusFileName_woext + "_trim.png", "-fill", "none", "-stroke", "red", "-strokewidth", "3", "-draw", String.format( "rectangle %d,%d %d,%d", viaTemplateX, viaTemplateY, viaTemplatePlusWidth, viaTemplatePlusHeight), "+repage", pathPlusFileName_woext + "_draw.png"); Spawn.execute( Settings.Programs.TESSERACT.path(), pathPlusFileName_woext + "_" + mySuffix + ".png", pathPlusFileName_woext + "_" + mySuffix); } } } catch (Exception e) { e.printStackTrace(); } }
/** * Restituisce la lista delle sale specificate nel file di configurazione * * @param d - riferimento al file XML * @return NodeList degli oggetti hall */ private static NodeList findCinemaHall(Document d) { return d.getElementsByTagName("hall"); }