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; }
@Override public void apply(Element e) { if (e.getTagName().equals("property")) { Element parent = (Element) e.getParentNode(); if (parent != null && parent.getTagName().equals("ndbx")) { Attr name = e.getAttributeNode("name"); Attr value = e.getAttributeNode("value"); if (name != null && name.getValue().equals("oscPort")) { if (value != null) { Element device = e.getOwnerDocument().createElement("device"); device.setAttribute("name", "osc1"); device.setAttribute("type", "osc"); Element portProperty = e.getOwnerDocument().createElement("property"); portProperty.setAttribute("name", "port"); portProperty.setAttribute("value", value.getValue()); device.appendChild(portProperty); Element autostartProperty = e.getOwnerDocument().createElement("property"); autostartProperty.setAttribute("name", "autostart"); autostartProperty.setAttribute("value", "true"); device.appendChild(autostartProperty); parent.replaceChild(device, e); } else { parent.removeChild(e); } } } } }
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; }
@Override public void apply(Element e) { if (e.getTagName().equals("property")) { Element parent = (Element) e.getParentNode(); if (parent != null && parent.getTagName().equals("device")) { Attr type = parent.getAttributeNode("type"); if (type != null && type.getValue().equals(this.deviceType)) { Attr name = e.getAttributeNode("name"); if (name != null && name.getValue().equals(oldPropertyName)) name.setValue(newPropertyName); } } } }
private static UpgradeStringResult transformXml( String xml, String newFormatVersion, UpgradeOp... ops) { try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; builder = builderFactory.newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader(xml))); // Check that this is a NodeBox document and set the new formatVersion. Element root = document.getDocumentElement(); checkArgument(root.getTagName().equals("ndbx"), "This is not a valid NodeBox document."); root.setAttribute("formatVersion", newFormatVersion); // Loop through all upgrade operations. ArrayList<String> warnings = new ArrayList<String>(); for (UpgradeOp op : ops) { op.start(root); transformXmlRecursive(document.getDocumentElement(), op); op.end(root); warnings.addAll(op.getWarnings()); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(document); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); transformer.transform(source, result); return new UpgradeStringResult(sw.toString(), warnings); } catch (Exception e) { throw new RuntimeException("Error while upgrading to " + newFormatVersion + ".", e); } }
/** * 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); }
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; }
/** * Set a property of a resource to a value. * * @param name the property name * @param value the property value * @exception com.ibm.webdav.WebDAVException */ public void setProperty(String name, Element value) throws WebDAVException { // load the properties Document propertiesDocument = resource.loadProperties(); Element properties = propertiesDocument.getDocumentElement(); String ns = value.getNamespaceURI(); Element property = null; if (ns == null) { property = (Element) ((Element) properties).getElementsByTagName(value.getTagName()).item(0); } else { property = (Element) properties.getElementsByTagNameNS(ns, value.getLocalName()).item(0); } if (property != null) { try { properties.removeChild(property); } catch (DOMException exc) { } } properties.appendChild(propertiesDocument.importNode(value, true)); // write out the properties resource.saveProperties(propertiesDocument); }
@Test public void testElementGetAPIs() throws Exception { // builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); String xml = "<?xml version=\"1.0\"?>" + "<t:root xmlns=\"http://void.com/\" xmlns:t=\"http://t.com/\" id=\"stella\" t:type=\"police\">" + "<t:item id=\"a\"/>" + "<child id=\"1\"/>" + "<t:item id=\"b\"/>" + "<child id=\"2\"/>" + "</t:root>"; DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes())); Element root = doc.getDocumentElement(); Assert.assertEquals("tagName", "t:root", root.getTagName()); Assert.assertEquals("attribute", "stella", root.getAttribute("id")); Assert.assertEquals("attributeNS", "police", root.getAttributeNS("http://t.com/", "type")); Assert.assertEquals("attribute(has)", true, root.hasAttribute("id")); Assert.assertEquals("attribute(has)", false, root.hasAttribute("__id__")); Assert.assertEquals("attributeNS(has)", true, root.hasAttributeNS("http://t.com/", "type")); Assert.assertEquals("attributeNS(has)", false, root.hasAttributeNS("http://t.com/", "tipe")); }
/** * Unmarshall a Chromosome instance from a given XML Element representation. * * @param a_activeConfiguration the current active Configuration object that is to be used during * construction of the Chromosome * @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 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 * @since 1.0 */ public static Chromosome getChromosomeFromElement( Configuration a_activeConfiguration, Element a_xmlElement) throws ImproperXMLException, InvalidConfigurationException, UnsupportedRepresentationException, GeneCreationException { // Do some sanity checking. Make sure the XML Element isn't null and // that in fact represents a chromosome. // ----------------------------------------------------------------- if (a_xmlElement == null || !(a_xmlElement.getTagName().equals(CHROMOSOME_TAG))) { throw new ImproperXMLException( "Unable to build Chromosome instance from XML Element: " + "given Element is not a 'chromosome' element."); } // Extract the nested genes element and make sure it exists. // --------------------------------------------------------- Element genesElement = (Element) a_xmlElement.getElementsByTagName(GENES_TAG).item(0); if (genesElement == null) { throw new ImproperXMLException( "Unable to build Chromosome instance from XML Element: " + "'genes' sub-element not found."); } // Construct the genes from their representations. // ----------------------------------------------- Gene[] geneAlleles = getGenesFromElement(a_activeConfiguration, genesElement); // Construct the new Chromosome with the genes and return it. // ---------------------------------------------------------- return new Chromosome(a_activeConfiguration, geneAlleles); }
/** * @param sourceFile File to read from * @return List of String objects with the shas */ public static FileRequestFileContent readRequestFile(final File sourceFile) { if (!sourceFile.isFile() || !(sourceFile.length() > 0)) { return null; } Document d = null; try { d = XMLTools.parseXmlFile(sourceFile.getPath()); } catch (final Throwable t) { logger.log(Level.SEVERE, "Exception in readRequestFile, during XML parsing", t); return null; } if (d == null) { logger.log(Level.SEVERE, "Could'nt parse the request file"); return null; } final Element rootNode = d.getDocumentElement(); if (rootNode.getTagName().equals(TAG_FrostFileRequestFile) == false) { logger.severe( "Error: xml request file does not contain the root tag '" + TAG_FrostFileRequestFile + "'"); return null; } final String timeStampStr = XMLTools.getChildElementsTextValue(rootNode, TAG_timestamp); if (timeStampStr == null) { logger.severe("Error: xml file does not contain the tag '" + TAG_timestamp + "'"); return null; } final long timestamp = Long.parseLong(timeStampStr); final List<Element> nodelist = XMLTools.getChildElementsByTagName(rootNode, TAG_shaList); if (nodelist.size() != 1) { logger.severe("Error: xml request files must contain only one element '" + TAG_shaList + "'"); return null; } final Element rootShaNode = nodelist.get(0); final List<String> shaList = new LinkedList<String>(); final List<Element> xmlKeys = XMLTools.getChildElementsByTagName(rootShaNode, TAG_sha); for (final Element el : xmlKeys) { final Text txtname = (Text) el.getFirstChild(); if (txtname == null) { continue; } final String sha = txtname.getData(); shaList.add(sha); } final FileRequestFileContent content = new FileRequestFileContent(timestamp, shaList); return content; }
private static boolean isNodeWithPrototype(Element e, String nodePrototype) { if (e.getTagName().equals("node")) { Attr prototype = e.getAttributeNode("prototype"); if (prototype != null && prototype.getValue().equals(nodePrototype)) { return true; } } return false; }
/** * ** 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; }
private static Vector<Annotation> parseAnnotations(Node parent) throws XmlParserException { Vector<Annotation> annotations = new Vector<Annotation>(); 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("annotation")) { String label = null, value = null, valuetype = null, unit = null; NodeList annotation_nodes = element.getChildNodes(); for (int annotationid = 0; annotationid < annotation_nodes.getLength(); ++annotationid) { Node annotation_node = annotation_nodes.item(annotationid); if (annotation_node.getNodeType() != Node.ELEMENT_NODE) continue; Element annotation_element = (Element) annotation_node; if (annotation_element.getTagName().equals("label")) label = annotation_element.getTextContent(); else if (annotation_element.getTagName().equals("value")) value = annotation_element.getTextContent(); else if (annotation_element.getTagName().equals("valuetype")) valuetype = annotation_element.getTextContent(); } if (label == null || value == null || valuetype == null) throw new XmlParserException("Annotation is missing either: label, value or valuetype"); Annotation annotation = new Annotation(label, value, Annotation.ValueType.valueOf(valuetype)); annotation.setUnit(unit); if (annotation.getValueType() == Annotation.ValueType.ONTOLOGY) annotation.setOntologyRef(element.getAttribute("ontologyref")); if (element.getAttribute("unit") != null) annotation.setUnit(element.getAttribute("unit")); annotations.add(annotation); } } return annotations; }
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; }
private static ScanInfo parseScan(Node parent) throws XmlParserException { double retentiontime = 0; Polarity polarity = Polarity.NEUTRAL; Vector<Annotation> annotations = 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("polarity")) polarity = Polarity.valueOf(element.getTextContent()); else if (element.getTagName().equals("retentiontime")) retentiontime = Double.parseDouble(element.getTextContent()); else if (element.getTagName().equals("annotations")) annotations = parseAnnotations(element); } ScanInfo scan = new ScanInfo(retentiontime, polarity); if (annotations != null) scan.addAnnotations(annotations); return scan; }
private static FileInfo parseFile(Node parent) throws XmlParserException { String label = ""; String name = ""; String location = ""; Vector<Annotation> annotations = 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("label")) label = element.getTextContent(); else if (element.getTagName().equals("name")) name = element.getTextContent(); else if (element.getTagName().equals("location")) location = element.getTextContent(); else if (element.getTagName().equals("annotations")) annotations = parseAnnotations(node); } FileInfo file = new FileInfo(label, name, location); if (annotations != null) file.addAnnotations(annotations); return file; }
public void load(InputStream is) throws IOException, ParserConfigurationException, SAXException { doc = db.parse(is); docElt = doc.getDocumentElement(); if (docElt.getTagName().equals(docElementName)) { NodeList nl = docElt.getElementsByTagName(trackElementName); for (int i = 0; i < nl.getLength(); i++) { Element elt = (Element) nl.item(i); Track track = new Track(elt); tracks.add(track); hash.put(track.getKey(), track); } } }
private static Vector<FileInfo> parseFiles(Node parent) throws XmlParserException { Vector<FileInfo> files = new Vector<FileInfo>(); 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("file")) files.add(parseFile(node)); } return files; }
@Override public void apply(Element e) { if (e.getTagName().equals("node")) { if (shouldSkipRoot) { Element parent = (Element) e.getParentNode(); if (parent != null && !parent.getTagName().equals("node")) return; } Attr name = e.getAttributeNode("name"); if (name != null && name.getValue().equals(oldNodeName)) { Set<String> childNames = getChildNodeNames((Element) e.getParentNode()); String newNodeName = uniqueName(newPrefix, childNames); name.setValue(newNodeName); Element parent = (Element) e.getParentNode(); renameRenderedChildReference(parent, oldNodeName, newNodeName); List<Element> connections = childElementsWithName(parent, "conn"); renamePortReference(connections, "input", oldNodeName, newNodeName); renameNodeReference(connections, "output", oldNodeName, newNodeName); List<Element> ports = childElementsWithName(parent, "port"); renamePortReference(ports, "childReference", oldNodeName, newNodeName); } } }
/** * Unmarshall a Chromosome instance from a given XML Document representation. Its genes will be * unmarshalled from the gene sub-elements. * * @param a_activeConfiguration the current active Configuration object that is to be used during * construction of the Chromosome instances * @param a_xmlDocument the XML Document representation of the Chromosome * @return a new Chromosome instance setup with the data from the XML Document representation * @throws ImproperXMLException if the given Document 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 * @since 1.0 */ public static Chromosome getChromosomeFromDocument( Configuration a_activeConfiguration, Document a_xmlDocument) throws ImproperXMLException, InvalidConfigurationException, UnsupportedRepresentationException, GeneCreationException { // Extract the root element, which should be a chromosome element. // After verifying that the root element is not null and that it // in fact is a chromosome element, then convert it into a Chromosome // instance. // ------------------------------------------------------------------ Element rootElement = a_xmlDocument.getDocumentElement(); if (rootElement == null || !(rootElement.getTagName().equals(CHROMOSOME_TAG))) { throw new ImproperXMLException( "Unable to build Chromosome instance from XML Document: " + "'chromosome' element must be at root of Document."); } return getChromosomeFromElement(a_activeConfiguration, rootElement); }
protected static XmlConfigurator parse(Element root_element) throws java.io.IOException { XmlConfigurator configurator = null; final LinkedList<ProtocolConfiguration> prot_data = new LinkedList<ProtocolConfiguration>(); /** * CAUTION: crappy code ahead ! I (bela) am not an XML expert, so the code below is pretty * amateurish... But it seems to work, and it is executed only on startup, so no perf loss on * the critical path. If somebody wants to improve this, please be my guest. */ try { String root_name = root_element.getNodeName(); if (!"config".equals(root_name.trim().toLowerCase())) throw new IOException("the configuration does not start with a <config> element"); NodeList prots = root_element.getChildNodes(); for (int i = 0; i < prots.getLength(); i++) { Node node = prots.item(i); if (node.getNodeType() != Node.ELEMENT_NODE) continue; Element tag = (Element) node; String protocol = tag.getTagName(); Map<String, String> params = new HashMap<String, String>(); NamedNodeMap attrs = tag.getAttributes(); int attrLength = attrs.getLength(); for (int a = 0; a < attrLength; a++) { Attr attr = (Attr) attrs.item(a); String name = attr.getName(); String value = attr.getValue(); params.put(name, value); } ProtocolConfiguration cfg = new ProtocolConfiguration(protocol, params); prot_data.add(cfg); } configurator = new XmlConfigurator(prot_data); } catch (Exception x) { if (x instanceof java.io.IOException) throw (java.io.IOException) x; else { IOException tmp = new IOException(); tmp.initCause(x); throw tmp; } } return configurator; }
private static void parseIPeak(Node parent, IPeak peak) throws XmlParserException { // retrieve all the properties int scan = -1; double retentiontime = -1; double mass = -1; double intensity = -1; int patternid = -1; int measurementid = -1; // String sha1 = null; Vector<Annotation> annotations = 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("patternid")) patternid = Integer.parseInt(element.getTextContent()); else if (element.getTagName().equals("measurementid")) measurementid = Integer.parseInt(element.getTextContent()); else if (element.getTagName().equals("annotations")) annotations = parseAnnotations(element); else if (element.getTagName().equals("scan")) scan = Integer.parseInt(element.getTextContent()); else if (element.getTagName().equals("retentiontime")) retentiontime = Double.parseDouble(element.getTextContent()); else if (element.getTagName().equals("mass")) mass = Double.parseDouble(element.getTextContent()); else if (element.getTagName().equals("intensity")) intensity = Double.parseDouble(element.getTextContent()); // else if (element.getTagName().equals("sha1sum")) // sha1 = element.getTextContent(); } // check whether obligatory values are missing if (mass == -1 || intensity == -1) throw new XmlParserException("Mass and/or intensity information is missing for IPeak."); peak.setScanID(scan); peak.setRetentionTime(retentiontime); peak.setMass(mass); peak.setIntensity(intensity); peak.setPatternID(patternid); peak.setMeasurementID(measurementid); if (annotations != null) for (Annotation annotation : annotations) peak.addAnnotation(annotation); // check whether // if (sha1!=null && !sha1.equals(peak.sha1())) // throw new XmlParserException("SHA1-sum for individual ipeak element does not match."); }
@Test public void testgetAttributesWithNamedNodeMap() throws Exception { // builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); File f = new File(System.getProperty("user.dir"), "src/test/resources/sample-springbeans.xml"); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document doc = builder.parse(f); Element root = doc.getDocumentElement(); // System.out.println("* current impl: " + doc.getClass().getName()); // id, class Map<String, String> actualMap = new HashMap<String, String>(); NodeList list = root.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if (node instanceof Element) { Element elem = (Element) node; if (elem.getTagName().equals("beans:bean")) { // System.out.println("bean[" + elem.getAttribute("id") + "]"); NamedNodeMap map = elem.getAttributes(); String valueId = null; String valueClass = null; for (int x = 0; x < map.getLength(); x++) { Node attr = map.item(x); if (attr.getNodeName().equals("id")) valueId = attr.getNodeValue(); if (attr.getNodeName().equals("class")) valueClass = attr.getNodeValue(); } if (valueId != null && valueClass != null) actualMap.put(valueId, valueClass); } } } Map<String, String> expected = new HashMap<String, String>(); expected.put("authenticationManager", "org.springframework.security.providers.ProviderManager"); expected.put( "daoAuthenticationProvider", "org.springframework.security.providers.dao.DaoAuthenticationProvider"); expected.put( "loggerListener", "org.springframework.security.event.authentication.LoggerListener"); Assert.assertEquals("Attributes with NamedNodeMap", expected, actualMap); }
private static NodeList getChildElements(Element self, String elementName) { List result = new ArrayList(); NodeList nodeList = self.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element child = (Element) node; if ("*".equals(elementName) || child.getTagName().equals(elementName)) { result.add(child); } } else if (node.getNodeType() == Node.TEXT_NODE) { String value = node.getNodeValue(); if (trimWhitespace) { value = value.trim(); } if ("*".equals(elementName) && value.length() > 0) { node.setNodeValue(value); result.add(node); } } } return new NodesHolder(result); }
@SuppressWarnings("unchecked") private static BackgroundIon<? extends Peak> parseBackgroundIon(Node parent) throws XmlParserException { // retrieve the separate peaks PeakData<? extends Peak> peakdata = 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("peakdata")) { peakdata = parsePeakData(element); } } // create the bugger BackgroundIon<? extends Peak> backgroundion = null; if (peakdata.getFactory().getPeakClass().equals(Centroid.class)) backgroundion = new BackgroundIon<Centroid>((PeakData<Centroid>) peakdata); parseIPeak(parent, backgroundion); return backgroundion; }
// http://code.google.com/apis/maps/documentation/geocoding/index.html public GeoPoint getGeocode(String address, String country) { /* URL */ String url = this.getGeoPointGeocodeURL(address, country); Print.logDebug("Google GC URL: " + url); /* create XML document */ Document xmlDoc = GetXMLDocument(url, this.getGeocodeTimeout()); if (xmlDoc == null) { return null; } /* vars */ String errCode = null; GeoPoint geoPoint = null; /* parse "xml" */ Element kml = xmlDoc.getDocumentElement(); if (kml.getTagName().equalsIgnoreCase(TAG_kml)) { NodeList ResponseList = XMLTools.getChildElements(kml, TAG_Response); for (int g = 0; (g < ResponseList.getLength()); g++) { Element response = (Element) ResponseList.item(g); NodeList responseNodes = response.getChildNodes(); for (int n = 0; n < responseNodes.getLength(); n++) { Node responseNode = responseNodes.item(n); if (!(responseNode instanceof Element)) { continue; } Element responseElem = (Element) responseNode; String responseNodeName = responseElem.getNodeName(); if (responseNodeName.equalsIgnoreCase(TAG_name)) { // <name>1600 Amphitheatre Parkway, Mountain View, CA</name> } else if (responseNodeName.equalsIgnoreCase(TAG_Status)) { // <Status> ... </Status> NodeList statusNodes = responseElem.getChildNodes(); for (int st = 0; st < statusNodes.getLength(); st++) { Node statusNode = statusNodes.item(st); if (!(statusNode instanceof Element)) { continue; } Element statusElem = (Element) statusNode; String statusNodeName = statusElem.getNodeName(); if (statusNodeName.equalsIgnoreCase(TAG_code)) { errCode = StringTools.trim(GoogleGeocodeV2.GetNodeText(statusElem)); // expect "200" break; // we only care about the 'code' } } } else if (responseNodeName.equalsIgnoreCase(TAG_Placemark)) { // <Placemark> ... </Placemark> String id = responseElem.getAttribute(ATTR_id); if ((id != null) && id.equals("p1")) { NodeList placemarkNodes = responseElem.getChildNodes(); for (int pm = 0; (geoPoint == null) && (pm < placemarkNodes.getLength()); pm++) { Node placemarkNode = placemarkNodes.item(pm); if (!(placemarkNode instanceof Element)) { continue; } Element placemarkElem = (Element) placemarkNode; String placemarkNodeName = placemarkElem.getNodeName(); if (placemarkNodeName.equalsIgnoreCase(TAG_Point)) { NodeList pointNodes = placemarkElem.getChildNodes(); for (int ptn = 0; (geoPoint == null) && (ptn < pointNodes.getLength()); ptn++) { Node pointNode = pointNodes.item(ptn); if (!(pointNode instanceof Element)) { continue; } Element pointElem = (Element) pointNode; String pointNodeName = pointElem.getNodeName(); if (pointNodeName.equalsIgnoreCase(TAG_coordinates)) { String ll[] = StringTools.split(GoogleGeocodeV2.GetNodeText(pointElem), ','); if (ll.length >= 2) { double lon = StringTools.parseDouble(ll[0], 0.0); // longitude is first double lat = StringTools.parseDouble(ll[1], 0.0); if (GeoPoint.isValid(lat, lon)) { geoPoint = new GeoPoint(lat, lon); break; // we only care about the 'GeoPoint' } } } } } } } else { // Print.logInfo("Skipping Placemark ID = %s", id); } } } } } /* create address */ if (geoPoint != null) { // GeoPoint found return geoPoint; } /* check for Google reverse-geocode limit exceeded */ if ((errCode != null) && errCode.equals("620")) { Print.logError("!!!! Google Reverse-Geocode Limit Exceeded [Error 620] !!!!"); } /* no reverse-geocode available */ return null; }
/* return reverse-geocode using nearest address */ public ReverseGeocode getAddressReverseGeocode(GeoPoint gp, String localeStr, boolean cache) { /* check for failover mode */ if (this.isReverseGeocodeFailoverMode()) { ReverseGeocodeProvider frgp = this.getFailoverReverseGeocodeProvider(); return frgp.getReverseGeocode(gp, localeStr, cache); } /* URL */ String url = this.getAddressReverseGeocodeURL(gp, localeStr); Print.logDebug("Google RG URL: " + url); // byte xmlBytes[] = HTMLTools.readPage(url); /* create XML document */ Document xmlDoc = GetXMLDocument(url, this.getReverseGeocodeTimeout()); if (xmlDoc == null) { return null; } /* vars */ String errCode = null; String address = null; /* parse "xml" */ Element kml = xmlDoc.getDocumentElement(); if (kml.getTagName().equalsIgnoreCase(TAG_kml)) { NodeList ResponseList = XMLTools.getChildElements(kml, TAG_Response); for (int g = 0; (g < ResponseList.getLength()); g++) { Element response = (Element) ResponseList.item(g); NodeList responseNodes = response.getChildNodes(); for (int n = 0; n < responseNodes.getLength(); n++) { Node responseNode = responseNodes.item(n); if (!(responseNode instanceof Element)) { continue; } Element responseElem = (Element) responseNode; String responseNodeName = responseElem.getNodeName(); if (responseNodeName.equalsIgnoreCase(TAG_name)) { // <name>40.479581,-117.773438</name> } else if (responseNodeName.equalsIgnoreCase(TAG_Status)) { // <Status> ... </Status> NodeList statusNodes = responseElem.getChildNodes(); for (int st = 0; st < statusNodes.getLength(); st++) { Node statusNode = statusNodes.item(st); if (!(statusNode instanceof Element)) { continue; } Element statusElem = (Element) statusNode; String statusNodeName = statusElem.getNodeName(); if (statusNodeName.equalsIgnoreCase(TAG_code)) { errCode = StringTools.trim(GoogleGeocodeV2.GetNodeText(statusElem)); // expect "200" break; // we only care about the 'code' } } } else if (responseNodeName.equalsIgnoreCase(TAG_Placemark)) { // <Placemark> ... </Placemark> String id = responseElem.getAttribute(ATTR_id); if ((id != null) && id.equals("p1")) { NodeList placemarkNodes = responseElem.getChildNodes(); for (int pm = 0; pm < placemarkNodes.getLength(); pm++) { Node placemarkNode = placemarkNodes.item(pm); if (!(placemarkNode instanceof Element)) { continue; } Element placemarkElem = (Element) placemarkNode; String placemarkNodeName = placemarkElem.getNodeName(); if (placemarkNodeName.equalsIgnoreCase(TAG_address)) { address = GoogleGeocodeV2.GetNodeText(placemarkElem); break; // we only care about the 'address' } } } else { // Print.logInfo("Skipping Placemark ID = %s", id); } } } } } /* create address */ if (FAILOVER_DEBUG) { errCode = "620"; } else if (!StringTools.isBlank(address)) { // address found ReverseGeocode rg = new ReverseGeocode(); rg.setFullAddress(address); return rg; } /* check for Google reverse-geocode limit exceeded */ if ((errCode != null) && errCode.equals("620")) { Print.logError("!!!! Google Reverse-Geocode Limit Exceeded [Error 620] !!!!"); if (this.hasFailoverReverseGeocodeProvider()) { this.startReverseGeocodeFailoverMode(); ReverseGeocodeProvider frgp = this.getFailoverReverseGeocodeProvider(); Print.logWarn("Failing over to '" + frgp.getName() + "'"); return frgp.getReverseGeocode(gp, localeStr, cache); } } /* no reverse-geocode available */ return null; }
private static PeakData<? extends Peak> parsePeakData(Node parent) throws XmlParserException { // get the attributes Node typeattribute = parent.getAttributes().getNamedItem(PeakMLWriter.TYPE); if (typeattribute == null) throw new XmlParserException("Failed to locate a type attribute."); Node sizeattribute = parent.getAttributes().getNamedItem(PeakMLWriter.SIZE); if (sizeattribute == null) throw new XmlParserException("Failed to locate a size attribute."); int size = Integer.parseInt(sizeattribute.getNodeValue()); String type = typeattribute.getNodeValue(); // create the arrays int scanids[] = null; int patternids[] = null; int measurementids[] = null; double masses[] = null; double intensities[] = null; double retentiontimes[] = null; // retrieve all the data 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("scanids")) scanids = ByteArray.toIntArray( Base64.decode(element.getTextContent()), ByteArray.ENDIAN_LITTLE, 32); else if (element.getTagName().equals("patternids")) patternids = ByteArray.toIntArray( Base64.decode(element.getTextContent()), ByteArray.ENDIAN_LITTLE, 32); else if (element.getTagName().equals("measurementids")) measurementids = ByteArray.toIntArray( Base64.decode(element.getTextContent()), ByteArray.ENDIAN_LITTLE, 32); else if (element.getTagName().equals("masses")) masses = ByteArray.toDoubleArray( Base64.decode(element.getTextContent()), ByteArray.ENDIAN_LITTLE, 32); else if (element.getTagName().equals("intensities")) intensities = ByteArray.toDoubleArray( Base64.decode(element.getTextContent()), ByteArray.ENDIAN_LITTLE, 32); else if (element.getTagName().equals("retentiontimes")) retentiontimes = ByteArray.toDoubleArray( Base64.decode(element.getTextContent()), ByteArray.ENDIAN_LITTLE, 32); } // create the PeakData instance if (type.equals("centroid")) return new PeakData<Centroid>( Centroid.factory, size, scanids, patternids, measurementids, masses, intensities, retentiontimes); return null; }
/** * Reads XML element(s) into an indexed bean property by first locating the XML element(s) * corresponding to this property. * * @param ob The bean whose property is being set * @param desc The property that will be set * @param nodes The list of XML items that may contain the property * @throws IOException If there is an error reading the document */ public void readIndexedProperty( Object ob, IndexedPropertyDescriptor desc, NodeList nodes, NamedNodeMap attrs) throws IOException { // Create a vector to hold the property values Vector v = new Vector(); int numAttrs = attrs.getLength(); for (int i = 0; i < numAttrs; i++) { // See if this attribute matches the property name if (namesMatch(desc.getName(), attrs.item(i).getNodeName())) { // Get the property value Object obValue = getObjectValue(desc, attrs.item(i).getNodeValue()); if (obValue != null) { // Add the value to the list of values to be set v.addElement(obValue); } } } int numNodes = nodes.getLength(); for (int i = 0; i < numNodes; i++) { Node node = nodes.item(i); // Skip non-element nodes if (!(node instanceof Element)) continue; Element element = (Element) node; // See if this element tag matches the property name if (namesMatch(desc.getName(), element.getTagName())) { // Get the property value Object obValue = getObjectValue(desc, element); if (obValue != null) { // Add the value to the list of values to be set v.addElement(obValue); } } } // Get the method used to set the property value Method setter = desc.getWriteMethod(); // If this property has no setter, don't write it if (setter == null) return; // Create a new array of property values Object propArray = Array.newInstance(desc.getPropertyType().getComponentType(), v.size()); // Copy the vector into the array v.copyInto((Object[]) propArray); try { // Store the array of property values setter.invoke(ob, new Object[] {propArray}); } catch (InvocationTargetException exc) { throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString()); } catch (IllegalAccessException exc) { throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString()); } }