// Gets the specified XML Schema doc if one is mentioned in the file
  public static File getSchemaFile(Document xmlDoc) {
    /** @todo Must be an easier way of doing this... */
    logger.logComment("Getting schema file for: " + xmlDoc.getDocumentURI());

    NodeList nl = xmlDoc.getChildNodes();
    for (int j = 0; j < nl.getLength(); j++) {
      Node node = nl.item(j);
      logger.logComment("Type: " + node.getNodeType() + "Name: " + node.getNodeName());
      if (node.getNodeName().equals(XML_STYLESHEET_NODE)) {
        String nodeVal = node.getNodeValue();

        logger.logComment("Looking at: " + nodeVal);
        String xslFileName =
            nodeVal.substring(nodeVal.indexOf("href=\"") + 6, nodeVal.length() - 1);
        File xslFile = new File(xslFileName);
        return xslFile;
      }

      if (node.getAttributes().getLength() > 0) {
        logger.logComment("Attributes: " + node.getAttributes());
        if (node.getAttributes().getNamedItem(XML_SCHEMA_LOC_ATTR) != null) {
          String locString = node.getAttributes().getNamedItem(XML_SCHEMA_LOC_ATTR).getNodeValue();
          logger.logComment("Loc string: " + locString);
          String file = locString.split("\\s")[1];
          return new File(file);
        }
      }
    }
    logger.logError("No node found with name: " + XML_STYLESHEET_NODE);
    return null;
  }
 public static final Map parseFrame(Node node) {
   NodeList bones = node.getChildNodes();
   Map bone_infos = new HashMap();
   for (int i = 0; i < bones.getLength(); i++) {
     Node bone = bones.item(i);
     if (bone.getNodeName().equals("transform")) {
       String name = bone.getAttributes().getNamedItem("name").getNodeValue();
       float[] matrix = new float[16];
       matrix[0 * 4 + 0] = getAttrFloat(bone, "m00");
       matrix[0 * 4 + 1] = getAttrFloat(bone, "m01");
       matrix[0 * 4 + 2] = getAttrFloat(bone, "m02");
       matrix[0 * 4 + 3] = getAttrFloat(bone, "m03");
       matrix[1 * 4 + 0] = getAttrFloat(bone, "m10");
       matrix[1 * 4 + 1] = getAttrFloat(bone, "m11");
       matrix[1 * 4 + 2] = getAttrFloat(bone, "m12");
       matrix[1 * 4 + 3] = getAttrFloat(bone, "m13");
       matrix[2 * 4 + 0] = getAttrFloat(bone, "m20");
       matrix[2 * 4 + 1] = getAttrFloat(bone, "m21");
       matrix[2 * 4 + 2] = getAttrFloat(bone, "m22");
       matrix[2 * 4 + 3] = getAttrFloat(bone, "m23");
       matrix[3 * 4 + 0] = getAttrFloat(bone, "m30");
       matrix[3 * 4 + 1] = getAttrFloat(bone, "m31");
       matrix[3 * 4 + 2] = getAttrFloat(bone, "m32");
       matrix[3 * 4 + 3] = getAttrFloat(bone, "m33");
       bone_infos.put(name, matrix);
     }
   }
   return bone_infos;
 }
Example #3
0
      public void onDocument(Document document, String xpath) throws XmlParserException {
        if (xpath.equals(XPATH_IPEAK)) {
          Node node = document.getFirstChild();

          // check whether we're getting the correct ipeak
          Node typeattribute = node.getAttributes().getNamedItem(PeakMLWriter.TYPE);
          if (typeattribute == null)
            throw new XmlParserException("Failed to locate the type attribute.");
          if (!typeattribute.getNodeValue().equals(PeakMLWriter.TYPE_BACKGROUNDION))
            throw new XmlParserException(
                "IPeak ("
                    + typeattribute.getNodeValue()
                    + ") is not of type: '"
                    + PeakMLWriter.TYPE_BACKGROUNDION
                    + "'");

          // parse this node as a mass chromatogram
          BackgroundIon<? extends Peak> backgroundion = parseBackgroundIon(node);
          if (backgroundion != null) peaks.add(backgroundion);

          //
          if (_listener != null && result.header != null && result.header.getNrPeaks() != 0)
            _listener.update((100. * index++) / result.header.getNrPeaks());
        } else if (xpath.equals(XPATH_HEADER)) {
          result.header = parseHeader(document.getFirstChild());
        }
      }
Example #4
0
 /**
  * Get a list of the names for all of the attributes for this node.
  *
  * @webref xml:method
  * @brief Returns a list of names of all attributes as an array
  */
 public String[] listAttributes() {
   NamedNodeMap nnm = node.getAttributes();
   String[] outgoing = new String[nnm.getLength()];
   for (int i = 0; i < outgoing.length; i++) {
     outgoing[i] = nnm.item(i).getNodeName();
   }
   return outgoing;
 }
