Example #1
0
  private void encodeElements(String encoding, Element element, boolean applyBase64) {
    if (element.hasChildNodes()) {

      NodeList childNodes = element.getChildNodes();

      for (int i = 0; i < childNodes.getLength(); i++) {
        Node node = childNodes.item(i);
        if (node.getNodeType() == node.ELEMENT_NODE) {
          this.encodeElements(encoding, (Element) node, applyBase64);
        } else if (node.getNodeType() == node.TEXT_NODE) {
          if (applyBase64) {
            try {
              byte[] bytes = base64.decode(node.getNodeValue());
              String decodedString = new String(bytes, encoding);
              node.setNodeValue(decodedString);
            } catch (Exception exp) {
            }
          } else {
            try {
              byte[] bytes = node.getNodeValue().getBytes(encoding);
              String decodedString = new String(bytes);
              node.setNodeValue(decodedString);
            } catch (Exception epx) {
            }
          }
        }
      }
    }
  }
  protected void transferAttributes(
      Element source, Element result, java.util.List nonTransferList) {
    boolean debug = false;
    NamedNodeMap sourceAttrNodeMap = source.getAttributes();
    if (sourceAttrNodeMap == null) return;

    NamedNodeMap resultAttrNodeMap = result.getAttributes();

    for (int index = 0; index < sourceAttrNodeMap.getLength(); index++) {
      Node sourceAttrNode = sourceAttrNodeMap.item(index);
      if (!this.canTransferAttribute(sourceAttrNode.getNodeName(), nonTransferList)) continue;
      if (!isValidAttributeToTransfer(
          sourceAttrNode.getNodeName(), getAttributeListForElement(result.getTagName()))) continue;
      if (resultAttrNodeMap == null) {
        Attr addAttr = result.getOwnerDocument().createAttribute(sourceAttrNode.getNodeName());
        addAttr.setValue(sourceAttrNode.getNodeValue());
        result.setAttributeNode(addAttr);
      } else {
        Node resultAttrNode = resultAttrNodeMap.getNamedItem(sourceAttrNode.getNodeName());
        if (resultAttrNode != null) {
          resultAttrNode.setNodeValue(sourceAttrNode.getNodeValue());
          // result.setAttributeNode((Attr)resultAttrNode);
        } else {
          Attr addAttr = result.getOwnerDocument().createAttribute(sourceAttrNode.getNodeName());
          addAttr.setValue(sourceAttrNode.getNodeValue());
          result.setAttributeNode(addAttr);
        }
      }
    }
  }
  public static void main(String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setIgnoringElementContentWhitespace(true);
    DocumentBuilder parser = factory.newDocumentBuilder();

    // Load an existing document
    Document doc = parser.parse(args[0]);
    // doc.normalize();

    Element book = findElement(doc.getDocumentElement());
    if (book == null) {
      System.out.println("Book with the right title not found !");
      System.exit(1);
    }

    Node title = book.getFirstChild().getFirstChild();
    title.setNodeValue("Java and XML");

    // Serialize document tree

    TransformerFactory transFactory = TransformerFactory.newInstance();
    // transFactory.setAttribute("indent-number", 2);
    Transformer idTransform = transFactory.newTransformer();
    idTransform.setOutputProperty(OutputKeys.METHOD, "xml");
    idTransform.setOutputProperty(OutputKeys.INDENT, "yes");
    Source input = new DOMSource(doc);
    Result output = new StreamResult(System.out);
    idTransform.transform(input, output);
  }
