Example #1
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());
        }
      }
  /**
   * Handle text node during validation.
   *
   * @param received
   * @param source
   */
  private void doText(Node received, Node source) {
    if (log.isDebugEnabled()) {
      log.debug("Validating node value for element: " + received.getParentNode());
    }

    if (received.getNodeValue() != null) {
      Assert.isTrue(
          source.getNodeValue() != null,
          ValidationUtils.buildValueMismatchErrorMessage(
              "Node value not equal for element '" + received.getParentNode().getLocalName() + "'",
              null,
              received.getNodeValue().trim()));

      Assert.isTrue(
          received.getNodeValue().trim().equals(source.getNodeValue().trim()),
          ValidationUtils.buildValueMismatchErrorMessage(
              "Node value not equal for element '" + received.getParentNode().getLocalName() + "'",
              source.getNodeValue().trim(),
              received.getNodeValue().trim()));
    } else {
      Assert.isTrue(
          source.getNodeValue() == null,
          ValidationUtils.buildValueMismatchErrorMessage(
              "Node value not equal for element '" + received.getParentNode().getLocalName() + "'",
              source.getNodeValue().trim(),
              null));
    }

    if (log.isDebugEnabled()) {
      log.debug("Node value '" + received.getNodeValue().trim() + "': OK");
    }
  }
Example #3
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;
 }
  /**
   * Perform validation on namespace qualified attribute values if present. This includes the
   * validation of namespace presence and equality.
   *
   * @param receivedElement
   * @param receivedAttribute
   * @param sourceElement
   * @param sourceAttribute
   */
  private void doNamespaceQualifiedAttributeValidation(
      Node receivedElement, Node receivedAttribute, Node sourceElement, Node sourceAttribute) {
    String receivedValue = receivedAttribute.getNodeValue();
    String sourceValue = sourceAttribute.getNodeValue();

    if (receivedValue.contains(":") && sourceValue.contains(":")) {
      // value has namespace prefix set, do special QName validation
      String receivedPrefix = receivedValue.substring(0, receivedValue.indexOf(':'));
      String sourcePrefix = sourceValue.substring(0, sourceValue.indexOf(':'));

      Map<String, String> receivedNamespaces =
          XMLUtils.lookupNamespaces(receivedAttribute.getOwnerDocument());
      receivedNamespaces.putAll(XMLUtils.lookupNamespaces(receivedElement));

      if (receivedNamespaces.containsKey(receivedPrefix)) {
        Map<String, String> sourceNamespaces =
            XMLUtils.lookupNamespaces(sourceAttribute.getOwnerDocument());
        sourceNamespaces.putAll(XMLUtils.lookupNamespaces(sourceElement));

        if (sourceNamespaces.containsKey(sourcePrefix)) {
          Assert.isTrue(
              sourceNamespaces.get(sourcePrefix).equals(receivedNamespaces.get(receivedPrefix)),
              ValidationUtils.buildValueMismatchErrorMessage(
                  "Values not equal for attribute value namespace '" + receivedValue + "'",
                  sourceNamespaces.get(sourcePrefix),
                  receivedNamespaces.get(receivedPrefix)));

          // remove namespace prefixes as they must not form equality
          receivedValue = receivedValue.substring((receivedPrefix + ":").length());
          sourceValue = sourceValue.substring((sourcePrefix + ":").length());
        } else {
          throw new ValidationException(
              "Received attribute value '"
                  + receivedAttribute.getLocalName()
                  + "' describes namespace qualified attribute value,"
                  + " control value '"
                  + sourceValue
                  + "' does not");
        }
      }
    }

    Assert.isTrue(
        receivedValue.equals(sourceValue),
        ValidationUtils.buildValueMismatchErrorMessage(
            "Values not equal for attribute '" + receivedAttribute.getLocalName() + "'",
            sourceValue,
            receivedValue));
  }
