private void addRunConfigurationFromXMLTree(Element treeTop, String runManagerName) { NodeList list = treeTop.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { NamedNodeMap nodeMap = list.item(i).getAttributes(); if (nodeMap != null && nodeMap.getNamedItem("name") != null) { if (!runManagerName.equals(nodeMap.getNamedItem("name").getNodeValue())) { continue; } NodeList configList = list.item(i).getChildNodes(); for (int j = 0; j < configList.getLength(); j++) { NamedNodeMap configNodeMap = configList.item(j).getAttributes(); if (configNodeMap != null && configNodeMap.getNamedItem("default") != null && configNodeMap.getNamedItem("default").getNodeValue() != null && configNodeMap.getNamedItem("default").getNodeValue().equals("false")) { try { runConfigurations.add(new ASIdeaRunConfiguration(configList.item(j))); } catch (ASExternalImporterException e) { // Ignore } } } } } }
public ArrayList<String> parseXML() throws Exception { ArrayList<String> ret = new ArrayList<String>(); handshake(); URL url = new URL( "http://mangaonweb.com/page.do?cdn=" + cdn + "&cpn=book.xml&crcod=" + crcod + "&rid=" + (int) (Math.random() * 10000)); String page = DownloaderUtils.getPage(url.toString(), "UTF-8", cookies); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(page)); Document d = builder.parse(is); Element doc = d.getDocumentElement(); NodeList pages = doc.getElementsByTagName("page"); total = pages.getLength(); for (int i = 0; i < pages.getLength(); i++) { Element e = (Element) pages.item(i); ret.add(e.getAttribute("path")); } return (ret); }
private void buildHierarchyDOM() { TransformerFactory factory = TransformerFactory.newInstance(); StreamSource src = new StreamSource( this.getServletContext() .getResourceAsStream("/WEB-INF/classes/gpt/search/browse/ownerHierarchy.xml")); log.info("initializing src from stream " + src); try { Transformer t = factory.newTransformer(); dom = new DOMResult(); t.transform(src, dom); // now go thru tree, setting up the query attribute for each node Node tree = dom.getNode(); NodeList children = tree.getChildNodes(); log.info("dom tree contains " + children.getLength() + " nodes"); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { Element e = (Element) child; String query = computeQuery(e); e.setAttribute("query", query); } } } catch (Exception e) { log.severe("Could not init ownerHierarchy because exception thrown:"); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); log.severe(sw.toString()); } }
private static IPeakSet<? extends IPeak> parsePeakSet(Node parent) throws XmlParserException { // retrieve all the properties Vector<IPeak> peaks = new Vector<IPeak>(); NodeList nodes = parent.getChildNodes(); for (int nodeid = 0; nodeid < nodes.getLength(); ++nodeid) { Node node = nodes.item(nodeid); if (node.getNodeType() != Node.ELEMENT_NODE) continue; Element element = (Element) node; if (element.getTagName().equals("peaks")) { NodeList nodes2 = node.getChildNodes(); for (int nodeid2 = 0; nodeid2 < nodes2.getLength(); ++nodeid2) { Node node2 = nodes2.item(nodeid2); if (node2.getNodeType() != Node.ELEMENT_NODE) continue; IPeak peak = parseIPeak(node2); if (peak != null) peaks.add(peak); } } } // create the bugger IPeakSet<IPeak> peakset = new IPeakSet<IPeak>(peaks); parseIPeak(parent, peakset); return peakset; }
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; }
void lookup(String text) { NodeList nl = DOMInfoExtractor.locateNodes(document, ".//text()[contains(.,'" + text + "')]"); System.out.println("find " + nl.getLength() + " items"); FoundItem[] fis = new FoundItem[nl.getLength()]; for (int i = 0; i < nl.getLength(); i++) { fis[i] = getFoundItem(nl.item(i), text); } foundList.setListData(fis); }
/** * Carries out preprocessing that makes JEuclid handle the document better. * * @param doc Document */ static void preprocessForJEuclid(Document doc) { // underbrace and overbrace NodeList list = doc.getElementsByTagName("mo"); for (int i = 0; i < list.getLength(); i++) { Element mo = (Element) list.item(i); String parentName = ((Element) mo.getParentNode()).getTagName(); if (parentName == null) { continue; } if (parentName.equals("munder") && isTextChild(mo, "\ufe38")) { mo.setAttribute("stretchy", "true"); mo.removeChild(mo.getFirstChild()); mo.appendChild(doc.createTextNode("\u23df")); } else if (parentName.equals("mover") && isTextChild(mo, "\ufe37")) { mo.setAttribute("stretchy", "true"); mo.removeChild(mo.getFirstChild()); mo.appendChild(doc.createTextNode("\u23de")); } } // menclose for long division doesn't allow enough top padding. Oh, and // <mpadded> isn't implemented. And there isn't enough padding to left of // the bar either. Solve by adding an <mover> with just an <mspace> over# // the longdiv, contained within an mrow that adds a <mspace> before it. list = doc.getElementsByTagName("menclose"); for (int i = 0; i < list.getLength(); i++) { Element menclose = (Element) list.item(i); // Only for longdiv if (!"longdiv".equals(menclose.getAttribute("notation"))) { continue; } Element mrow = doc.createElementNS(WebMathsService.NS, "mrow"); Element mover = doc.createElementNS(WebMathsService.NS, "mover"); Element mspace = doc.createElementNS(WebMathsService.NS, "mspace"); Element mspaceW = doc.createElementNS(WebMathsService.NS, "mspace"); boolean previousElement = false; for (Node previous = menclose.getPreviousSibling(); previous != null; previous = previous.getPreviousSibling()) { if (previous.getNodeType() == Node.ELEMENT_NODE) { previousElement = true; break; } } if (previousElement) { mspaceW.setAttribute("width", "4px"); } menclose.getParentNode().insertBefore(mrow, menclose); menclose.getParentNode().removeChild(menclose); mrow.appendChild(mspaceW); mrow.appendChild(mover); mover.appendChild(menclose); mover.appendChild(mspace); } }
private void loadFromXml(String fileName) throws ParserConfigurationException, SAXException, IOException, ParseException { System.out.println("NeuralNetwork : loading network topology from file " + fileName); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(fileName); Node nodeNeuralNetwork = doc.getDocumentElement(); if (!nodeNeuralNetwork.getNodeName().equals("neuralNetwork")) throw new ParseException( "[Error] NN-Load: Parse error in XML file, neural network couldn't be loaded.", 0); // nodeNeuralNetwork ok // indexNeuralNetworkContent -> indexStructureContent -> indexLayerContent -> indexNeuronContent // -> indexNeuralInputContent NodeList nodeNeuralNetworkContent = nodeNeuralNetwork.getChildNodes(); for (int innc = 0; innc < nodeNeuralNetworkContent.getLength(); innc++) { Node nodeStructure = nodeNeuralNetworkContent.item(innc); if (nodeStructure.getNodeName().equals("structure")) { // for structure element NodeList nodeStructureContent = nodeStructure.getChildNodes(); for (int isc = 0; isc < nodeStructureContent.getLength(); isc++) { Node nodeLayer = nodeStructureContent.item(isc); if (nodeLayer.getNodeName().equals("layer")) { // for layer element NeuralLayer neuralLayer = new NeuralLayer(this); this.listLayers.add(neuralLayer); NodeList nodeLayerContent = nodeLayer.getChildNodes(); for (int ilc = 0; ilc < nodeLayerContent.getLength(); ilc++) { Node nodeNeuron = nodeLayerContent.item(ilc); if (nodeNeuron.getNodeName().equals("neuron")) { // for neuron in layer Neuron neuron = new Neuron( Double.parseDouble(((Element) nodeNeuron).getAttribute("threshold")), neuralLayer); neuralLayer.listNeurons.add(neuron); NodeList nodeNeuronContent = nodeNeuron.getChildNodes(); for (int inc = 0; inc < nodeNeuronContent.getLength(); inc++) { Node nodeNeuralInput = nodeNeuronContent.item(inc); // if (nodeNeuralInput==null) System.out.print("-"); else System.out.print("*"); if (nodeNeuralInput.getNodeName().equals("input")) { // System.out.println("neuron at // STR:"+innc+" LAY:"+isc+" NEU:"+ilc+" INP:"+inc); NeuralInput neuralInput = new NeuralInput( Double.parseDouble(((Element) nodeNeuralInput).getAttribute("weight")), neuron); neuron.listInputs.add(neuralInput); } } } } } } } } }
void lookupByXPath(String xpath) { NodeList nl = DOMInfoExtractor.locateNodes(document, xpath); System.out.println("lookupByXPath: " + xpath); if (nl == null) { JOptionPane.showMessageDialog(this, "error xpath: " + xpath); } System.out.println("find " + nl.getLength() + " items"); FoundItem[] fis = new FoundItem[nl.getLength()]; for (int i = 0; i < nl.getLength(); i++) { fis[i] = getFoundItem(nl.item(i), null); } foundList.setListData(fis); }
// 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(); } }
// read all defense missiles from given id protected void readDefensDestructoreMissiles(NodeList missiles, String whoLaunchMeId) { String targetId, destructTimeCheck; int destructTime; int size = missiles.getLength(); for (int i = 0; i < size; i++) { Element missile = (Element) missiles.item(i); targetId = missile.getAttribute("id"); destructTimeCheck = missile.getAttribute("destructAfterLaunch"); if (destructTimeCheck.equals("")) destructTimeCheck = missile.getAttribute("destructTime"); try { destructTime = Integer.parseInt(destructTimeCheck); } catch (NumberFormatException e) { destructTime = -1; // System.out.println(e.getStackTrace()); } // create the thread of the missile createDefenseMissile(whoLaunchMeId, targetId, destructTime); } }
private static MeasurementInfo parseMeasurement(Node parent) throws XmlParserException { String id = ""; String label = ""; String sampleid = ""; Vector<FileInfo> files = null; Vector<ScanInfo> scans = null; NodeList nodes = parent.getChildNodes(); for (int nodeid = 0; nodeid < nodes.getLength(); ++nodeid) { Node node = nodes.item(nodeid); if (node.getNodeType() != Node.ELEMENT_NODE) continue; Element element = (Element) node; if (element.getTagName().equals("id")) id = element.getTextContent(); else if (element.getTagName().equals("label")) label = element.getTextContent(); else if (element.getTagName().equals("sampleid")) sampleid = element.getTextContent(); else if (element.getTagName().equals("scans")) scans = parseScans(node); else if (element.getTagName().equals("files")) files = parseFiles(node); } MeasurementInfo measurement = new MeasurementInfo(Integer.parseInt(id), sampleid); measurement.setLabel(label); measurement.addFileInfos(files); if (scans != null) measurement.addScanInfos(scans); return measurement; }
private static SetInfo parseSet(Node parent) throws XmlParserException { String id = ""; String type = ""; String measurementids = null; NodeList nodes = parent.getChildNodes(); Vector<SetInfo> sets = new Vector<SetInfo>(); for (int nodeid = 0; nodeid < nodes.getLength(); ++nodeid) { Node node = nodes.item(nodeid); if (node.getNodeType() != Node.ELEMENT_NODE) continue; Element element = (Element) node; if (element.getTagName().equals("id")) id = element.getTextContent(); else if (element.getTagName().equals("set")) sets.add(parseSet(element)); else if (element.getTagName().equals("type")) type = element.getTextContent(); else if (element.getTagName().equals("measurementids")) measurementids = element.getTextContent(); } // create the set SetInfo set = new SetInfo(id, Integer.parseInt(type)); if (measurementids != null) { int mids[] = ByteArray.toIntArray(Base64.decode(measurementids), ByteArray.ENDIAN_LITTLE, 32); for (int mid : mids) set.addMeasurementID(mid); } // add the children for (SetInfo s : sets) set.addChild(s); return set; }
private static Header parseHeader(Node parent) throws XmlParserException { Header header = new Header(); NodeList nodes = parent.getChildNodes(); for (int nodeid = 0; nodeid < nodes.getLength(); ++nodeid) { Node node = nodes.item(nodeid); if (node.getNodeType() != Node.ELEMENT_NODE) continue; Element element = (Element) node; try { if (element.getTagName().equals("nrpeaks")) header.setNrPeaks(Integer.parseInt(element.getTextContent())); else if (element.getTagName().equals("date")) header.setDate(element.getTextContent()); else if (element.getTagName().equals("owner")) header.setOwner(element.getTextContent()); else if (element.getTagName().equals("description")) header.setDescription(element.getTextContent()); else if (element.getTagName().equals("sets")) header.addSetInfos(parseSets(element)); else if (element.getTagName().equals("measurements")) header.addMeasurementInfos(parseMeasurements(element)); else if (element.getTagName().equals("annotations")) { Vector<Annotation> annotations = parseAnnotations(element); if (annotations != null) for (Annotation annotation : annotations) header.addAnnotation(annotation); } } catch (Exception e) { throw new XmlParserException( "Invalid value in header (" + element.getTagName() + "): '" + e.getMessage() + "'."); } } return header; }
/** * Unmarshall a Genotype instance from a given XML Element representation. Its population of * Chromosomes will be unmarshalled from the Chromosome sub-elements. * * @param a_activeConfiguration the current active Configuration object that is to be used during * construction of the Genotype and Chromosome instances * @param a_xmlElement the XML Element representation of the Genotype * @return a new Genotype instance, complete with a population of Chromosomes, setup with the data * from the XML Element representation * @throws ImproperXMLException if the given Element is improperly structured or missing data * @throws InvalidConfigurationException if the given Configuration is in an inconsistent state * @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 * @author Klaus Meffert * @since 1.0 */ public static Genotype getGenotypeFromElement( Configuration a_activeConfiguration, Element a_xmlElement) throws ImproperXMLException, InvalidConfigurationException, UnsupportedRepresentationException, GeneCreationException { // Sanity check. Make sure the XML element isn't null and that it // actually represents a genotype. if (a_xmlElement == null || !(a_xmlElement.getTagName().equals(GENOTYPE_TAG))) { throw new ImproperXMLException( "Unable to build Genotype instance from XML Element: " + "given Element is not a 'genotype' element."); } // Fetch all of the nested chromosome elements and convert them // into Chromosome instances. // ------------------------------------------------------------ NodeList chromosomes = a_xmlElement.getElementsByTagName(CHROMOSOME_TAG); int numChromosomes = chromosomes.getLength(); Population population = new Population(a_activeConfiguration, numChromosomes); for (int i = 0; i < numChromosomes; i++) { population.addChromosome( getChromosomeFromElement(a_activeConfiguration, (Element) chromosomes.item(i))); } // Construct a new Genotype with the chromosomes and return it. // ------------------------------------------------------------ return new Genotype(a_activeConfiguration, population); }
// read all the missiles of the current id launcher protected void readMissilesForGivenLauncher(NodeList missiles, String idLauncher) { int launchTime, flyTime, damage; for (int i = 0; i < missiles.getLength(); i++) { Element missile = (Element) missiles.item(i); String id = missile.getAttribute("id"); String destination = missile.getAttribute("destination"); try { launchTime = Integer.parseInt(missile.getAttribute("launchTime")); flyTime = Integer.parseInt(missile.getAttribute("flyTime")); damage = Integer.parseInt(missile.getAttribute("damage")); } catch (NumberFormatException e) { launchTime = -1; flyTime = -1; damage = -1; System.out.println("ERROR reading from XML"); // System.out.println(e.getStackTrace()); } // create the thread of the missile createEnemyMissile(id, destination, launchTime, flyTime, damage, idLauncher); } }
private LinkedHashMap[] obtenerMapeos(CliGol cliGol, NodeList variables, String[] excluye) { LinkedHashMap<String, Object> mapa = new LinkedHashMap<String, Object>(); LinkedHashMap<String, String> puntos = new LinkedHashMap<String, String>(); List<String> ex = Arrays.asList(excluye); for (int i = 0; i < variables.getLength(); i++) { String nom = variables.item(i).getNodeName(); if (!ex.contains(nom)) { String golMapdijo = GolMap.xmlGol(nom); String val = null; if (golMapdijo != null) { val = buscaValEnCli(golMapdijo, cliGol); mapa.put(nom, val); puntos.put(nom, variables.item(i).getTextContent()); } } } return new LinkedHashMap[] {mapa, puntos}; }
public static final Map parseFrame(Node node) { NodeList bones = node.getChildNodes(); Map bone_infos = new HashMap(); for (int i = 0; i < bones.getLength(); i++) { Node bone = bones.item(i); if (bone.getNodeName().equals("transform")) { String name = bone.getAttributes().getNamedItem("name").getNodeValue(); float[] matrix = new float[16]; matrix[0 * 4 + 0] = getAttrFloat(bone, "m00"); matrix[0 * 4 + 1] = getAttrFloat(bone, "m01"); matrix[0 * 4 + 2] = getAttrFloat(bone, "m02"); matrix[0 * 4 + 3] = getAttrFloat(bone, "m03"); matrix[1 * 4 + 0] = getAttrFloat(bone, "m10"); matrix[1 * 4 + 1] = getAttrFloat(bone, "m11"); matrix[1 * 4 + 2] = getAttrFloat(bone, "m12"); matrix[1 * 4 + 3] = getAttrFloat(bone, "m13"); matrix[2 * 4 + 0] = getAttrFloat(bone, "m20"); matrix[2 * 4 + 1] = getAttrFloat(bone, "m21"); matrix[2 * 4 + 2] = getAttrFloat(bone, "m22"); matrix[2 * 4 + 3] = getAttrFloat(bone, "m23"); matrix[3 * 4 + 0] = getAttrFloat(bone, "m30"); matrix[3 * 4 + 1] = getAttrFloat(bone, "m31"); matrix[3 * 4 + 2] = getAttrFloat(bone, "m32"); matrix[3 * 4 + 3] = getAttrFloat(bone, "m33"); bone_infos.put(name, matrix); } } return bone_infos; }
// Gets the specified XML Schema doc if one is mentioned in the file public static File getSchemaFile(Document xmlDoc) { /** @todo Must be an easier way of doing this... */ logger.logComment("Getting schema file for: " + xmlDoc.getDocumentURI()); NodeList nl = xmlDoc.getChildNodes(); for (int j = 0; j < nl.getLength(); j++) { Node node = nl.item(j); logger.logComment("Type: " + node.getNodeType() + "Name: " + node.getNodeName()); if (node.getNodeName().equals(XML_STYLESHEET_NODE)) { String nodeVal = node.getNodeValue(); logger.logComment("Looking at: " + nodeVal); String xslFileName = nodeVal.substring(nodeVal.indexOf("href=\"") + 6, nodeVal.length() - 1); File xslFile = new File(xslFileName); return xslFile; } if (node.getAttributes().getLength() > 0) { logger.logComment("Attributes: " + node.getAttributes()); if (node.getAttributes().getNamedItem(XML_SCHEMA_LOC_ATTR) != null) { String locString = node.getAttributes().getNamedItem(XML_SCHEMA_LOC_ATTR).getNodeValue(); logger.logComment("Loc string: " + locString); String file = locString.split("\\s")[1]; return new File(file); } } } logger.logError("No node found with name: " + XML_STYLESHEET_NODE); return null; }
public static Element[] filterChildElements(Element parent, String ns, String lname) { /* way too noisy if (LOGGER.isDebugEnabled()) { StringBuilder buf = new StringBuilder(100); buf.append("XmlaUtil.filterChildElements: "); buf.append(" ns=\""); buf.append(ns); buf.append("\", lname=\""); buf.append(lname); buf.append("\""); LOGGER.debug(buf.toString()); } */ List<Element> elems = new ArrayList<Element>(); NodeList nlst = parent.getChildNodes(); for (int i = 0, nlen = nlst.getLength(); i < nlen; i++) { Node n = nlst.item(i); if (n instanceof Element) { Element e = (Element) n; if ((ns == null || ns.equals(e.getNamespaceURI())) && (lname == null || lname.equals(e.getLocalName()))) { elems.add(e); } } } return elems.toArray(new Element[elems.size()]); }
/* * Output this item. Then, if the element has child elements, output each. */ private void outputItem(Element e, PrintWriter out) { int chk = 0; HashMap collection = new HashMap(); String key = null; Element collectionElement = null; log.fine("outputing item for " + e.getAttribute("name") + ": " + e.getAttribute("query")); out.println("<item>"); out.println("<name>" + e.getAttribute("name") + "</name>"); if (e.getTagName().equalsIgnoreCase("collection")) { // change made by NETTY (change collectionlist to collection) out.println( "<query>collection=" + e.getAttribute("col_id") + "&xsl=metadata_to_html_full</query>"); } else { out.println( "<query>owner=" + e.getAttribute("query") + "&xsl=metadata_to_html_full</query>"); } // now output children NodeList children = e.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { chk++; outputItem((Element) child, out); } } out.println("</item>"); }
/* * If the element contains an attribute 'makeOnly' with a value of 'true', * create a child element before any existing children which will display a node * which will display only the elements records. * Compute the query attribute, which is the appended result of all of the children * appended to this element name. If noQuery=true. then do not generate a query term * for this element. */ String computeQuery(Element e) { String query = ""; if (!(e.getAttribute("noQuery").equalsIgnoreCase("true"))) { query = e.getAttribute("name"); } String makeOnly = e.getAttribute("makeOnly"); boolean madeOnly = false; NodeList children = e.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { if (makeOnly.equalsIgnoreCase("true") && !madeOnly) { // need to make an ...-Only node and populate it String onlyTagName = e.getTagName() + "-Only"; Element only = ((Document) dom.getNode()).createElement(onlyTagName); only.setAttribute("name", e.getAttribute("name") + "-Only"); only.setAttribute("query", e.getAttribute("name")); e.insertBefore(only, child); i++; madeOnly = true; } if (query.length() > 0) { query += ","; } query += computeQuery((Element) child); } } log.info("setting query for " + e.getNodeName() + " " + query); e.setAttribute("query", query); return query; }
public static void traverseAMLforObjectNames( HashMap partialMap, Node currentNode, HashMap ObjDef_LinkId, HashMap ModelId_ModelType) { if (currentNode.hasChildNodes()) { for (int i = 0; i < currentNode.getChildNodes().getLength(); i++) { Node currentChild = currentNode.getChildNodes().item(i); if (currentChild.getNodeName().equals("Group")) { traverseAMLforObjectNames(partialMap, currentChild, ObjDef_LinkId, ModelId_ModelType); } if (currentChild.getNodeName().equals("Model")) { if (currentChild.hasAttributes()) { String mid = currentChild.getAttributes().getNamedItem("Model.ID").getNodeValue(); String type = currentChild.getAttributes().getNamedItem("Model.Type").getNodeValue(); ModelId_ModelType.put(mid, type); } // traverseAMLforObjectNames(partialMap, currentChild, // ObjDef_LinkId); } if (currentChild.getNodeName().equals("ObjDef")) { String id = currentChild.getAttributes().getNamedItem("ObjDef.ID").getNodeValue(); NodeList currentChildren = currentChild.getChildNodes(); String ObjName = ""; for (int k = 0; k < currentChildren.getLength(); k++) { Node Child = currentChildren.item(k); if (!Child.getNodeName().equals("AttrDef")) { continue; } else if (!Child.getAttributes() .getNamedItem("AttrDef.Type") .getNodeValue() .equals("AT_NAME")) { continue; } else if (Child.hasChildNodes()) { for (int l = 0; l < Child.getChildNodes().getLength(); l++) { if (!(Child.getChildNodes().item(l).getNodeName().equals("AttrValue"))) { continue; } else { ObjName = getTextContent(Child.getChildNodes().item(l)); ObjName = ObjName.replaceAll("\n", "\\\\n"); break; } } } } partialMap.put(id, ObjName); for (int j = 0; j < currentChild.getAttributes().getLength(); j++) { if (currentChild.getAttributes().item(j).getNodeName().equals("LinkedModels.IdRefs")) { String links = currentChild.getAttributes().getNamedItem("LinkedModels.IdRefs").getNodeValue(); /* * if (links.indexOf(" ") > -1) { * Message.add("yes, yes, yes"); links = * links.substring(0, links.indexOf(" ")); } */ ObjDef_LinkId.put(id, links); } } } } } }
private Element getElement(String eltName) { NodeList nodeList = docElt.getElementsByTagName(eltName); if (nodeList.getLength() != 0) { Node node = nodeList.item(0); if (node instanceof Element) return (Element) node; } return null; }
/** * Metodo per la lettura e il salvataggio in DB dei dati relativi alla prima configurazione del * cinema multisala * * @throws Exception */ public static void readInitialConfig() throws Exception { // Lettura del file config.xml MySQLAccess msa = new MySQLAccess(); msa.readDB(); Document config = loadDocument(CONFIG_FILE); // Creazione della lista di sale NodeList cinemaHalls = findCinemaHall(config); for (int i = 0; i < cinemaHalls.getLength(); i++) { NamedNodeMap attr = cinemaHalls.item(i).getAttributes(); String[] s = attr.getNamedItem("id").toString().split("\""); // ID della sala i char id = s[1].toCharArray()[0]; s = attr.getNamedItem("name").toString().split("\""); // Nome sala i String name = s[1]; s = attr.getNamedItem("specialseat").toString().split("\""); // Numero posti speciali int specialSeats = Integer.parseInt(s[1]); NodeList rows = readRows((Element) cinemaHalls.item(i)); // Numero file della sala i int n_rows = rows.getLength(); // Numero posti totali int seats = 0; for (int j = 0; j < n_rows; j++) { // Numero posti della fila j int r_seats = Integer.parseInt(rows.item(j).getTextContent().toString().trim()); seats += r_seats; } // Invoca l'inserimento in DB msa.insertCinemaHall(id, name, n_rows, seats, specialSeats); for (int j = 0; j < n_rows; j++) { NamedNodeMap r_attr = rows.item(j).getAttributes(); s = r_attr.getNamedItem("number").toString().split("\""); int number = Integer.parseInt(s[1]); // Numero posti della fila j int r_seats = Integer.parseInt(rows.item(j).getTextContent().toString().trim()); msa.insertRow(id, number, r_seats); } } msa.closeDB(); }
private void removeNodes(NodeList nl) { int count = nl.getLength(); for (int i = 0; i < count; i++) { Node node = nl.item(i); Node parent = node.getParentNode(); if (parent == null) continue; parent.removeChild(node); } }
public Vector getNodes(Element padre) { Vector vectorNode = new Vector(); NodeList nodeList = padre.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) vectorNode.add(node); } return vectorNode; }
public static Vector recuperarHojasAsVector(Element esteNodo, String tag) { NodeList listaElem = esteNodo.getElementsByTagName(tag); Vector vector = new Vector(); for (int i = 0; i < listaElem.getLength(); i++) { Element xmlElement = (Element) listaElem.item(i); Node xmlHoja = (Node) xmlElement.getChildNodes().item(0); vector.addElement(xmlHoja.getNodeValue()); } return vector; }
/** * Honey, can you just check on the kids? Thanks. * * <p>Internal function; not included in reference. */ protected void checkChildren() { if (children == null) { NodeList kids = node.getChildNodes(); int childCount = kids.getLength(); children = new XML[childCount]; for (int i = 0; i < childCount; i++) { children[i] = new XML(this, kids.item(i)); } } }
/** * ** Gets a virtual DBRecord from the specified remote service ** @param servReq The remote web * service ** @return The virtual DBRecord (cannot be saved or reloaded) */ @SuppressWarnings("unchecked") public gDBR getVirtualDBRecord(final ServiceRequest servReq) throws DBException { String CMD_dbget = DBFactory.CMD_dbget; String TAG_Response = servReq.getTagResponse(); String TAG_Record = DBFactory.TAG_Record; String ATTR_command = servReq.getAttrCommand(); String ATTR_result = servReq.getAttrResult(); /* send request / get response */ Document xmlDoc = null; try { xmlDoc = servReq.sendRequest( CMD_dbget, new ServiceRequest.RequestBody() { public StringBuffer appendRequestBody(StringBuffer sb, int indent) { return DBRecordKey.this.toRequestXML(sb, indent); } }); } catch (IOException ioe) { Print.logException("Error", ioe); throw new DBException("Request read error", ioe); } /* parse 'GTSResponse' */ Element gtsResponse = xmlDoc.getDocumentElement(); if (!gtsResponse.getTagName().equalsIgnoreCase(TAG_Response)) { Print.logError("Request XML does not start with '%s'", TAG_Response); throw new DBException("Response XML does not begin eith '" + TAG_Response + "'"); } /* request command/argument */ String cmd = StringTools.trim(gtsResponse.getAttribute(ATTR_command)); String result = StringTools.trim(gtsResponse.getAttribute(ATTR_result)); if (StringTools.isBlank(result)) { result = StringTools.trim(gtsResponse.getAttribute("type")); } if (!result.equalsIgnoreCase("success")) { Print.logError("Response indicates failure"); throw new DBException("Response does not indicate 'success'"); } /* Record */ NodeList rcdList = XMLTools.getChildElements(gtsResponse, TAG_Record); if (rcdList.getLength() <= 0) { Print.logError("No 'Record' tags"); throw new DBException("GTSResponse does not contain any 'Record' tags"); } Element rcdElem = (Element) rcdList.item(0); /* return DBRecord */ gDBR dbr = (gDBR) DBFactory.parseXML_DBRecord(rcdElem); dbr.setVirtual(true); return dbr; }