Example #4
0
 public void setAttribute(final String attribute, final String value) {
   Node attr = this.node.getAttributes().getNamedItem(attribute);
   if (attr == null) {
     attr = getDocument().createAttribute(attribute);
   }
   attr.setNodeValue(value);
   this.node.getAttributes().setNamedItem(attr);
 }
  private boolean isDigested(NodeList nodes, VerifyReference[] references) {
    for (int idx = 0; idx < nodes.getLength(); idx++) {
      Node node = nodes.item(idx);
      this._logger.log(Level.FINE, "node name: {0}", node.getLocalName());
      boolean changed = false;
      if (node.getNodeType() == Node.TEXT_NODE) {
        String originalTextValue = node.getNodeValue();
        String changedTextValue = originalTextValue + "foobar";
        node.setNodeValue(changedTextValue);
        changed = false; // need to have impact anyway
        for (int referenceIdx = 0; referenceIdx < references.length; referenceIdx++) {
          VerifyReference reference = references[referenceIdx];
          changed |= reference.hasChanged();
        }
        if (false == changed) {
          return false;
        }
        node.setNodeValue(originalTextValue);
      } else if (node.getNodeType() == Node.ELEMENT_NODE) {
        Element element = (Element) node;

        NamedNodeMap attributes = element.getAttributes();
        for (int attributeIdx = 0; attributeIdx < attributes.getLength(); attributeIdx++) {
          Node attributeNode = attributes.item(attributeIdx);
          String originalAttributeValue = attributeNode.getNodeValue();
          String changedAttributeValue = originalAttributeValue + "foobar";
          attributeNode.setNodeValue(changedAttributeValue);
          for (int referenceIdx = 0; referenceIdx < references.length; referenceIdx++) {
            VerifyReference reference = references[referenceIdx];
            changed |= reference.hasChanged();
          }

          attributeNode.setNodeValue(originalAttributeValue);
        }
        changed |= isDigested(element.getChildNodes(), references);
      } else if (node.getNodeType() == Node.COMMENT_NODE) {
        // not always digested by the ds:References
      } else {
        throw new RuntimeException("unsupported node type: " + node.getNodeType());
      }
      if (false == changed) {
        return false;
      }
    }
    return true;
  }
Example #6
0
 /**
  * Set text for the active element of XML object.
  *
  * @param text The text value to be set
  */
 public void setText(String text) {
   Node firstChild = activeElement.getFirstChild();
   if (firstChild == null || firstChild.getNodeType() != Node.TEXT_NODE) {
     Node textNode = ownerDoc.createTextNode(text);
     activeElement.appendChild(textNode);
   } else {
     firstChild.setNodeValue(text);
   }
 }
 private void setValue(Node node, String value) {
   Node child = null;
   for (child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
     if (child.getNodeType() == Node.TEXT_NODE) {
       child.setNodeValue(value);
       break;
     }
   }
 }
Example #8
0
 /** Set or replace the text value */
 public static void setText(Node node, String val) {
   Node chld = DomUtil.getChild(node, Node.TEXT_NODE);
   if (chld == null) {
     Node textN = node.getOwnerDocument().createTextNode(val);
     node.appendChild(textN);
     return;
   }
   // change the value
   chld.setNodeValue(val);
 }
  /**
   * Sets the text of a node.
   *
   * @param doc The document the node comes from.
   * @param node The node whichs text should be changed.
   * @param text The text to set.
   */
  public static void setText(Document doc, Node node, String text) {
    Node textNode = getChild(node, "#text");

    if (textNode == null) {
      textNode = doc.createTextNode(text);
      node.appendChild(textNode);
    } else {
      textNode.setNodeValue(text);
    }
  }
 /** Enregistre un changement dans le DOM. */
 private void enregistrerChangement() {
   String valeur = getValeur();
   if ((valeur == null || "".equals(valeur)) && noeud == null) {
     // arrive si enregistrerChangement est appelé 2 fois lors d'un effacement
     // il n'y a rien à changer
     return;
   }
   if (valeur == null) valeur = "";
   doc.setModif(true);
   MyCompoundEdit cedit = null;
   if (noeud == null && !"".equals(valeur)) {
     cedit = new MyCompoundEdit();
     creerNoeud(cedit);
   } else if (noeud != null && "".equals(valeur) && affParent != null) {
     effacerNoeud(false, null);
     return;
   }
   if (!attribut) {
     final Element el = (Element) noeud;
     final Node firstChild = el.getFirstChild();
     if (firstChild == null) {
       final FormUndoableEdit fedit = new FormUndoableEdit(this, "", valeur);
       if (cedit != null) cedit.addEdit(fedit);
       else doc.textPane.addEdit(fedit);
       final Node textnode = el.getOwnerDocument().createTextNode(valeur);
       el.appendChild(textnode);
     } else if (firstChild.getNodeType() == Node.TEXT_NODE) {
       final FormUndoableEdit fedit =
           new FormUndoableEdit(this, firstChild.getNodeValue(), valeur);
       if (cedit != null) cedit.addEdit(fedit);
       else doc.textPane.addEdit(fedit);
       firstChild.setNodeValue(valeur);
     } else
       LOG.error(
           "AffichageFormulaire.enregistrerChangement : pas de noeud texte pour enregistrer le champ");
   } else {
     final FormUndoableEdit fedit = new FormUndoableEdit(this, noeud.getNodeValue(), valeur);
     if (cedit != null) cedit.addEdit(fedit);
     else doc.textPane.addEdit(fedit);
     final Element elparent = (Element) affParent.getNoeud();
     final String nom = cfg.nomAttribut(refNoeud);
     final String espace = cfg.espaceAttribut(refNoeud);
     elparent.setAttributeNS(espace, nom, valeur);
   }
   if (cedit != null) {
     cedit.end();
     doc.textPane.addEdit(cedit);
   }
   if ("".equals(valeur)) setValidite(true);
   else {
     if (attribut) setValidite(cfg.attributValide(refNoeud, valeur));
     else setValidite(cfg.valeurElementValide(refNoeud, valeur));
   }
 }
