Esempio n. 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;
  }
Esempio n. 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;
  }
Esempio n. 3
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;
  }
  /**
   * 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);
  }
Esempio n. 5
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>");
  }
Esempio n. 6
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);
 }
Esempio n. 9
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;
  }
Esempio n. 10
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;
  }
Esempio n. 11
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;
  }
Esempio n. 12
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;
  }
Esempio n. 13
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;
  }
Esempio n. 14
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;
  }
 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);
     }
   }
 }
Esempio n. 16
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;
  }
 /**
  * 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);
 }
Esempio n. 18
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.");
  }
Esempio n. 19
0
  @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;
  }
 /**
  * Unmarshall a Chromosome instance from a given XML Element representation.
  *
  * @param a_activeConfiguration current Configuration object
  * @param a_xmlElement the XML Element representation of the Chromosome
  * @return a new Chromosome instance setup with the data from the XML Element representation
  * @throws ImproperXMLException if the given Element is improperly structured or missing data
  * @throws UnsupportedRepresentationException if the actively configured Gene implementation does
  *     not support the string representation of the alleles used in the given XML document
  * @throws GeneCreationException if there is a problem creating or populating a Gene instance
  * @author Neil Rotstan
  * @since 1.0
  */
 public static Gene[] getGenesFromElement(
     Configuration a_activeConfiguration, Element a_xmlElement)
     throws ImproperXMLException, UnsupportedRepresentationException, GeneCreationException {
   // Do some sanity checking. Make sure the XML Element isn't null and
   // that it in fact represents a set of genes.
   // -----------------------------------------------------------------
   if (a_xmlElement == null || !(a_xmlElement.getTagName().equals(GENES_TAG))) {
     throw new ImproperXMLException(
         "Unable to build Chromosome instance from XML Element: "
             + "given Element is not a 'genes' element.");
   }
   List genes = Collections.synchronizedList(new ArrayList());
   // Extract the nested gene elements.
   // ---------------------------------
   NodeList geneElements = a_xmlElement.getElementsByTagName(GENE_TAG);
   if (geneElements == null) {
     throw new ImproperXMLException(
         "Unable to build Gene instances from XML Element: "
             + "'"
             + GENE_TAG
             + "'"
             + " sub-elements not found.");
   }
   // For each gene, get the class attribute so we know what class
   // to instantiate to represent the gene instance, and then find
   // the child text node, which is where the string representation
   // of the allele is located, and extract the representation.
   // -------------------------------------------------------------
   int numberOfGeneNodes = geneElements.getLength();
   for (int i = 0; i < numberOfGeneNodes; i++) {
     Element thisGeneElement = (Element) geneElements.item(i);
     thisGeneElement.normalize();
     // Fetch the class attribute and create an instance of that
     // class to represent the current gene.
     // --------------------------------------------------------
     String geneClassName = thisGeneElement.getAttribute(CLASS_ATTRIBUTE);
     Gene thisGeneObject;
     Class geneClass = null;
     try {
       geneClass = Class.forName(geneClassName);
       try {
         Constructor constr = geneClass.getConstructor(new Class[] {Configuration.class});
         thisGeneObject = (Gene) constr.newInstance(new Object[] {a_activeConfiguration});
       } catch (NoSuchMethodException nsme) {
         // Try it by calling method newGeneInternal.
         // -----------------------------------------
         Constructor constr = geneClass.getConstructor(new Class[] {});
         thisGeneObject = (Gene) constr.newInstance(new Object[] {});
         thisGeneObject =
             (Gene)
                 PrivateAccessor.invoke(
                     thisGeneObject, "newGeneInternal", new Class[] {}, new Object[] {});
       }
     } catch (Throwable e) {
       throw new GeneCreationException(geneClass, e);
     }
     // Find the text node and fetch the string representation of
     // the allele.
     // ---------------------------------------------------------
     NodeList children = thisGeneElement.getChildNodes();
     int childrenSize = children.getLength();
     String alleleRepresentation = null;
     for (int j = 0; j < childrenSize; j++) {
       Element alleleElem = (Element) children.item(j);
       if (alleleElem.getTagName().equals(ALLELE_TAG)) {
         alleleRepresentation = alleleElem.getAttribute("value");
       }
       if (children.item(j).getNodeType() == Node.TEXT_NODE) {
         // We found the text node. Extract the representation.
         // ---------------------------------------------------
         alleleRepresentation = children.item(j).getNodeValue();
         break;
       }
     }
     // Sanity check: Make sure the representation isn't null.
     // ------------------------------------------------------
     if (alleleRepresentation == null) {
       throw new ImproperXMLException(
           "Unable to build Gene instance from XML Element: "
               + "value (allele) is missing representation.");
     }
     // Now set the value of the gene to that reflect the
     // string representation.
     // -------------------------------------------------
     try {
       thisGeneObject.setValueFromPersistentRepresentation(alleleRepresentation);
     } catch (UnsupportedOperationException e) {
       throw new GeneCreationException(
           "Unable to build Gene because it does not support the "
               + "setValueFromPersistentRepresentation() method.");
     }
     // Finally, add the current gene object to the list of genes.
     // ----------------------------------------------------------
     genes.add(thisGeneObject);
   }
   return (Gene[]) genes.toArray(new Gene[genes.size()]);
 }
  /**
   * Edit the properties of a resource. The updates must refer to a Document containing a WebDAV
   * propertyupdates element as the document root.
   *
   * @param updates an XML Document containing propertyupdate elements
   * @return the result of making the updates describing the edits to be made.
   * @exception com.ibm.webdav.WebDAVException
   */
  public MultiStatus setProperties(Document propertyUpdates) throws WebDAVException {
    // create a MultiStatus to hold the results. It will hold a MethodResponse
    // for each update, and one for the method as a whole
    MultiStatus multiStatus = new MultiStatus();
    boolean errorsOccurred = false;

    // first, load the properties so they can be edited
    Document propertiesDocument = resource.loadProperties();
    Element properties = (Element) propertiesDocument.getDocumentElement();

    // be sure the updates have at least one update
    Element propertyupdate = (Element) propertyUpdates.getDocumentElement();
    String tagName = propertyupdate.getNamespaceURI() + propertyupdate.getLocalName();

    if (!tagName.equals("DAV:propertyupdate")) {
      throw new WebDAVException(
          WebDAVStatus.SC_UNPROCESSABLE_ENTITY, "missing propertyupdate element");
    }

    NodeList updates = propertyupdate.getChildNodes();

    if (updates.getLength() == 0) {
      throw new WebDAVException(WebDAVStatus.SC_UNPROCESSABLE_ENTITY, "no updates in request");
    }

    Vector propsGood = new Vector(); // a list of properties that

    // were patched correctly or would have been if another
    // property hadn't gone bad.
    // apply the updates
    Node temp = null;

    for (int i = 0; i < updates.getLength(); i++) {
      temp = updates.item(i);

      // skip any ignorable TXText elements
      if (!(temp.getNodeType() == Node.ELEMENT_NODE)) {
        continue;
      }

      Element update = (Element) temp;
      int updateCommand = -1;
      tagName = update.getNamespaceURI() + update.getLocalName();

      if (tagName.equals("DAV:set")) {
        updateCommand = set;
      } else if (tagName.equals("DAV:remove")) {
        updateCommand = remove;
      } else {
        throw new WebDAVException(
            WebDAVStatus.SC_UNPROCESSABLE_ENTITY,
            update.getTagName() + " is not a valid property update request");
      }

      // iterate through the props in the set or remove element and update the
      // properties as directed
      Element prop = (Element) update.getElementsByTagNameNS("DAV:", "prop").item(0);

      if (prop == null) {
        throw new WebDAVException(
            WebDAVStatus.SC_UNPROCESSABLE_ENTITY, "no propeprties in update request");
      }

      NodeList propsToUpdate = prop.getChildNodes();

      for (int j = 0; j < propsToUpdate.getLength(); j++) {
        temp = propsToUpdate.item(j);

        // skip any TXText elements??
        if (!(temp.getNodeType() == Node.ELEMENT_NODE)) {
          continue;
        }

        Element propToUpdate = (Element) temp;

        // find the property in the properties element
        Element property = null;
        PropertyName propertyName = new PropertyName(propToUpdate);

        if (((Element) propToUpdate).getNamespaceURI() != null) {
          property =
              (Element)
                  properties
                      .getElementsByTagNameNS(
                          propToUpdate.getNamespaceURI(), propToUpdate.getLocalName())
                      .item(0);
        } else {
          property = (Element) properties.getElementsByTagName(propToUpdate.getTagName()).item(0);
        }

        boolean liveone = isLive(propertyName.asExpandedString());

        if (liveone) {
          errorsOccurred = true;

          PropertyResponse response = new PropertyResponse(resource.getURL().toString());
          response.addProperty(propertyName, propToUpdate, WebDAVStatus.SC_FORBIDDEN);
          multiStatus.addResponse(response);
        }

        // do the update
        if (updateCommand == set) {
          if (property != null) {
            try {
              properties.removeChild(property);
            } catch (DOMException exc) {
            }
          }

          if (!liveone) {
            // I don't think we're allowed to update live properties
            //    here.  Doing so effects the cache.  A case in
            //    point is the lockdiscoveryproperty.  properties
            //    is actually the properites cache "document" of this
            //    resource.  Even though we don't "save" the request
            //    if it includes live properties, we don't remove
            //    it from the cache after we'd set it here, so it
            //    can affect other queries. (jlc 991002)
            properties.appendChild(propertiesDocument.importNode(propToUpdate, true));

            propsGood.addElement(propToUpdate);
          }
        } else if (updateCommand == remove) {
          try {
            if (property != null) {
              properties.removeChild(property);
              propsGood.addElement(propToUpdate);
            }
          } catch (DOMException exc) {
          }
        }
      }
    }

    {
      Enumeration els = propsGood.elements();

      for (; els.hasMoreElements(); ) {
        Object ob1 = els.nextElement();
        Element elProp = (Element) ob1;
        PropertyName pn = new PropertyName(elProp);
        PropertyResponse response = new PropertyResponse(resource.getURL().toString());
        response.addProperty(
            pn,
            (Element) elProp.cloneNode(false),
            (errorsOccurred ? WebDAVStatus.SC_FAILED_DEPENDENCY : WebDAVStatus.SC_OK));

        // todo: add code for responsedescription
        multiStatus.addResponse(response);
      }
    }

    // write out the properties
    if (!errorsOccurred) {
      resource.saveProperties(propertiesDocument);
    }

    return multiStatus;
  }