Example #5
0
 public static void traverseAMLforObjectNames(
     HashMap partialMap, Node currentNode, HashMap ObjDef_LinkId, HashMap ModelId_ModelType) {
   if (currentNode.hasChildNodes()) {
     for (int i = 0; i < currentNode.getChildNodes().getLength(); i++) {
       Node currentChild = currentNode.getChildNodes().item(i);
       if (currentChild.getNodeName().equals("Group")) {
         traverseAMLforObjectNames(partialMap, currentChild, ObjDef_LinkId, ModelId_ModelType);
       }
       if (currentChild.getNodeName().equals("Model")) {
         if (currentChild.hasAttributes()) {
           String mid = currentChild.getAttributes().getNamedItem("Model.ID").getNodeValue();
           String type = currentChild.getAttributes().getNamedItem("Model.Type").getNodeValue();
           ModelId_ModelType.put(mid, type);
         }
         // traverseAMLforObjectNames(partialMap, currentChild,
         // ObjDef_LinkId);
       }
       if (currentChild.getNodeName().equals("ObjDef")) {
         String id = currentChild.getAttributes().getNamedItem("ObjDef.ID").getNodeValue();
         NodeList currentChildren = currentChild.getChildNodes();
         String ObjName = "";
         for (int k = 0; k < currentChildren.getLength(); k++) {
           Node Child = currentChildren.item(k);
           if (!Child.getNodeName().equals("AttrDef")) {
             continue;
           } else if (!Child.getAttributes()
               .getNamedItem("AttrDef.Type")
               .getNodeValue()
               .equals("AT_NAME")) {
             continue;
           } else if (Child.hasChildNodes()) {
             for (int l = 0; l < Child.getChildNodes().getLength(); l++) {
               if (!(Child.getChildNodes().item(l).getNodeName().equals("AttrValue"))) {
                 continue;
               } else {
                 ObjName = getTextContent(Child.getChildNodes().item(l));
                 ObjName = ObjName.replaceAll("\n", "\\\\n");
                 break;
               }
             }
           }
         }
         partialMap.put(id, ObjName);
         for (int j = 0; j < currentChild.getAttributes().getLength(); j++) {
           if (currentChild.getAttributes().item(j).getNodeName().equals("LinkedModels.IdRefs")) {
             String links =
                 currentChild.getAttributes().getNamedItem("LinkedModels.IdRefs").getNodeValue();
             /*
              * if (links.indexOf(" ") > -1) {
              * Message.add("yes, yes, yes"); links =
              * links.substring(0, links.indexOf(" ")); }
              */
             ObjDef_LinkId.put(id, links);
           }
         }
       }
     }
   }
 }
 public String getAtributo(Node nodo, String nombreAtributo) {
   NamedNodeMap atts;
   atts = nodo.getAttributes();
   if (atts == null) return null;
   for (int i = 0; i < atts.getLength(); i++) {
     Node atributo = atts.item(i);
     if (atributo.getNodeName().equalsIgnoreCase(nombreAtributo)) return atributo.getNodeValue();
   }
   return null;
 }
Example #7
0
 private static IPeak parseIPeak(Node parent) throws XmlParserException {
   Node type = parent.getAttributes().getNamedItem(PeakMLWriter.TYPE);
   if (type == null) return null;
   else if (type.getNodeValue().equals(PeakMLWriter.TYPE_PEAKSET)) return parsePeakSet(parent);
   else if (type.getNodeValue().equals(PeakMLWriter.TYPE_BACKGROUNDION))
     return parseBackgroundIon(parent);
   else if (type.getNodeValue().equals(PeakMLWriter.TYPE_MASSCHROMATOGRAM))
     return parseMassChromatogram(parent);
   else return null;
 }
Example #8
0
 public String getString(String name, String defaultValue) {
   NamedNodeMap attrs = node.getAttributes();
   if (attrs != null) {
     Node attr = attrs.getNamedItem(name);
     if (attr != null) {
       return attr.getNodeValue();
     }
   }
   return defaultValue;
 }