Example #11
0
  /**
   * Set the text as a CDATA section of a node.
   *
   * @param doc The document the node comes from.
   * @param node The node whichs CDATA section should be changed.
   * @param text The text to set.
   */
  public static void setCData(Document doc, Node node, String text) {
    Node cDataNode = getChild(node, "#cdata-section");

    if (cDataNode == null) {
      CDATASection cDataSection = doc.createCDATASection(text);
      node.appendChild(cDataSection);

    } else {
      cDataNode.setNodeValue(text);
    }
  }
Example #12
0
 public void setValue(String value) {
   Node valueNode = getValueNodeStrict();
   if (valueNode != null) {
     valueNode.setNodeValue(value);
   } else {
     try {
       addTextNode(value);
     } catch (SOAPException e) {
       throw new RuntimeException(e.getMessage());
     }
   }
 }
Example #13
0
 public static void setObjectValue(Node node, Object value) {
   switch (node.getNodeType()) {
     case Node.ELEMENT_NODE:
       setObjectValue((Element) node, value);
       break;
     case Node.DOCUMENT_NODE:
       setObjectValue(((Document) node).getDocumentElement(), value);
       break;
     default:
       // replace content
       node.setNodeValue(getStringValue(value));
   }
 }
 private void changerTexte(final String s) {
   final AffichageFormulaire affP = premierAffichage.chercherAffichage(parent);
   if (noeud instanceof Element) {
     final AffichageFormulaire aff = affP.chercherAffichage(noeud);
     Node noeudTexte = noeud.getFirstChild();
     if (aff == null && !"".equals(s)) recreerElement();
     else if (noeudTexte != null) noeudTexte.setNodeValue(s);
     else {
       noeudTexte = noeud.getOwnerDocument().createTextNode(s);
       noeud.appendChild(noeudTexte);
     }
     affP.majPanel(null);
   } else { // attribut
     final Element elparent = (Element) parent;
     if (!elparent.hasAttributeNS(noeud.getNamespaceURI(), noeud.getLocalName()))
       elparent.setAttributeNodeNS((Attr) noeud);
     noeud.setNodeValue(s);
     affP.majPanel(null);
   }
   final AffichageFormulaire affAj = affP.chercherAffichage(noeud);
   if (affAj != null && affAj.comp != null) affAj.comp.requestFocusInWindow();
 }