Example #5
0
  private Node[] processIndexNode(
      final Node theNode,
      final Document theTargetDocument,
      final IndexEntryFoundListener theIndexEntryFoundListener) {
    theNode.normalize();

    boolean ditastyle = false;
    String textNode = null;

    final NodeList childNodes = theNode.getChildNodes();
    final StringBuilder textBuf = new StringBuilder();
    final List<Node> contents = new ArrayList<Node>();
    for (int i = 0; i < childNodes.getLength(); i++) {
      final Node child = childNodes.item(i);
      if (checkElementName(child)) {
        ditastyle = true;
        break;
      } else if (child.getNodeType() == Node.ELEMENT_NODE) {
        textBuf.append(XMLUtils.getStringValue((Element) child));
        contents.add(child);
      } else if (child.getNodeType() == Node.TEXT_NODE) {
        textBuf.append(child.getNodeValue());
        contents.add(child);
      }
    }
    textNode = IndexStringProcessor.normalizeTextValue(textBuf.toString());
    if (textNode.length() == 0) {
      textNode = null;
    }

    if (theNode.getAttributes().getNamedItem(elIndexRangeStartName) != null
        || theNode.getAttributes().getNamedItem(elIndexRangeEndName) != null) {
      ditastyle = true;
    }

    final ArrayList<Node> res = new ArrayList<Node>();
    if ((ditastyle)) {
      final IndexEntry[] indexEntries = indexDitaProcessor.processIndexDitaNode(theNode, "");

      for (final IndexEntry indexEntrie : indexEntries) {
        theIndexEntryFoundListener.foundEntry(indexEntrie);
      }

      final Node[] nodes = transformToNodes(indexEntries, theTargetDocument, null);
      for (final Node node : nodes) {
        res.add(node);
      }

    } else if (textNode != null) {
      final Node[] nodes =
          processIndexString(textNode, contents, theTargetDocument, theIndexEntryFoundListener);
      for (final Node node : nodes) {
        res.add(node);
      }
    } else {
      return new Node[0];
    }

    return (Node[]) res.toArray(new Node[res.size()]);
  }
  /**
   * Checks whether the given node contains a validation matcher
   *
   * @param node
   * @return true if node value contains validation matcher, false if not
   */
  private boolean isValidationMatcherExpression(Node node) {
    switch (node.getNodeType()) {
      case Node.ELEMENT_NODE:
        return node.getFirstChild() != null
            && StringUtils.hasText(node.getFirstChild().getNodeValue())
            && ValidationMatcherUtils.isValidationMatcherExpression(
                node.getFirstChild().getNodeValue().trim());

      case Node.ATTRIBUTE_NODE:
        return StringUtils.hasText(node.getNodeValue())
            && ValidationMatcherUtils.isValidationMatcherExpression(node.getNodeValue().trim());

      default:
        return false; // validation matchers makes no sense
    }
  }
 private void extractAttribute(
     Set<String> pReadAttributes, Set<String> pWriteAttributes, Node pParam) {
   Node mode = pParam.getAttributes().getNamedItem("mode");
   pReadAttributes.add(pParam.getTextContent().trim());
   if (mode == null || !mode.getNodeValue().equalsIgnoreCase("read")) {
     pWriteAttributes.add(pParam.getTextContent().trim());
   }
 }
 /**
  * Handle processing instruction during validation.
  *
  * @param received
  */
 private void doPI(Node received) {
   log.info(
       "Ignored processing instruction ("
           + received.getLocalName()
           + "="
           + received.getNodeValue()
           + ")");
 }
 /* return the value of the XML text node (never null) */
 protected static String GetNodeText(Node root) {
   StringBuffer sb = new StringBuffer();
   if (root != null) {
     NodeList list = root.getChildNodes();
     for (int i = 0; i < list.getLength(); i++) {
       Node n = list.item(i);
       if (n.getNodeType() == Node.CDATA_SECTION_NODE) { // CDATA Section
         sb.append(n.getNodeValue());
       } else if (n.getNodeType() == Node.TEXT_NODE) {
         sb.append(n.getNodeValue());
       } else {
         // Print.logWarn("Unrecognized node type: " + n.getNodeType());
       }
     }
   }
   return sb.toString();
 }
Example #10
0
 public static String text(Node node) {
   if (node.getNodeType() == Node.TEXT_NODE) {
     return node.getNodeValue();
   }
   if (node.hasChildNodes()) {
     return text(node.getChildNodes());
   }
   return "";
 }