Example #9
0
 private static final Skeleton parseSkeleton(Node skel_node) {
   Map name_to_bone_map = new HashMap();
   Map initial_pose =
       AnimationLoader.parseFrame(ConvertToBinary.getNodeByName("init_pose", skel_node));
   NodeList bone_list = ConvertToBinary.getNodeByName("bones", skel_node).getChildNodes();
   Map bone_parent_map = new HashMap();
   for (int i = 0; i < bone_list.getLength(); i++) {
     Node bone_node = bone_list.item(i);
     if (bone_node.getNodeName().equals("bone")) {
       String bone_name = bone_node.getAttributes().getNamedItem("name").getNodeValue();
       String bone_parent_name = bone_node.getAttributes().getNamedItem("parent").getNodeValue();
       // System.out.println("bone name = " + bone_name + " parent name = " + bone_parent_name);
       bone_parent_map.put(bone_name, bone_parent_name);
     }
   }
   Map bone_children_map = new HashMap();
   Iterator it = bone_parent_map.keySet().iterator();
   String root = null;
   while (it.hasNext()) {
     String name = (String) it.next();
     String parent = (String) bone_parent_map.get(name);
     if (bone_parent_map.get(parent) == null) {
       if (root != null) {
         System.out.println(
             "WARNING: Multiple roots in skeleton, root = "
                 + root
                 + ", additional root = "
                 + name);
         parent = root;
         bone_parent_map.put(name, parent);
       } else root = name;
     }
     List parent_children = (List) bone_children_map.get(parent);
     if (parent_children == null) {
       parent_children = new ArrayList();
       bone_children_map.put(parent, parent_children);
     }
     parent_children.add(name);
   }
   Bone bone_root = buildBone((byte) 0, bone_children_map, root, name_to_bone_map);
   return new Skeleton(bone_root, initial_pose, name_to_bone_map);
 }
Example #10
0
    /** Возвращает имя метода. */
    public String getName() {

      /** Получаем атрибуты узла метода. */
      NamedNodeMap attributes = node.getAttributes();

      /** Получаем узел аттрибута. */
      Node nameAttrib = attributes.getNamedItem("name");

      /** Возвращаем значение атрибута. */
      return nameAttrib.getNodeValue();
    }
Example #11
0
 /**
  * Populates LOCALES list with contents of xml.
  *
  * @param list the configuration list
  */
 private static void parseLocales(NodeList list) {
   for (int i = 0; i < list.getLength(); ++i) {
     Node node = list.item(i);
     NamedNodeMap attributes = node.getAttributes();
     String label = ((Attr) attributes.getNamedItem("label")).getValue();
     String code = ((Attr) attributes.getNamedItem("isoCode")).getValue();
     String dictLocation = ((Attr) attributes.getNamedItem("dictionaryUrl")).getValue();
     try {
       LOCALES.add(new Locale(label, code, new URL(dictLocation)));
     } catch (MalformedURLException exc) {
       logger.warn(
           "Unable to parse dictionary location of " + label + " (" + dictLocation + ")", exc);
     }
   }
 }
Example #12
0
      public void onDocument(Document document, String xpath) throws XmlParserException {
        if (xpath.equals(XPATH_IPEAK)) {
          Node node = document.getChildNodes().item(0);

          // check whether we're getting the correct ipeak
          Node typeattribute = node.getAttributes().getNamedItem(PeakMLWriter.TYPE);
          if (typeattribute == null)
            throw new XmlParserException("Failed to locate a type attribute.");

          // ...
          //					IPeak peak = (_loadall ? parseIPeak(node) : parseCentroid(node));
          IPeak peak = parseIPeak(node);
          if (peak != null) _listener.onIPeak(peak);
        } else if (xpath.equals(XPATH_HEADER)) {
          Header header = parseHeader(document.getFirstChild());
          _listener.onHeader(header);
        }
      }
Example #13
0
      public void onDocument(Document document, String xpath) throws XmlParserException {
        if (xpath.equals(XPATH_IPEAK)) {
          Node node = document.getChildNodes().item(0);

          // check whether we're getting the correct ipeak
          Node typeattribute = node.getAttributes().getNamedItem(PeakMLWriter.TYPE);
          if (typeattribute == null
              || !typeattribute.getNodeValue().equals(PeakMLWriter.TYPE_PEAKSET))
            throw new XmlParserException("Failed to locate a type attribute.");

          // parse this node as a mass chromatogram
          IPeakSet<? extends IPeak> peakset = parsePeakSet(node);
          if (peakset != null) peaks.add(peakset);

          //
          if (_listener != null && result.header != null && result.header.getNrPeaks() != 0)
            _listener.update((100. * index++) / result.header.getNrPeaks());
        } else if (xpath.equals(XPATH_HEADER)) {
          result.header = parseHeader(document.getFirstChild());
        }
      }
 /**
  * @param node
  * @param indent
  */
 public static String toString(Node node, int indent) {
   StringBuffer str = new StringBuffer();
   for (int i = 0; i < indent; ++i) str.append("    ");
   str.append(node);
   if (node.hasAttributes()) {
     NamedNodeMap attrs = node.getAttributes();
     for (int j = 0; j < attrs.getLength(); ++j) {
       Node attr = attrs.item(j);
       // str.append(toString(attr,indent+2));
       str.append(" ");
       str.append(attr);
     }
   }
   str.append("\n");
   ++indent;
   for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
     str.append(toString(child, indent));
     // str.append("\n");
   }
   return str.toString();
 }