Example #15
0
  /**
   * Replaces ${property[:default value]} references in all attributes and text nodes of supplied
   * node. If the property is not defined neither in the given Properties instance nor in
   * System.getProperty and no default value is provided, a runtime exception is thrown.
   *
   * @param node DOM node to walk for substitutions
   * @param properties the Properties instance from which a value can be looked up
   */
  public static void substituteProperties(Node node, Properties properties) {
    // loop through child nodes
    Node child;
    Node next = node.getFirstChild();
    while ((child = next) != null) {

      // set next before we change anything
      next = child.getNextSibling();

      // handle child by node type
      if (child.getNodeType() == Node.TEXT_NODE) {
        child.setNodeValue(PropertiesUtil.substituteProperty(child.getNodeValue(), properties));
      } else if (child.getNodeType() == Node.ELEMENT_NODE) {
        // handle child elements with recursive call
        NamedNodeMap attributes = child.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
          Node attribute = attributes.item(i);
          attribute.setNodeValue(
              PropertiesUtil.substituteProperty(attribute.getNodeValue(), properties));
        }
        substituteProperties(child, properties);
      }
    }
  }
Example #16
0
  /**
   * Updates a node identified by xpath with a value.
   *
   * @param contextNode Node to be searched for the node
   * @param xpath query path to the node that has to be updated with the value
   * @param value value for the node
   */
  public static void putValue(Node contextNode, String xpath, String value) {

    if (contextNode == null || value == null) {
      return;
    }

    Document doc = contextNode.getOwnerDocument();

    if (doc == null) {
      return;
    }

    try {
      Node node = jaxenXPath.getSingleNode(contextNode, xpath);

      if (node != null) {
        switch (node.getNodeType()) {
          case Node.TEXT_NODE:
          case Node.CDATA_SECTION_NODE:
            break;

          case Node.ATTRIBUTE_NODE:
            ((Attr) node).setValue(value.trim());
            break;

          case Node.ELEMENT_NODE:
            // if node has no text nodes, create it
            if (!node.hasChildNodes()) {
              node.appendChild(doc.createTextNode(value.trim()));
            } else {
              NodeList childNodes = node.getChildNodes();
              int length = childNodes.getLength();
              for (int i = 0; i < length; i++) {
                Node child = childNodes.item(i);
                if (isText(child)) {
                  child.setNodeValue(value.trim());
                  return;
                }
              }

              node.appendChild(doc.createTextNode(value.trim()));
            }
            break;
        }
      }
    } catch (Exception e) {
    }
  }
Example #17
0
 /*
  * Set the value of the subnode
  *
  * @param name java.lang.String
  * @param value java.lang.String
  */
 public static void setNodeValue(Node node, String name, String value) {
   String s = node.getNodeValue();
   if (s != null) {
     node.setNodeValue(value);
     return;
   }
   NodeList nodelist = node.getChildNodes();
   for (int i = 0; i < nodelist.getLength(); i++) {
     if (nodelist.item(i) instanceof Text) {
       Text text = (Text) nodelist.item(i);
       text.setData(value);
       return;
     }
   }
   return;
 }
  public void test() {
    UnitOfWork uow = getSession().acquireUnitOfWork();
    Employee_XML emp =
        (Employee_XML)
            uow.readObject(
                Employee_XML.class, new ExpressionBuilder().get("firstName").equal("Frank"));
    Document resume = emp.resume;
    // System.out.println(resume);
    NodeList nodes = resume.getElementsByTagName("last-name");
    // System.out.println(nodes);
    Node lastName = nodes.item(0);
    Node lastNameText = lastName.getFirstChild();
    lastNameText.setNodeValue("Williams");
    emp.payroll_xml = "<payroll><salary>50000</salary><pay-period>weekly</pay-period></payroll>";

    uow.commit();
  }