Example #11
0
    /** Возвращает имя метода. */
    public String getName() {

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

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

      /** Возвращаем значение атрибута. */
      return nameAttrib.getNodeValue();
    }
Example #12
0
 /** @deprecated use allText(Element elem, boolean trim) */
 public static String allTextFromElement(Element elem, boolean trim) throws DOMException {
   StringBuffer textBuf = new StringBuffer();
   NodeList nl = elem.getChildNodes();
   for (int j = 0, len = nl.getLength(); j < len; ++j) {
     Node node = nl.item(j);
     if (node instanceof Text) // includes Text and CDATA!
     textBuf.append(node.getNodeValue());
   }
   String out = textBuf.toString();
   return (trim ? out.trim() : out);
 }
 private static String getValue(Node node) {
   String textValue = "";
   Node child = null;
   if (node != null)
     for (child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
       if (child.getNodeType() == Node.TEXT_NODE) {
         textValue = child.getNodeValue();
         break;
       }
     }
   return textValue.trim();
 }
 protected Element copyElementToName(Element element, String tagName) {
   Element newElement = element.getOwnerDocument().createElement(tagName);
   NamedNodeMap attrs = element.getAttributes();
   for (int i = 0; i < attrs.getLength(); i++) {
     Node attribute = attrs.item(i);
     newElement.setAttribute(attribute.getNodeName(), attribute.getNodeValue());
   }
   for (int i = 0; i < element.getChildNodes().getLength(); i++) {
     newElement.appendChild(element.getChildNodes().item(i).cloneNode(true));
   }
   return newElement;
 }
Example #15
0
  private static String getTextContent(Node n) {
    NodeList nodeList = n.getChildNodes();
    String textContent = "";
    for (int j = 0; j < nodeList.getLength(); j++) {
      Node k = nodeList.item(j);
      if (k.getNodeType() == Node.TEXT_NODE) {
        textContent = k.getNodeValue();
        break;
      }
    }

    return textContent;
  }
Example #16
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());
        }
      }
Example #17
0
 private static NodeList getChildElements(Element self, String elementName) {
   List result = new ArrayList();
   NodeList nodeList = self.getChildNodes();
   for (int i = 0; i < nodeList.getLength(); i++) {
     Node node = nodeList.item(i);
     if (node.getNodeType() == Node.ELEMENT_NODE) {
       Element child = (Element) node;
       if ("*".equals(elementName) || child.getTagName().equals(elementName)) {
         result.add(child);
       }
     } else if (node.getNodeType() == Node.TEXT_NODE) {
       String value = node.getNodeValue();
       if (trimWhitespace) {
         value = value.trim();
       }
       if ("*".equals(elementName) && value.length() > 0) {
         node.setNodeValue(value);
         result.add(node);
       }
     }
   }
   return new NodesHolder(result);
 }
Example #18
0
  private void processPanelLayout(Session session, Element element, HashMap additionalInformation) {

    String nodeName = element.getNodeName();
    String panelName = nodeName;

    NamedNodeMap tNodeMap = element.getAttributes();
    for (int i = 0; i < tNodeMap.getLength(); i++) {
      Node node = tNodeMap.item(i);
      String name = node.getNodeName();
      if (name.equals("dividerFractions")) {
        String value = node.getNodeValue();
        String[] tokens = value.split(",");
        double[] divs = new double[tokens.length];
        try {
          for (int j = 0; j < tokens.length; j++) {
            divs[j] = Double.parseDouble(tokens[j]);
          }
          session.setDividerFractions(divs);
        } catch (NumberFormatException e) {
          log.error("Error parsing divider locations", e);
        }
      }
    }
  }