Example #15
0
 private static final float getAttrFloat(Node node, String name) {
   return Float.parseFloat(node.getAttributes().getNamedItem(name).getNodeValue());
 }
 /**
  * @param list
  * @param parent
  * @exception NumberFormatException
  * @exception DicomException
  */
 void addAttributesFromNodeToList(AttributeList list, Node parent)
     throws NumberFormatException, DicomException {
   if (parent != null) {
     Node node = parent.getFirstChild();
     while (node != null) {
       String elementName = node.getNodeName();
       NamedNodeMap attributes = node.getAttributes();
       if (attributes != null) {
         Node vrNode = attributes.getNamedItem("vr");
         Node groupNode = attributes.getNamedItem("group");
         Node elementNode = attributes.getNamedItem("element");
         if (vrNode != null && groupNode != null && elementNode != null) {
           String vrString = vrNode.getNodeValue();
           String groupString = groupNode.getNodeValue();
           String elementString = elementNode.getNodeValue();
           if (vrString != null && groupString != null && elementString != null) {
             byte[] vr = vrString.getBytes();
             int group = Integer.parseInt(groupString, 16);
             int element = Integer.parseInt(elementString, 16);
             AttributeTag tag = new AttributeTag(group, element);
             if ((group % 2 == 0 && element == 0)
                 || (group == 0x0008 && element == 0x0001)
                 || (group == 0xfffc && element == 0xfffc)) {
               // System.err.println("ignoring group length or length to end or dataset trailing
               // padding "+tag);
             } else {
               if (vrString.equals("SQ")) {
                 SequenceAttribute a = new SequenceAttribute(tag);
                 // System.err.println("Created "+a);
                 if (node.hasChildNodes()) {
                   Node childNode = node.getFirstChild();
                   while (childNode != null) {
                     String childNodeName = childNode.getNodeName();
                     // System.err.println("childNodeName = "+childNodeName);
                     if (childNodeName != null && childNodeName.equals("Item")) {
                       // should check item number, but ignore for now :(
                       // System.err.println("Adding item to sequence");
                       AttributeList itemList = new AttributeList();
                       addAttributesFromNodeToList(itemList, childNode);
                       a.addItem(itemList);
                     }
                     // else may be a #text element in between
                     childNode = childNode.getNextSibling();
                   }
                 }
                 // System.err.println("Sequence Attribute is "+a);
                 list.put(tag, a);
               } else {
                 Attribute a = AttributeFactory.newAttribute(tag, vr);
                 // System.err.println("Created "+a);
                 if (node.hasChildNodes()) {
                   Node childNode = node.getFirstChild();
                   while (childNode != null) {
                     String childNodeName = childNode.getNodeName();
                     // System.err.println("childNodeName = "+childNodeName);
                     if (childNodeName != null && childNodeName.equals("value")) {
                       // should check value number, but ignore for now :(
                       String value = childNode.getTextContent();
                       // System.err.println("Value value = "+value);
                       if (value != null) {
                         value =
                             StringUtilities.removeLeadingOrTrailingWhitespaceOrISOControl(
                                 value); // just in case
                         a.addValue(value);
                       }
                     }
                     // else may be a #text element in between
                     childNode = childNode.getNextSibling();
                   }
                 }
                 // System.err.println("Attribute is "+a);
                 list.put(tag, a);
               }
             }
           }
         }
       }
       node = node.getNextSibling();
     }
   }
 }
  /**
   * @param list
   * @param document
   * @param parent
   */
  void addAttributesFromListToNode(AttributeList list, Document document, Node parent) {
    DicomDictionary dictionary = list.getDictionary();
    Iterator i = list.values().iterator();
    while (i.hasNext()) {
      Attribute attribute = (Attribute) i.next();
      AttributeTag tag = attribute.getTag();

      String elementName = dictionary.getNameFromTag(tag);
      if (elementName == null) {
        elementName = makeElementNameFromHexadecimalGroupElementValues(tag);
      }
      Node node = document.createElement(elementName);
      parent.appendChild(node);

      {
        Attr attr = document.createAttribute("group");
        attr.setValue(HexDump.shortToPaddedHexString(tag.getGroup()));
        node.getAttributes().setNamedItem(attr);
      }
      {
        Attr attr = document.createAttribute("element");
        attr.setValue(HexDump.shortToPaddedHexString(tag.getElement()));
        node.getAttributes().setNamedItem(attr);
      }
      {
        Attr attr = document.createAttribute("vr");
        attr.setValue(ValueRepresentation.getAsString(attribute.getVR()));
        node.getAttributes().setNamedItem(attr);
      }

      if (attribute instanceof SequenceAttribute) {
        int count = 0;
        Iterator si = ((SequenceAttribute) attribute).iterator();
        while (si.hasNext()) {
          SequenceItem item = (SequenceItem) si.next();
          Node itemNode = document.createElement("Item");
          Attr numberAttr = document.createAttribute("number");
          numberAttr.setValue(Integer.toString(++count));
          itemNode.getAttributes().setNamedItem(numberAttr);
          node.appendChild(itemNode);
          addAttributesFromListToNode(item.getAttributeList(), document, itemNode);
        }
      } else {
        // Attr attr = document.createAttribute("value");
        // attr.setValue(attribute.getDelimitedStringValuesOrEmptyString());
        // node.getAttributes().setNamedItem(attr);

        // node.appendChild(document.createTextNode(attribute.getDelimitedStringValuesOrEmptyString()));

        String values[] = null;
        try {
          values = attribute.getStringValues();
        } catch (DicomException e) {
          // e.printStackTrace(System.err);
        }
        if (values != null) {
          for (int j = 0; j < values.length; ++j) {
            Node valueNode = document.createElement("value");
            Attr numberAttr = document.createAttribute("number");
            numberAttr.setValue(Integer.toString(j + 1));
            valueNode.getAttributes().setNamedItem(numberAttr);
            valueNode.appendChild(document.createTextNode(values[j]));
            node.appendChild(valueNode);
          }
        }
      }
    }
  }
