Пример #1
0
  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;
  }
Пример #2
0
  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;
  }
Пример #3
0
 @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);
         }
       }
     }
   }
 }
Пример #4
0
 /**
  * Tests if a Element <code>element</code> is valid for the <code>XmlCenter</code>.
  *
  * @param element
  * @return boolean
  */
 public static boolean isMatch(Element element) {
   String tagName = element.getTagName();
   if (!"center".equals(tagName)) {
     return (false);
   }
   RStack target = new RStack(element);
   Element child;
   child = target.popElement();
   if (child == null) {
     return (false);
   }
   if (!"ra".equals(child.getTagName())) {
     return (false);
   }
   child = target.popElement();
   if (child == null) {
     return (false);
   }
   if (!"decl".equals(child.getTagName())) {
     return (false);
   }
   if (!target.isEmptyElement()) {
     return (false);
   }
   return (true);
 }
Пример #5
0
 @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);
       }
     }
   }
 }
Пример #6
0
  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;
  }
Пример #7
0
 public void parseChildren(Element e) {
   try {
     NodeList nl = e.getChildNodes();
     for (int i = 0; i < nl.getLength(); i++) {
       // parse Elements only
       if ((nl.item(i).getNodeType() == Node.ELEMENT_NODE)) {
         Element elm = (Element) nl.item(i);
         String tag = elm.getTagName();
         if (tag.equals("canvas")) {
           parseChildren(elm);
         } else if (tag.equals("label")) {
           parseLabel(elm);
         } else if (tag.equals("textfield")) {
           parseTextField(elm);
         } else if (tag.equals("button")) {
           parseButton(elm);
         } else if (tag.equals("textarea")) {
           parseTextArea(elm);
         } else if (tag.equals("progressbar")) {
           parseProgressBar(elm);
         }
       }
     }
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
Пример #8
0
  @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"));
  }
Пример #9
0
  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);
    }
  }
Пример #10
0
  /*
   * 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")
              + "&amp;xsl=metadata_to_html_full</query>");
    } else {
      out.println(
          "<query>owner=" + e.getAttribute("query") + "&amp;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>");
  }
  /**
   * 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);
  }
Пример #12
0
 /*
  * 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;
 }
 /**
  * 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);
 }
 /**
  * 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);
 }
Пример #15
0
  /**
   * @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;
  }
Пример #16
0
 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;
 }
Пример #17
0
  /**
   * ** 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;
  }
Пример #18
0
  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;
  }
Пример #19
0
  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;
  }
Пример #20
0
  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;
  }
Пример #21
0
 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);
     }
   }
 }
Пример #22
0
  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;
  }
Пример #23
0
  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;
  }
Пример #24
0
    @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);
 }
Пример #26
0
  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;
  }
Пример #27
0
  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.");
  }
Пример #28
0
  @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);
  }
Пример #29
0
 public void parseBorder(JComponent c, Element elm) {
   if (elm.getTagName().equals("border")) {
     String type = elm.getAttribute("type");
     if (type.equals("empty")) {
       c.setBorder(new EmptyBorder(2, 2, 2, 2));
     } else if (type.equals("titled")) {
       String title = elm.getAttribute("title");
       c.setBorder(new TitledBorder(title));
     } else if (type.equals("beveled")) {
       int btype = Integer.parseInt(elm.getAttribute("bevel"));
       c.setBorder(new BevelBorder(btype));
     }
   } else {
     NodeList nl = elm.getElementsByTagName("border");
     for (int n = 0; n < nl.getLength(); n++) {
       parseBorder(c, (Element) nl.item(n));
     }
   }
 }
Пример #30
0
  /**
   * Runs the test case.
   *
   * @throws Throwable Any uncaught exception causes test to fail
   */
  public void runTest() throws Throwable {
    Document doc;
    DOMImplementation domImpl;
    Document newDoc;
    String namespaceURI;
    DocumentType nullDocType = null;

    Element docElem;
    String rootNS;
    String rootName;
    String qname;
    doc = (Document) load("hc_staff", false);
    docElem = doc.getDocumentElement();
    rootNS = docElem.getNamespaceURI();
    rootName = docElem.getTagName();
    domImpl = doc.getImplementation();
    qname = "dom3:" + rootName;
    newDoc = domImpl.createDocument(rootNS, qname, nullDocType);
    namespaceURI = newDoc.lookupNamespaceURI("dom3");
    assertEquals("nodelookupnamespaceuri02", rootNS, namespaceURI);
  }