Esempio n. 22
0
  /**
   * Reads an XML element into a bean property by first locating the XML element 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 readProperty(Object ob, PropertyDescriptor desc, NodeList nodes, NamedNodeMap attrs)
      throws IOException {
    int numAttrs = attrs.getLength();

    for (int i = 0; i < numAttrs; i++) {
      // See if the attribute name matches the property name
      if (namesMatch(desc.getName(), attrs.item(i).getNodeName())) {
        // Get the method used to set this property
        Method setter = desc.getWriteMethod();

        // If this object has no setter, don't bother writing it
        if (setter == null) continue;

        // Get the value of the property
        Object obValue = getObjectValue(desc, attrs.item(i).getNodeValue());
        if (obValue != null) {
          try {
            // Set the property value
            setter.invoke(ob, new Object[] {obValue});
          } 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());
          }
        }

        return;
      }
    }

    int numNodes = nodes.getLength();

    Vector arrayBuild = null;

    for (int i = 0; i < numNodes; i++) {
      Node node = nodes.item(i);

      // If this node isn't an element, skip it
      if (!(node instanceof Element)) continue;

      Element element = (Element) node;

      // See if the tag name matches the property name
      if (namesMatch(desc.getName(), element.getTagName())) {
        // Get the method used to set this property
        Method setter = desc.getWriteMethod();

        // If this object has no setter, don't bother writing it
        if (setter == null) continue;

        // Get the value of the property
        Object obValue = getObjectValue(desc, element);

        // 070201 MAW: Modified from change submitted by Steve Poulson
        if (setter.getParameterTypes()[0].isArray()) {
          if (arrayBuild == null) {
            arrayBuild = new Vector();
          }
          arrayBuild.addElement(obValue);

          // 070201 MAW: Go ahead and read through the rest of the nodes in case
          //             another one matches the array. This has the effect of skipping
          //             over the "return" statement down below
          continue;
        }

        if (obValue != null) {
          try {
            // Set the property value
            setter.invoke(ob, new Object[] {obValue});
          } 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());
          }
        }
        return;
      }
    }

    // If we build a vector of array members, convert the vector into
    // an array and save it in the property
    if (arrayBuild != null) {
      // Get the method used to set this property
      Method setter = desc.getWriteMethod();

      if (setter == null) return;

      Object[] obValues = (Object[]) Array.newInstance(desc.getPropertyType(), arrayBuild.size());

      arrayBuild.copyInto(obValues);

      try {
        setter.invoke(ob, new Object[] {obValues});
      } 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());
      }

      return;
    }
  }
Esempio n. 23
0
  /**
   * ** Returns a ReverseGeocode instance containing address information ** @param gp The GeoPoint
   * ** @return The ReverseGeocode instance
   */
  private ReverseGeocode getAddressReverseGeocode(GeoPoint gp, String localeStr) {

    /* URL */
    String url = this.getAddressReverseGeocodeURL(gp);
    Print.logInfo("Address URL: " + url);

    /* create XML document */
    Document xmlDoc = GetXMLDocument(url);
    if (xmlDoc == null) {
      return null;
    }

    /* create ReverseGeocode response */
    Element reversegeocode = xmlDoc.getDocumentElement();
    if (!reversegeocode.getTagName().equalsIgnoreCase(TAG_reversegeocode)) {
      return null;
    }

    /* init */
    String address_val = null; // null address
    String house_val = null; // house number
    String road_val = null; // street name
    String city_val = null; // city name
    String county_val = null; // county name
    String state_val = null; // state/province
    String postcode_val = null; // postal code
    String country_name_val = null; // country name
    String country_code_val = null; // country code

    // full address
    NodeList resultList = XMLTools.getChildElements(reversegeocode, TAG_result);
    for (int r = 0; r < resultList.getLength(); r++) {
      Element result = (Element) resultList.item(r);
      // String osmType = XMLTools.getAttribute(result, ATTR_osm_type, null, false);
      address_val = XMLTools.getNodeText(result, " ", false);
      break; // only the first element
    }

    // address components
    NodeList addresspartsList = XMLTools.getChildElements(reversegeocode, TAG_addressparts);
    for (int a = 0; (a < addresspartsList.getLength()); a++) {
      Element addressparts = (Element) addresspartsList.item(a);
      NodeList addresspartsChildren = addressparts.getChildNodes();
      for (int ac = 0; ac < addresspartsChildren.getLength(); ac++) {
        Node child = addresspartsChildren.item(ac);
        if (!(child instanceof Element)) {
          continue;
        }
        Element elem = (Element) child;
        String elemName = elem.getNodeName();
        if (elemName.equalsIgnoreCase(TAG_house)) {
          house_val = XMLTools.getNodeText(elem, " ", false);
        } else if (elemName.equalsIgnoreCase(TAG_tram)) {
          // ignore
        } else if (elemName.equalsIgnoreCase(TAG_road)) {
          road_val = XMLTools.getNodeText(elem, " ", false);
        } else if (elemName.equalsIgnoreCase(TAG_residential)) {
          // ignore
        } else if (elemName.equalsIgnoreCase(TAG_village)) {
          // ignore
        } else if (elemName.equalsIgnoreCase(TAG_town)) {
          if (StringTools.isBlank(city_val)) {
            city_val = XMLTools.getNodeText(elem, " ", false);
          }
        } else if (elemName.equalsIgnoreCase(TAG_city)) {
          city_val = XMLTools.getNodeText(elem, " ", false);
        } else if (elemName.equalsIgnoreCase(TAG_county)) {
          county_val = XMLTools.getNodeText(elem, " ", false);
        } else if (elemName.equalsIgnoreCase(TAG_postcode)) {
          postcode_val = XMLTools.getNodeText(elem, " ", false);
        } else if (elemName.equalsIgnoreCase(TAG_state)) {
          state_val = XMLTools.getNodeText(elem, " ", false);
        } else if (elemName.equalsIgnoreCase(TAG_country)) {
          country_name_val = XMLTools.getNodeText(elem, " ", false);
        } else if (elemName.equalsIgnoreCase(TAG_country_code)) {
          country_code_val = StringTools.trim(XMLTools.getNodeText(elem, " ", false)).toUpperCase();
        } else {
          // elemName unrecognized
        }
      }
      break; // only the first element
    }

    /* populate ReverseGeocode instance */
    ReverseGeocode rg = new ReverseGeocode();
    StringBuffer addr = new StringBuffer();
    // house number /road
    if (!StringTools.isBlank(house_val)) {
      addr.append(house_val);
      if (!StringTools.isBlank(road_val)) {
        addr.append(" ");
        addr.append(road_val);
        rg.setStreetAddress(house_val + " " + road_val);
      } else {
        rg.setStreetAddress(house_val);
      }
    } else if (!StringTools.isBlank(road_val)) {
      addr.append(road_val);
      rg.setStreetAddress(road_val);
    }
    // city/county
    if (!StringTools.isBlank(city_val)) {
      if (addr.length() > 0) {
        addr.append(", ");
      }
      addr.append(city_val);
      rg.setCity(city_val);
    }
    if (!StringTools.isBlank(county_val)) {
      if (StringTools.isBlank(city_val)) {
        // "city" not provided, at least include the "county"
        if (addr.length() > 0) {
          addr.append(", ");
        }
        addr.append("[").append(county_val).append("]");
      }
      // rg.setCounty(county_val);
    }
    // state/province
    if (!StringTools.isBlank(state_val)) {
      if (addr.length() > 0) {
        addr.append(", ");
      }
      addr.append(state_val);
      rg.setStateProvince(state_val);
      if (!StringTools.isBlank(postcode_val)) {
        addr.append(" ").append(postcode_val);
        rg.setPostalCode(postcode_val);
      }
    } else {
      if (!StringTools.isBlank(postcode_val)) {
        if (addr.length() > 0) {
          addr.append(", ");
        }
        addr.append(postcode_val);
        rg.setPostalCode(postcode_val);
      }
    }
    // country
    if (!StringTools.isBlank(country_code_val)) {
      if (country_code_val.equalsIgnoreCase("US")) {
        // if (addr.length() > 0) { addr.append(", "); }
        // addr.append("USA");
      } else if (!StringTools.isBlank(country_name_val)) {
        if (addr.length() > 0) {
          addr.append(", ");
        }
        addr.append(country_name_val);
      } else {
        if (addr.length() > 0) {
          addr.append(", ");
        }
        addr.append(country_code_val);
      }
      rg.setCountryCode(country_code_val);
    }
    // full address
    rg.setFullAddress(addr.toString());

    return rg;
  }
Esempio n. 24
0
  // 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;
  }
Esempio n. 25
0
  /* 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;
  }
Esempio n. 26
0
  /**
   * 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());
    }
  }
Esempio n. 27
0
  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;
  }