Example #18
0
 /**
  * Returns whether an attribute exists.
  *
  * @webref xml:method
  * @brief Checks whether or not an element has the specified attribute
  */
 public boolean hasAttribute(String name) {
   return (node.getAttributes().getNamedItem(name) != null);
 }
Example #19
0
  public void serializeNode(Node node, Writer writer, String indentLevel) throws IOException {
    // Determine action based on node type
    switch (node.getNodeType()) {
      case Node.DOCUMENT_NODE:
        writer.write("<?xml version = '1.0'?>"); // "<xml version=\"1.0\">");
        writer.write(lineSeparator);
        // recurse on each child
        NodeList nodes = node.getChildNodes();
        if (nodes != null) {
          for (int i = 0; i < nodes.getLength(); i++) {
            serializeNode(nodes.item(i), writer, "");
          }
        }

        /*
         *  Document doc = (Document)node;
         *  serializeNode(doc.getDocumentElement( ), writer, " ");
         */
        break;
      case Node.ELEMENT_NODE:
        String name = node.getNodeName();
        writer.write(indentLevel + "<" + name);
        NamedNodeMap attributes = node.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
          Node current = attributes.item(i);
          writer.write(" " + current.getNodeName() + "=\"" + current.getNodeValue() + "\"");
        }
        writer.write(">");
        // recurse on each child
        NodeList children = node.getChildNodes();
        if (children != null) {
          if ((children.item(0) != null) && (children.item(0).getNodeType() == Node.ELEMENT_NODE)) {
            writer.write(lineSeparator);
          }
          for (int i = 0; i < children.getLength(); i++) {
            serializeNode(children.item(i), writer, indentLevel + indent);
          }
          if ((children.item(0) != null)
              && (children.item(children.getLength() - 1).getNodeType() == Node.ELEMENT_NODE)) {
            writer.write(indentLevel);
          }
        }
        writer.write("</" + name + ">");
        writer.write(lineSeparator);
        break;
      case Node.TEXT_NODE:
        writer.write(node.getNodeValue());
        break;
      case Node.CDATA_SECTION_NODE:
        writer.write("<![CDATA[" + node.getNodeValue() + "]]>");
        break;
      case Node.COMMENT_NODE:
        writer.write(indentLevel + "<!-- " + node.getNodeValue() + " -->");
        writer.write(lineSeparator);
        break;
      case Node.PROCESSING_INSTRUCTION_NODE:
        writer.write("<?" + node.getNodeName() + " " + node.getNodeValue() + "?>");
        writer.write(lineSeparator);
        break;
      case Node.ENTITY_REFERENCE_NODE:
        writer.write("&" + node.getNodeName() + ";");
        break;
      case Node.DOCUMENT_TYPE_NODE:
        DocumentType docType = (DocumentType) node;
        writer.write("<!DOCTYPE " + docType.getName());
        if (docType.getPublicId() != null) {
          System.out.print(" PUBLIC \"" + docType.getPublicId() + "\" ");
        } else {
          writer.write(" SYSTEM ");
        }
        writer.write("\"" + docType.getSystemId() + "\">");
        writer.write(lineSeparator);
        break;
    }
  }
Example #20
0
 /**
  * Returns the number of attributes.
  *
  * @webref xml:method
  * @brief Counts the specified element's number of attributes
  */
 public int getAttributeCount() {
   return node.getAttributes().getLength();
 }