Example #19
0
  public static String getFirstTextNodeVal(Node node) {
    node = getFirstTextNode(node);
    if (node != null) return node.getNodeValue();

    return null;
  }
  /**
   * Handle attribute node during validation.
   *
   * @param receivedElement
   * @param receivedAttribute
   * @param sourceElement
   * @param validationContext
   */
  private void doAttribute(
      Node receivedElement,
      Node receivedAttribute,
      Node sourceElement,
      XmlMessageValidationContext validationContext,
      NamespaceContext namespaceContext,
      TestContext context) {
    if (receivedAttribute.getNodeName().startsWith(XMLConstants.XMLNS_ATTRIBUTE)) {
      return;
    }

    String receivedAttributeName = receivedAttribute.getLocalName();

    if (log.isDebugEnabled()) {
      log.debug(
          "Validating attribute: "
              + receivedAttributeName
              + " ("
              + receivedAttribute.getNamespaceURI()
              + ")");
    }

    NamedNodeMap sourceAttributes = sourceElement.getAttributes();
    Node sourceAttribute =
        sourceAttributes.getNamedItemNS(receivedAttribute.getNamespaceURI(), receivedAttributeName);

    Assert.isTrue(
        sourceAttribute != null,
        "Attribute validation failed for element '"
            + receivedElement.getLocalName()
            + "', unknown attribute "
            + receivedAttributeName
            + " ("
            + receivedAttribute.getNamespaceURI()
            + ")");

    if (XmlValidationUtils.isAttributeIgnored(
        receivedElement,
        receivedAttribute,
        sourceAttribute,
        validationContext.getIgnoreExpressions(),
        namespaceContext)) {
      return;
    }

    String receivedValue = receivedAttribute.getNodeValue();
    String sourceValue = sourceAttribute.getNodeValue();
    if (isValidationMatcherExpression(sourceAttribute)) {
      ValidationMatcherUtils.resolveValidationMatcher(
          sourceAttribute.getNodeName(),
          receivedAttribute.getNodeValue().trim(),
          sourceAttribute.getNodeValue().trim(),
          context);
    } else if (receivedValue.contains(":") && sourceValue.contains(":")) {
      doNamespaceQualifiedAttributeValidation(
          receivedElement, receivedAttribute, sourceElement, sourceAttribute);
    } else {
      Assert.isTrue(
          receivedValue.equals(sourceValue),
          ValidationUtils.buildValueMismatchErrorMessage(
              "Values not equal for attribute '" + receivedAttributeName + "'",
              sourceValue,
              receivedValue));
    }

    if (log.isDebugEnabled()) {
      log.debug("Attribute '" + receivedAttributeName + "'='" + receivedValue + "': OK");
    }
  }
 /**
  * @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();
     }
   }
 }
Example #22
0
 private Object deserialize(Node node, boolean setProperty, boolean popBean) throws Exception {
   Object object = null;
   currentType = null;
   currentNode = node;
   currentName = node.getNodeName();
   boolean isNull = false;
   NamedNodeMap attrs = node.getAttributes();
   String arrayType = null;
   for (int i = 0; i < attrs.getLength(); i++) {
     String nodeName = attrs.item(i).getNodeName();
     String nodeValue = attrs.item(i).getNodeValue();
     if (nodeName.equals(NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + Constants.ATTR_TYPE))
       currentType = new StringBuffer(nodeValue).delete(0, nodeValue.indexOf(':') + 1).toString();
     else if (nodeName.equals(
         NamespaceConstants.NSPREFIX_SOAP_ENCODING + ":" + Constants.ATTR_ARRAY_TYPE))
       arrayType = new StringBuffer(nodeValue).delete(0, nodeValue.indexOf(':') + 1).toString();
     else if (nodeName.equals(NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null"))
       isNull = nodeValue.equals("true");
   }
   Class cls = null;
   if (currentType != null) cls = getXsdTypeClass(currentType);
   // Handle array, Vector, ArrayList, LinkedList, Hashtable,
   // Properties, and HashMap data types
   if ((cls != null)
       && ((cls == java.lang.reflect.Array.class)
           || (cls == Vector.class)
           || (cls == ArrayList.class)
           || (cls == LinkedList.class)
           || (cls == Hashtable.class)
           || (cls == Properties.class)
           || (cls == HashMap.class)
           || (cls == SortedMap.class))) {
     parentNode = currentNode;
     String name = node.getNodeName();
     // Handle arrays
     if (cls == java.lang.reflect.Array.class) {
       int a = arrayType.indexOf("[");
       int b = arrayType.indexOf("]");
       String s = arrayType.substring(a + 1, b);
       int arrayLen = Integer.valueOf(s).intValue();
       arrayType = arrayType.substring(0, a);
       // check if the array element is a standard Java class
       Class arrayClass = getXsdTypeClass(arrayType);
       // otherwise try to get the class of the bean
       if (arrayClass == null)
         arrayClass = getClassOfBean((ClassLoader) classLoaderStrategy, arrayType);
       object = java.lang.reflect.Array.newInstance(arrayClass, arrayLen);
     } else {
       // Construct the list or map type
       Constructor ct = cls.getConstructor((Class[]) null);
       object = ct.newInstance((Object[]) null);
     }
     // deserialize the elements of the array, list, or map
     NodeList childNodes = node.getChildNodes();
     int arrayIndex = -1;
     Node childNode = null;
     Object nodeObj = null;
     for (int i = 0; i < childNodes.getLength(); i++) {
       childNode = childNodes.item(i);
       if (childNode.getNodeType() == Node.ELEMENT_NODE) {
         if ((cls == java.lang.reflect.Array.class)
             || (cls == Vector.class)
             || (cls == ArrayList.class)
             || (cls == LinkedList.class)) {
           nodeObj = deserialize(childNode, false, true);
           if (nodeObj != null) {
             if (cls == java.lang.reflect.Array.class)
               java.lang.reflect.Array.set(object, ++arrayIndex, nodeObj);
             else ((List) object).add(nodeObj);
           }
         } else if ((cls == Hashtable.class)
             || (cls == Properties.class)
             || (cls == HashMap.class)
             || (cls == SortedMap.class)) {
           if (childNode.getLocalName().equals("item")) {
             NodeList htNodes = childNode.getChildNodes();
             if (htNodes.getLength() == 2) {
               Object hashKey = deserialize(htNodes.item(0), false, false);
               Object hashValue = deserialize(htNodes.item(1), false, true);
               ((Map) object).put(hashKey, hashValue);
             }
           }
         }
       }
     }
     setBeanProperty(name, object);
     // Handle everything else (primitives & POJOs)
   } else {
     // recurse on each of the child nodes
     NodeList childNodes = node.getChildNodes();
     if ((childNodes != null) && (childNodes.getLength() > 0)) {
       for (int i = 0; i < childNodes.getLength(); i++) {
         Node childNode = childNodes.item(i);
         if (childNode.getNodeType() == Node.ELEMENT_NODE) {
           if (currentType != null)
             createObject(
                 node,
                 currentName,
                 currentPackage,
                 currentType,
                 childNode.getNodeValue(),
                 setProperty);
           parentNode = node;
           object = deserialize(childNode, true, true);
         } else if ((childNode.getNodeType() == Node.TEXT_NODE) && (currentType != null)) {
           object =
               createObject(
                   node,
                   currentName,
                   currentPackage,
                   currentType,
                   childNode.getNodeValue(),
                   setProperty);
         }
         currentType = null;
       }
     } else {
       if (!isNull)
         object = createObject(node, currentName, currentPackage, currentType, null, setProperty);
     }
     if (node.getParentNode() != parentNode) {
       parentNode = node.getParentNode();
       if (popBean) {
         Object bean = popBeanOffStack();
         if (bean != null) object = bean;
       }
     }
   }
   return object;
 }
Example #23
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 #24
0
  /**
   * Process a track element. This should return a single track, but could return multiple tracks
   * since the uniqueness of the track id is not enforced.
   *
   * @param session
   * @param element
   * @param additionalInformation
   * @return
   */
  private List<Track> processTrack(
      Session session, Element element, HashMap additionalInformation) {

    String id = getAttribute(element, SessionAttribute.ID.getText());

    // TODo -- put in utility method, extacts attributes from element **Definitely need to do this
    HashMap<String, String> tAttributes = new HashMap();
    HashMap<String, String> drAttributes = null;

    NamedNodeMap tNodeMap = element.getAttributes();
    for (int i = 0; i < tNodeMap.getLength(); i++) {
      Node node = tNodeMap.item(i);
      String value = node.getNodeValue();
      if (value != null && value.length() > 0) {
        tAttributes.put(node.getNodeName(), value);
      }
    }

    if (element.hasChildNodes()) {
      drAttributes = new HashMap();
      Node childNode = element.getFirstChild();
      Node sibNode = childNode.getNextSibling();
      String sibName = sibNode.getNodeName();
      if (sibName.equals(SessionElement.DATA_RANGE.getText())) {
        NamedNodeMap drNodeMap = sibNode.getAttributes();
        for (int i = 0; i < drNodeMap.getLength(); i++) {
          Node node = drNodeMap.item(i);
          String value = node.getNodeValue();
          if (value != null && value.length() > 0) {
            drAttributes.put(node.getNodeName(), value);
          }
        }
      }
    }

    // Get matching tracks.
    List<Track> matchedTracks = trackDictionary.get(id);

    if (matchedTracks == null) {
      log.info("Warning.  No tracks were found with id: " + id + " in session file");
    } else {
      for (final Track track : matchedTracks) {

        // Special case for sequence & gene tracks,  they need to be removed before being placed.
        if (version >= 4 && track == geneTrack || track == seqTrack) {
          igv.removeTracks(Arrays.asList(track));
        }

        track.restorePersistentState(tAttributes);
        if (drAttributes != null) {
          DataRange dr = track.getDataRange();
          dr.restorePersistentState(drAttributes);
          track.setDataRange(dr);
        }
      }
      trackDictionary.remove(id);
    }

    NodeList elements = element.getChildNodes();
    process(session, elements, additionalInformation);

    return matchedTracks;
  }