Example #19
0
 public static void setStringValue(Element elem, String value) {
   // remove xsi:nil
   elem.removeAttributeNS(BpelConstants.NS_XML_SCHEMA_INSTANCE, BpelConstants.ATTR_NIL);
   // save first child
   Node firstChild = elem.getFirstChild();
   // if first child is text, reuse it
   if (firstChild instanceof org.w3c.dom.Text) {
     firstChild.setNodeValue(value);
   }
   // otherwise, just create new text
   else {
     firstChild = elem.getOwnerDocument().createTextNode(value);
   }
   // remove all children
   removeChildNodes(elem);
   // append text
   elem.appendChild(firstChild);
 }
Example #20
0
  public static void set(final Document doc, final String path, String value) {
    XPath xp = xpathFactory.newXPath();
    NodeList nodes;
    try {
      nodes = (NodeList) xp.compile(path).evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
      System.err.println(e);
      return;
    }

    for (int i = 0; i < nodes.getLength(); i++) {
      Node n = nodes.item(i);
      if (n != null && n.getNodeType() == Node.ATTRIBUTE_NODE) {
        n.setNodeValue(value);
      }
    }

    writeDocument(USER_CONFIG_FILE, doc);
  }
  /**
   * Update xml entries in dom document.
   *
   * @param config
   * @param payload
   */
  public static void updateXmlValues(Map<String, String> config, Document payload) {

    for (Map.Entry<String, String> configEntry : config.entrySet()) {
      // get <connection> nodes
      NodeList connectionNodes = payload.getElementsByTagName(configEntry.getKey());
      // update value for each node
      CDATASection cdata = null;
      for (int i = 0; i < connectionNodes.getLength(); i++) {
        Node n = connectionNodes.item(i);
        n.setNodeValue("");
        NodeList dbNodes = n.getChildNodes();
        while (dbNodes.getLength() > 0) {
          n.removeChild(dbNodes.item(0));
        }
        cdata = payload.createCDATASection(configEntry.getValue());
        n.appendChild(cdata);
      }
    }
  }
Example #22
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 #23
0
  protected static Node copyNode(Document target, Node source, boolean deep) {
    Node nodeNew;

    String strNodeName = source.getNodeName();
    String strNodeValue = source.getNodeValue();

    switch (source.getNodeType()) {
      case Node.ELEMENT_NODE:
        Element elem = target.createElement(strNodeName);
        nodeNew = elem;

        NamedNodeMap map = source.getAttributes();

        for (int iMap = 0; iMap < map.getLength(); iMap++) {
          Node attr = map.item(iMap);
          elem.setAttribute(attr.getNodeName(), attr.getNodeValue());
        }

        break;
      case Node.COMMENT_NODE:
        nodeNew = target.createComment(strNodeName);
        break;
      case Node.TEXT_NODE:
        nodeNew = target.createTextNode(strNodeName);
        break;
      default:
        nodeNew = null;
        break;
    }

    nodeNew.setNodeValue(strNodeValue);

    if (deep == true && nodeNew != null) DBSetup.importChildNodes(nodeNew, source, deep);

    return nodeNew;
  }