Example #21
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;
  }
Example #22
0
  private void processTxt(Node operation) {
    List<Node> targets = getChildNodes(operation, "target");
    List<Node> optionNodes = getChildNodes(operation, "opt");
    List<Node> separatorNode = getChildNodes(operation, "separator");
    if (targets.isEmpty() || optionNodes.isEmpty()) {
      return;
    }
    String defaultSeparator = "=";
    String globalSeparator = defaultSeparator;
    if (!separatorNode.isEmpty()) {
      globalSeparator = separatorNode.get(0).getTextContent();
      if (globalSeparator.length() != 1) {
        globalSeparator = defaultSeparator;
      }
    }
    Map<String, String> options = new HashMap<String, String>();
    Map<String, String> processedOptions = new HashMap<String, String>();
    for (int i = 0; i < optionNodes.size(); i++) {
      Node option = optionNodes.get(i);
      String name = option.getAttributes().getNamedItem("name").getNodeValue();
      String value = option.getTextContent();
      if (options.containsKey(name)) {
        options.remove(name);
      }
      options.put(name, value);
    }
    for (int t = 0; t < targets.size(); t++) {
      File target = new File(absolutePath(targets.get(t).getTextContent()));
      File tmpFile = new File(Utils.timestamp());
      BufferedWriter bw = null;
      BufferedReader br = null;
      try {
        Node separatorAttr = targets.get(t).getAttributes().getNamedItem("separator");
        String separator = (separatorAttr == null) ? globalSeparator : separatorAttr.getNodeValue();
        if (separator.length() != 1) {
          separator = globalSeparator;
        }
        bw = new BufferedWriter(new FileWriter(tmpFile));
        if (target.exists()) {
          br = new BufferedReader(new FileReader(target));
          for (String line; (line = br.readLine()) != null; ) {
            String[] parts = line.split(separator);
            if (parts.length < 2) {
              bw.write(line);
              bw.newLine();
              continue;
            }

            String optName = parts[0].trim();
            if (options.containsKey(optName)) {
              String optValue = options.get(optName);
              bw.write(optName + " " + separator + " " + optValue);
              bw.newLine();
              processedOptions.put(optName, optValue);
              options.remove(optName);
            } else if (processedOptions.containsKey(optName)) {
              bw.write(optName + " " + separator + " " + processedOptions.get(optName));
              bw.newLine();
            } else {
              bw.write(line);
              bw.newLine();
            }
          }
          br.close();
        }
        for (Map.Entry<String, String> entry : options.entrySet()) {
          bw.write(entry.getKey() + " " + separator + " " + entry.getValue());
          bw.newLine();
        }
        bw.close();
        FileUtils.copyFile(tmpFile, target);
        FileUtils.forceDelete(tmpFile);
      } catch (IOException ex) {
        Utils.onError(new Error.WriteTxtConfig(target.getPath()));
      }
    }
  }
Example #23
0
  /** Prints the specified node, recursively. */
  public String print(Node node) {

    // is there anything to do?
    if (node == null) {
      return sb.toString();
    }

    int type = node.getNodeType();
    switch (type) {
        // print document
      case Node.DOCUMENT_NODE:
        {
          return print(((Document) node).getDocumentElement());
          // out.flush();
          // break;
        }

        // print element with attributes
      case Node.ELEMENT_NODE:
        {
          sb.append('<');
          sb.append(node.getNodeName());
          Attr attrs[] = sortAttributes(node.getAttributes());
          for (int i = 0; i < attrs.length; i++) {
            Attr attr = attrs[i];
            sb.append(' ');
            sb.append(attr.getNodeName());
            sb.append("=\"");
            sb.append(normalize(attr.getNodeValue()));
            sb.append('"');
          }
          sb.append('>');
          NodeList children = node.getChildNodes();
          if (children != null) {
            int len = children.getLength();
            for (int i = 0; i < len; i++) {
              print(children.item(i));
            }
          }
          break;
        }

        // handle entity reference nodes
      case Node.ENTITY_REFERENCE_NODE:
        {
          if (canonical) {
            NodeList children = node.getChildNodes();
            if (children != null) {
              int len = children.getLength();
              for (int i = 0; i < len; i++) {
                print(children.item(i));
              }
            }
          } else {
            sb.append('&');
            sb.append(node.getNodeName());
            sb.append(';');
          }
          break;
        }

        // print cdata sections
      case Node.CDATA_SECTION_NODE:
        {
          if (canonical) {
            sb.append(normalize(node.getNodeValue()));
          } else {
            sb.append("<![CDATA[");
            sb.append(node.getNodeValue());
            sb.append("]]>");
          }
          break;
        }

        // print text
      case Node.TEXT_NODE:
        {
          sb.append(normalize(node.getNodeValue()));
          break;
        }

        // print processing instruction
      case Node.PROCESSING_INSTRUCTION_NODE:
        {
          sb.append("<?");
          sb.append(node.getNodeName());
          String data = node.getNodeValue();
          if (data != null && data.length() > 0) {
            sb.append(' ');
            sb.append(data);
          }
          sb.append("?>");
          break;
        }
        // handle entity reference nodes
      case Node.DOCUMENT_FRAGMENT_NODE:
        {
          NodeList children = node.getChildNodes();
          if (children != null) {
            int len = children.getLength();
            for (int i = 0; i < len; i++) {
              print(children.item(i));
            }
          }
          break;
        }
    }

    if (type == Node.ELEMENT_NODE) {
      sb.append("</");
      sb.append(node.getNodeName());
      sb.append('>');
    }

    return sb.toString();
  } // print(Node)