Example #25
0
  // -----------------------------------------------------
  // Description: Get the value from the node.
  // YUUGAMEE!
  // -----------------------------------------------------
  String getTagValue(String sTag, Element eElement) {
    NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
    Node nValue = (Node) nlList.item(0);

    return nValue.getNodeValue();
  }
  /** updates the XMl with hashcode for the files */
  protected BudgetSubAwards updateXML(
      byte xmlContents[], Map fileMap, BudgetSubAwards budgetSubAwardBean, Budget budget)
      throws Exception {

    javax.xml.parsers.DocumentBuilderFactory domParserFactory =
        javax.xml.parsers.DocumentBuilderFactory.newInstance();
    javax.xml.parsers.DocumentBuilder domParser = domParserFactory.newDocumentBuilder();
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(xmlContents);

    org.w3c.dom.Document document = domParser.parse(byteArrayInputStream);
    byteArrayInputStream.close();
    String namespace = null;
    String formName = null;
    if (document != null) {
      Node node;
      Element element = document.getDocumentElement();
      NamedNodeMap map = element.getAttributes();
      String namespaceHolder =
          element.getNodeName().substring(0, element.getNodeName().indexOf(':'));
      node = map.getNamedItem("xmlns:" + namespaceHolder);
      namespace = node.getNodeValue();
      FormMappingInfo formMappingInfo = new FormMappingLoader().getFormInfo(namespace);
      formName = formMappingInfo.getFormName();
      budgetSubAwardBean.setNamespace(namespace);
      budgetSubAwardBean.setFormName(formName);
    }

    String xpathEmptyNodes =
        "//*[not(node()) and local-name(.) != 'FileLocation' and local-name(.) != 'HashValue']";
    String xpathOtherPers =
        "//*[local-name(.)='ProjectRole' and local-name(../../.)='OtherPersonnel' and count(../NumberOfPersonnel)=0]";
    removeAllEmptyNodes(document, xpathEmptyNodes, 0);
    removeAllEmptyNodes(document, xpathOtherPers, 1);
    removeAllEmptyNodes(document, xpathEmptyNodes, 0);
    changeDataTypeForNumberOfOtherPersons(document);

    List<String> fedNonFedSubAwardForms = getFedNonFedSubawardForms();
    NodeList budgetYearList =
        XPathAPI.selectNodeList(document, "//*[local-name(.) = 'BudgetYear']");
    for (int i = 0; i < budgetYearList.getLength(); i++) {
      Node bgtYearNode = budgetYearList.item(i);
      String period = getValue(XPathAPI.selectSingleNode(bgtYearNode, "BudgetPeriod"));
      if (fedNonFedSubAwardForms.contains(namespace)) {
        Element newBudgetYearElement =
            copyElementToName((Element) bgtYearNode, bgtYearNode.getNodeName());
        bgtYearNode.getParentNode().replaceChild(newBudgetYearElement, bgtYearNode);
      } else {
        Element newBudgetYearElement =
            copyElementToName((Element) bgtYearNode, bgtYearNode.getNodeName() + period);
        bgtYearNode.getParentNode().replaceChild(newBudgetYearElement, bgtYearNode);
      }
    }

    Node oldroot = document.removeChild(document.getDocumentElement());
    Node newroot = document.appendChild(document.createElement("Forms"));
    newroot.appendChild(oldroot);

    org.w3c.dom.NodeList lstFileName = document.getElementsByTagName("att:FileName");
    org.w3c.dom.NodeList lstFileLocation = document.getElementsByTagName("att:FileLocation");
    org.w3c.dom.NodeList lstMimeType = document.getElementsByTagName("att:MimeType");
    org.w3c.dom.NodeList lstHashValue = document.getElementsByTagName("glob:HashValue");

    if ((lstFileName.getLength() != lstFileLocation.getLength())
        || (lstFileLocation.getLength() != lstHashValue.getLength())) {
      //            throw new RuntimeException("Tag occurances mismatch in XML File");
    }

    org.w3c.dom.Node fileNode, hashNode, mimeTypeNode;
    org.w3c.dom.NamedNodeMap fileNodeMap, hashNodeMap;
    String fileName;
    byte fileBytes[];
    String contentId;
    List attachmentList = new ArrayList();

    for (int index = 0; index < lstFileName.getLength(); index++) {
      fileNode = lstFileName.item(index);

      Node fileNameNode = fileNode.getFirstChild();
      fileName = fileNameNode.getNodeValue();

      fileBytes = (byte[]) fileMap.get(fileName);

      if (fileBytes == null) {
        throw new RuntimeException("FileName mismatch in XML and PDF extracted file");
      }
      String hashVal = GrantApplicationHash.computeAttachmentHash(fileBytes);

      hashNode = lstHashValue.item(index);
      hashNodeMap = hashNode.getAttributes();

      Node temp = document.createTextNode(hashVal);
      hashNode.appendChild(temp);

      hashNode = hashNodeMap.getNamedItem("glob:hashAlgorithm");

      hashNode.setNodeValue(S2SConstants.HASH_ALGORITHM);

      fileNode = lstFileLocation.item(index);
      fileNodeMap = fileNode.getAttributes();
      fileNode = fileNodeMap.getNamedItem("att:href");

      contentId = fileNode.getNodeValue();
      String encodedContentId = cleanContentId(contentId);
      fileNode.setNodeValue(encodedContentId);

      mimeTypeNode = lstMimeType.item(0);
      String contentType = mimeTypeNode.getFirstChild().getNodeValue();

      BudgetSubAwardAttachment budgetSubAwardAttachmentBean = new BudgetSubAwardAttachment();
      budgetSubAwardAttachmentBean.setAttachment(fileBytes);
      budgetSubAwardAttachmentBean.setContentId(encodedContentId);

      budgetSubAwardAttachmentBean.setContentType(contentType);
      budgetSubAwardAttachmentBean.setBudgetId(budgetSubAwardBean.getBudgetId());
      budgetSubAwardAttachmentBean.setSubAwardNumber(budgetSubAwardBean.getSubAwardNumber());

      attachmentList.add(budgetSubAwardAttachmentBean);
    }

    budgetSubAwardBean.setBudgetSubAwardAttachments(attachmentList);

    javax.xml.transform.Transformer transformer =
        javax.xml.transform.TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes");

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    javax.xml.transform.stream.StreamResult result =
        new javax.xml.transform.stream.StreamResult(bos);
    javax.xml.transform.dom.DOMSource source = new javax.xml.transform.dom.DOMSource(document);

    transformer.transform(source, result);

    budgetSubAwardBean.setSubAwardXmlFileData(new String(bos.toByteArray()));

    bos.close();

    return budgetSubAwardBean;
  }
 /**
  * Handle comment node during validation.
  *
  * @param received
  */
 private void doComment(Node received) {
   log.info("Ignored comment node (" + received.getNodeValue() + ")");
 }
Example #28
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;
  }