Example #24
0
  public static Object setProperty(Node node, Collection.Key k, Object value, boolean caseSensitive)
      throws PageException {
    Document doc = (node instanceof Document) ? (Document) node : node.getOwnerDocument();

    // Comment
    if (k.equals(XMLCOMMENT)) {
      removeChilds(XMLCaster.toRawNode(node), Node.COMMENT_NODE, false);
      node.appendChild(XMLCaster.toRawNode(XMLCaster.toComment(doc, value)));
    }
    // NS URI
    else if (k.equals(XMLNSURI)) {
      // TODO impl
      throw new ExpressionException("XML NS URI can't be set", "not implemented");
    }
    // Prefix
    else if (k.equals(XMLNSPREFIX)) {
      // TODO impl
      throw new ExpressionException("XML NS Prefix can't be set", "not implemented");
      // node.setPrefix(Caster.toString(value));
    }
    // Root
    else if (k.equals(XMLROOT)) {
      doc.appendChild(XMLCaster.toNode(doc, value));
    }
    // Parent
    else if (k.equals(XMLPARENT)) {
      Node parent = getParentNode(node, caseSensitive);
      Key name = KeyImpl.init(parent.getNodeName());
      parent = getParentNode(parent, caseSensitive);

      if (parent == null)
        throw new ExpressionException(
            "there is no parent element, you are already on the root element");

      return setProperty(parent, name, value, caseSensitive);
    }
    // Name
    else if (k.equals(XMLNAME)) {
      throw new XMLException("You can't assign a new value for the property [xmlname]");
    }
    // Type
    else if (k.equals(XMLTYPE)) {
      throw new XMLException("You can't change type of a xml node [xmltype]");
    }
    // value
    else if (k.equals(XMLVALUE)) {
      node.setNodeValue(Caster.toString(value));
    }
    // Attributes
    else if (k.equals(XMLATTRIBUTES)) {
      Element parent = XMLCaster.toElement(doc, node);
      Attr[] attres = XMLCaster.toAttrArray(doc, value);
      // print.ln("=>"+value);
      for (int i = 0; i < attres.length; i++) {
        if (attres[i] != null) {
          parent.setAttributeNode(attres[i]);
          // print.ln(attres[i].getName()+"=="+attres[i].getValue());
        }
      }
    }
    // Text
    else if (k.equals(XMLTEXT)) {
      removeChilds(XMLCaster.toRawNode(node), Node.TEXT_NODE, false);
      node.appendChild(XMLCaster.toRawNode(XMLCaster.toText(doc, value)));
    }
    // CData
    else if (k.equals(XMLCDATA)) {
      removeChilds(XMLCaster.toRawNode(node), Node.CDATA_SECTION_NODE, false);
      node.appendChild(XMLCaster.toRawNode(XMLCaster.toCDATASection(doc, value)));
    }
    // Children
    else if (k.equals(XMLCHILDREN)) {
      Node[] nodes = XMLCaster.toNodeArray(doc, value);
      removeChilds(XMLCaster.toRawNode(node), Node.ELEMENT_NODE, false);
      for (int i = 0; i < nodes.length; i++) {
        if (nodes[i] == node) throw new XMLException("can't assign a XML Node to himself");
        if (nodes[i] != null) node.appendChild(XMLCaster.toRawNode(nodes[i]));
      }
    } else {
      Node child = XMLCaster.toNode(doc, value);
      if (!k.getString().equalsIgnoreCase(child.getNodeName())) {
        throw new XMLException(
            "if you assign a XML Element to a XMLStruct , assignment property must have same name like XML Node Name",
            "Property Name is "
                + k.getString()
                + " and XML Element Name is "
                + child.getNodeName());
      }
      NodeList list = XMLUtil.getChildNodes(node, Node.ELEMENT_NODE);
      int len = list.getLength();
      Node n;
      for (int i = 0; i < len; i++) {
        n = list.item(i);
        if (nameEqual(n, k.getString(), caseSensitive)) {
          node.replaceChild(XMLCaster.toRawNode(child), XMLCaster.toRawNode(n));
          return value;
        }
      }
      node.appendChild(XMLCaster.toRawNode(child));
    }

    return value;
  }
Example #25
0
 public void setNodeValue(final String value) {
   if (node == null) {
     return;
   }
   node.setNodeValue(value);
 }