Example #24
0
  private static void parseNet(
      Node node,
      EPC net,
      HashMap ObjDef_Name,
      HashMap ObjDef_LinkId,
      HashMap function_LinkId,
      String ModelName)
      throws Exception {
    HashMap mapping = new HashMap();

    // read all nodes
    NodeList nodes = node.getChildNodes();
    net.setIdentifier(ModelName);
    // Message.add("here I am still happy");
    for (int i = 0; i < nodes.getLength(); i++) {
      Node n = nodes.item(i);
      if (!n.getNodeName().equals("ObjOcc")) {
        continue;
      }
      if (n.getAttributes().getNamedItem("SymbolNum") == null) {
        continue;
      }
      String symbolnum = n.getAttributes().getNamedItem("SymbolNum").getNodeValue();
      if (!(symbolnum.equals("ST_FUNC")
          || symbolnum.equals("ST_EV")
          || symbolnum.equals("ST_OPR_AND_1")
          || symbolnum.equals("ST_OPR_OR_1")
          || symbolnum.equals("ST_OPR_XOR_1"))) {
        continue;
      }

      String ObjDef = n.getAttributes().getNamedItem("ObjDef.IdRef").getNodeValue();
      String ownName = (String) ObjDef_Name.get(ObjDef);
      // Message.add("YES " +
      // n.getAttributes().getNamedItem("ObjOcc.ID").getNodeValue());
      String id = n.getAttributes().getNamedItem("ObjOcc.ID").getNodeValue();
      // Message.add(id + " " + ownName);
      if (ownName == null || ownName == "") {
        ownName = id.substring(7, 11);
      }
      if (symbolnum.equals("ST_FUNC")) {
        if (ObjDef_LinkId.containsKey(ObjDef)) {
          EPCSubstFunction sf =
              (EPCSubstFunction)
                  net.addFunction(
                      new EPCSubstFunction(new LogEvent(ownName, "unknown:normal"), net, null));
          sf.setIdentifier(ownName);
          mapping.put(id, sf);
          function_LinkId.put(sf, ObjDef_LinkId.get(ObjDef));
        } else {
          EPCFunction f =
              net.addFunction(new EPCFunction(new LogEvent(ownName, "unknown:normal"), net));
          f.setIdentifier(ownName);
          mapping.put(id, f);
        }
      } else if (symbolnum.equals("ST_EV")) {
        EPCEvent e = net.addEvent(new EPCEvent(ownName, net));
        e.setIdentifier(ownName);
        mapping.put(id, e);
      } else if (symbolnum.equals("ST_OPR_AND_1")) {
        EPCConnector c = net.addConnector(new EPCConnector(EPCConnector.AND, net));
        mapping.put(id, c);
      } else if (symbolnum.equals("ST_OPR_OR_1")) {
        // EPCConnector c = net.addConnector(new
        // EPCConnector(EPCConnector.OR, net));
        EPCConnector c = net.addConnector(new EPCConnector(EPCConnector.AND, net));
        mapping.put(id, c);
      } else if (symbolnum.equals("ST_OPR_XOR_1")) {
        EPCConnector c = net.addConnector(new EPCConnector(EPCConnector.XOR, net));
        mapping.put(id, c);
      }
    }

    for (int i = 0; i < nodes.getLength(); i++) {
      Node n = nodes.item(i);
      if (!n.getNodeName().equals("ObjOcc")) {
        continue;
      }
      if (n.getAttributes().getNamedItem("SymbolNum") == null) {
        continue;
      }
      String symbolnum = n.getAttributes().getNamedItem("SymbolNum").getNodeValue();
      if (!(symbolnum.equals("ST_FUNC")
          || symbolnum.equals("ST_EV")
          || symbolnum.equals("ST_OPR_AND_1")
          || symbolnum.equals("ST_OPR_OR_1")
          || symbolnum.equals("ST_OPR_XOR_1"))) {
        continue;
      }
      String source = n.getAttributes().getNamedItem("ObjOcc.ID").getNodeValue();
      if (n.hasChildNodes()) {
        for (int j = 0; j < n.getChildNodes().getLength(); j++) {
          if (n.getChildNodes().item(j).getNodeName().equals("CxnOcc")) {
            Node CxnOcc = n.getChildNodes().item(j);
            String dest = CxnOcc.getAttributes().getNamedItem("ToObjOcc.IdRef").getNodeValue();
            if (mapping.get(dest) == null) {
              continue;
            }
            if (net.addEdge((EPCObject) mapping.get(source), (EPCObject) mapping.get(dest))
                == null) {
              throw (new Exception(
                  "<html>Structural properties of EPCs are violated in input file.<br>"
                      + "The following edge could not be added:<br><br>"
                      + mapping.get(source).toString()
                      + " ==> "
                      + mapping.get(dest).toString()
                      + "<br><br>Import aborted.</html>"));
            }
          }
        }
      }
    }
  }