Example #26
0
 /**
  * Saves the current variable to the specified node
  *
  * @throws UnsupportedOperationException if the functionality is not supported by the current
  *     variable type
  */
 @Override
 public boolean saveToXML(Node node) throws UnsupportedOperationException {
   // TODO a pointed variable will be replaced by its value. Does this make sense ?
   node.setNodeValue(toString());
   return true;
 }
  /** 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;
  }
Example #28
0
 public static void setAttribute(Node node, String attName, String val) {
   NamedNodeMap attributes = node.getAttributes();
   Node attNode = node.getOwnerDocument().createAttribute(attName);
   attNode.setNodeValue(val);
   attributes.setNamedItem(attNode);
 }
  /**
   * Test update object of Content Relation.
   *
   * @throws Exception Thrown if description is not updated or other (unexpected) values are
   *     changed.
   */
  @Test
  public void testUpdateObject() throws Exception {

    // change subject
    Document relationCreated = getDocument(relationXml);

    String newSubject = createItemFromTemplate("item_without_component.xml");

    String oldSubject = null;
    Node subject = null;
    if (Constants.TRANSPORT_REST == getTransport()) {
      subject = selectSingleNode(relationCreated, "/content-relation/object/@href");
      newSubject = "/ir/item/" + newSubject;

      oldSubject =
          selectSingleNode(relationCreated, "/content-relation/object/@href").getNodeValue();
    } else {
      subject = selectSingleNode(relationCreated, "/content-relation/object/@objid");
      oldSubject =
          selectSingleNode(relationCreated, "/content-relation/object/@objid").getNodeValue();
    }

    subject.setNodeValue(newSubject);

    String relationToUdate = toString(relationCreated, false);

    // update
    String updatedRelationXml = update(this.relationId, relationToUdate);

    // check values of updated ContentRelation
    assertXmlValidContentRelation(updatedRelationXml);
    Document updatedRelationDoc = getDocument(updatedRelationXml);

    String subjectValue = null;

    if (Constants.TRANSPORT_REST == getTransport()) {
      subjectValue =
          selectSingleNode(updatedRelationDoc, "/content-relation/object/@href").getNodeValue();
    } else {
      subjectValue =
          selectSingleNode(updatedRelationDoc, "/content-relation/object/@objid").getNodeValue();
    }
    assertEquals(oldSubject, subjectValue);

    // retrieve
    String retrieveXml = retrieve(this.relationId);

    // check values of retrieved ContentRelation
    assertXmlValidContentRelation(retrieveXml);
    Document retrieveDoc = getDocument(retrieveXml);
    if (Constants.TRANSPORT_REST == getTransport()) {
      subjectValue = selectSingleNode(retrieveDoc, "/content-relation/object/@href").getNodeValue();
    } else {
      subjectValue =
          selectSingleNode(retrieveDoc, "/content-relation/object/@objid").getNodeValue();
    }
    assertEquals(oldSubject, subjectValue);

    String lmdCreate = getLastModificationDateValue(relationCreated);
    String lmdUpdate = getLastModificationDateValue(updatedRelationDoc);
    String lmdRetrieve = getLastModificationDateValue(retrieveDoc);
    assertEquals("resource modified", lmdCreate, lmdUpdate);
    assertEquals("resource modified", lmdCreate, lmdRetrieve);
  }
  protected boolean execute(Map<String, String> parameters) throws TransformerRunException {
    String inputXML = parameters.remove("xml");
    String factory = parameters.remove("factory");
    String out = parameters.remove("out");
    String copyReferring = parameters.remove("copyReferring");

    URL xsltURL = Stylesheets.get("dtbook2xhtml.xsl");
    File inFile = FilenameOrFileURI.toFile(inputXML);

    /*
     * Check if the doc is compound
     */
    try {
      NamespaceReporter nsr = new NamespaceReporter(inFile.toURI().toURL());
      if (nsr.getNamespaceURIs().contains(Namespaces.MATHML_NS_URI)) {
        this.sendMessage(
            i18n("CONTAINS_MATHML"), MessageEvent.Type.INFO, MessageEvent.Cause.SYSTEM);
        parameters.put("svg_mathml", "true");
      }

      if (nsr.getNamespaceURIs().contains(Namespaces.SVG_NS_URI)) {
        this.sendMessage(i18n("CONTAINS_SVG"), MessageEvent.Type.INFO, MessageEvent.Cause.SYSTEM);
        parameters.put("svg_mathml", "true");
      }
    } catch (Exception e) {
      this.sendMessage(
          i18n("ERROR", e.getMessage()), MessageEvent.Type.ERROR, MessageEvent.Cause.SYSTEM);
    }

    try {
      File outFile = FilenameOrFileURI.toFile(out);
      FileUtils.createDirectory(outFile.getParentFile());

      if ("true".equals(copyReferring)) {
        EFile eInFile = new EFile(inFile);
        String outFileName;
        Directory folder;
        if (outFile.isDirectory()) {
          folder = new Directory(outFile);
          outFileName = eInFile.getNameMinusExtension() + ".html";
        } else {
          folder = new Directory(outFile.getParentFile());
          outFileName = outFile.getName();
        }

        if (inFile.getParentFile().getCanonicalPath().equals(folder.getCanonicalPath())) {
          throw new TransformerRunException(i18n("INPUT_OUTPUT_SAME"));
        }
        Fileset fileset = this.buildFileSet(new File(inputXML));
        if (!parameters.containsKey("css_path")) {
          parameters.put("css_path", "default.css");
        }
        Map<String, Object> xslParams = new HashMap<String, Object>();
        xslParams.putAll(parameters);
        Stylesheet.apply(
            inputXML,
            xsltURL,
            new File(folder, outFileName).toString(),
            factory,
            xslParams,
            CatalogEntityResolver.getInstance());

        URL url2 = Css.get(Css.DocumentType.D202_XHTML);
        folder.writeToFile(parameters.get("css_path"), url2.openStream());

        for (Iterator<FilesetFile> it = fileset.getLocalMembers().iterator(); it.hasNext(); ) {
          FilesetFile fsf = it.next();
          if (fsf instanceof ImageFile) {
            FileUtils.copyChild(fsf.getFile(), folder, inFile.getParentFile());
          }
        }
      } else {
        Map<String, Object> xslParams = new HashMap<String, Object>();
        xslParams.putAll(parameters);
        Stylesheet.apply(
            inputXML, xsltURL, out, factory, xslParams, CatalogEntityResolver.getInstance());
      }

      if (parameters.containsKey("svg_mathml")) {
        // some post-xslt namespace cleanup.
        Map<String, Object> domConfigMap =
            LSParserPool.getInstance().getDefaultPropertyMap(Boolean.FALSE);
        domConfigMap.put("resource-resolver", CatalogEntityResolver.getInstance());
        LSParser parser = LSParserPool.getInstance().acquire(domConfigMap);
        DOMConfiguration domConfig = parser.getDomConfig();
        domConfig.setParameter("error-handler", this);
        Document doc = parser.parseURI(outFile.toURI().toString());

        SimpleNamespaceContext snc = new SimpleNamespaceContext();
        snc.declareNamespace("m", Namespaces.MATHML_NS_URI);
        NodeList math = XPathUtils.selectNodes(doc.getDocumentElement(), "//m:*", snc);
        for (int i = 0; i < math.getLength(); i++) {
          try {
            Node m = math.item(i);
            m.setPrefix("");
            if (m.getLocalName().equals("math")) {
              m.getAttributes().removeNamedItem("xmlns:dtbook");
              m.getAttributes().removeNamedItem("xmlns:m");
              Node c = m.getAttributes().getNamedItem("xmlns");
              c.setNodeValue(Namespaces.MATHML_NS_URI);
            }
          } catch (Exception e) {
            this.sendMessage(e.getMessage(), MessageEvent.Type.ERROR);
          }
        }

        Map<String, Object> props = new HashMap<String, Object>();
        props.put(
            "namespaces", Boolean.FALSE); // temp because of attributeNS bug(?) in Xerces DOM3LS				
        props.put("error-handler", this);
        // props.put("format-pretty-print", Boolean.TRUE);
        Serializer.serialize(doc, outFile, "utf-8", props);
      }

    } catch (XSLTException e) {
      throw new TransformerRunException(e.getMessage(), e);
    } catch (CatalogExceptionNotRecoverable e) {
      throw new TransformerRunException(e.getMessage(), e);
    } catch (FilesetFatalException e) {
      throw new TransformerRunException(e.getMessage(), e);
    } catch (IOException e) {
      throw new TransformerRunException(e.getMessage(), e);
    }

    return true;
  }