Example #25
0
 public static EPCResult traverseAML(
     EPCResult partialResult,
     Node currentNode,
     Object parent,
     HashMap ObjDef_Name,
     HashMap ObjDef_LinkId,
     HashMap modelid_net,
     HashMap function_LinkId)
     throws Exception {
   if (currentNode.hasChildNodes()) {
     for (int i = 0; i < currentNode.getChildNodes().getLength(); i++) {
       Node currentChild = currentNode.getChildNodes().item(i);
       if (currentChild.getNodeName().equals("Group")) {
         String id = currentChild.getAttributes().getNamedItem("Group.ID").getNodeValue();
         String GroupName = "";
         if (currentChild.hasChildNodes()) {
           NodeList currentChildren = currentChild.getChildNodes();
           for (int j = 0; j < currentChildren.getLength(); j++) {
             Node Child = currentChildren.item(j);
             if (!(Child.getNodeName().equals("AttrDef"))) {
               continue;
             }
             if (Child.getAttributes()
                 .getNamedItem("AttrDef.Type")
                 .getNodeValue()
                 .equals("AT_NAME")) {
               if (Child.hasChildNodes()) {
                 for (int l = 0; l < Child.getChildNodes().getLength(); l++) {
                   if (!(Child.getChildNodes().item(l).getNodeName().equals("AttrValue"))) {
                     continue;
                   } else {
                     GroupName = getTextContent(Child.getChildNodes().item(l));
                   }
                 }
                 break;
               }
             }
           }
           if (GroupName.equals("")) {
             GroupName = id;
           }
         }
         ModelHierarchyDirectory dir = new ModelHierarchyDirectory(id, GroupName);
         partialResult.addInHierarchy(dir, parent, GroupName);
         partialResult =
             traverseAML(
                 partialResult,
                 currentChild,
                 dir,
                 ObjDef_Name,
                 ObjDef_LinkId,
                 modelid_net,
                 function_LinkId);
       }
       if (currentChild.getNodeName().equals("Model")
           && currentChild
               .getAttributes()
               .getNamedItem("Model.Type")
               .getNodeValue()
               .equals("MT_EEPC")) {
         String ModelName = "gaga";
         if (currentChild.hasChildNodes()) {
           NodeList currentChildren = currentChild.getChildNodes();
           for (int j = 0; j < currentChildren.getLength(); j++) {
             Node Child = currentChildren.item(j);
             if (!(Child.getNodeName().equals("AttrDef"))) {
               continue;
             }
             if (Child.getAttributes()
                 .getNamedItem("AttrDef.Type")
                 .getNodeValue()
                 .equals("AT_NAME")) {
               if (Child.hasChildNodes()) {
                 for (int l = 0; l < Child.getChildNodes().getLength(); l++) {
                   if (!(Child.getChildNodes().item(l).getNodeName().equals("AttrValue"))) {
                     continue;
                   } else {
                     ModelName = getTextContent(Child.getChildNodes().item(l));
                   }
                 }
               }
               break;
             }
           }
         }
         try {
           ModelName = ModelName.replaceAll("\n", " ");
           EPC net = read(currentChild, ObjDef_Name, ObjDef_LinkId, function_LinkId, ModelName);
           partialResult.addInHierarchy(net, parent, ModelName);
           modelid_net.put(
               currentChild.getAttributes().getNamedItem("Model.ID").getNodeValue(), net);
         } catch (Throwable x) {
           Message.add(x.getClass().getName());
           // throw new IOException(x.getMessage());
         }
       }
     }
   }
   return partialResult;
 }
Example #26
0
 private static final int getAttrInt(Node node, String name) {
   return Integer.parseInt(node.getAttributes().getNamedItem(name).getNodeValue());
 }