List of usage examples for org.w3c.dom Node cloneNode
public Node cloneNode(boolean deep);
From source file:org.broadleafcommerce.common.extensibility.context.merge.handlers.NodeReplaceInsert.java
protected boolean replaceNode(Node[] primaryNodes, Node testNode, final String attribute, List<Node> usedNodes) { if (testNode.getAttributes().getNamedItem(attribute) == null) { return false; }/* www . j a va2s .c o m*/ //filter out primary nodes that don't have the attribute ArrayList<Node> filterList = new ArrayList<Node>(); for (int j = 0; j < primaryNodes.length; j++) { if (primaryNodes[j].getAttributes().getNamedItem(attribute) != null) { filterList.add(primaryNodes[j]); } } Node[] filtered = {}; filtered = filterList.toArray(filtered); Comparator<Node> idCompare = new Comparator<Node>() { public int compare(Node arg0, Node arg1) { Node id1 = arg0.getAttributes().getNamedItem(attribute); Node id2 = arg1.getAttributes().getNamedItem(attribute); String idVal1 = id1.getNodeValue(); String idVal2 = id2.getNodeValue(); return idVal1.compareTo(idVal2); } }; Arrays.sort(filtered, idCompare); int pos = Arrays.binarySearch(filtered, testNode, idCompare); if (pos >= 0) { Node newNode = filtered[pos].getOwnerDocument().importNode(testNode.cloneNode(true), true); filtered[pos].getParentNode().replaceChild(newNode, filtered[pos]); usedNodes.add(testNode); return true; } return false; }
From source file:org.chiba.xml.xforms.ui.Repeat.java
private void initializePrototype(Node parent, Node prototype) { Node copy = prototype.cloneNode(false); if (copy.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) copy; if (element.getAttributeNS(null, "id").length() == 0) { element.setAttributeNS(null, "id", this.container.generateId()); }/*from w ww . j a va2s . c om*/ NodeList children = prototype.getChildNodes(); for (int index = 0; index < children.getLength(); index++) { initializePrototype(element, children.item(index)); } } parent.appendChild(copy); }
From source file:org.codelibs.fess.transformer.FessXpathTransformer.java
protected String getSingleNodeValue(final Document document, final String xpath, final boolean pruned) { StringBuilder buf = null;/*w w w. j a v a 2s. c o m*/ NodeList list = null; try { list = getXPathAPI().selectNodeList(document, xpath); for (int i = 0; i < list.getLength(); i++) { if (buf == null) { buf = new StringBuilder(1000); } else { buf.append(' '); } final Node node = list.item(i); if (pruned) { final Node n = pruneNode(node.cloneNode(true)); buf.append(n.getTextContent()); } else { buf.append(node.getTextContent()); } } } catch (final Exception e) { logger.warn("Could not parse a value of " + xpath); } if (buf == null) { return null; } return buf.toString(); }
From source file:org.deri.any23.extractor.html.HCardExtractor.java
private void fixIncludes(HTMLDocument document, Node node) { NamedNodeMap attributes = node.getAttributes(); // header case test 32 if ("TD".equals(node.getNodeName()) && (null != attributes.getNamedItem("headers"))) { String id = attributes.getNamedItem("headers").getNodeValue(); Node header = document.findNodeById(id); if (null != header) { node.appendChild(header.cloneNode(true)); attributes.removeNamedItem("headers"); }/* w w w. ja va 2 s. c om*/ } // include pattern, test 31 for (Node current : document.findAll("//*[@class]")) { if (!DomUtils.hasClassName(current, "include")) continue; // we have to remove the field soon to avoid infinite loops // no null check, we know it's there or we won't be in the loop current.getAttributes().removeNamedItem("class"); ArrayList<TextField> res = new ArrayList<TextField>(); HTMLDocument.readUrlField(res, current); TextField id = res.get(0); if (null == id) continue; id = new TextField(StringUtils.substringAfter(id.value(), "#"), id.source()); Node included = document.findNodeById(id.value()); if (null == included) continue; current.appendChild(included.cloneNode(true)); } }
From source file:org.etudes.component.app.melete.SubSectionUtilImpl.java
public String bringOneLevelUp(String sectionsSeqXML, String section_id) throws MeleteException { try {//from www . j a va 2s .co m org.w3c.dom.Document subSectionW3CDOM = Xml.readDocumentFromString(sectionsSeqXML); org.w3c.dom.Element root = subSectionW3CDOM.getDocumentElement(); org.w3c.dom.Element bringUpThisElement = subSectionW3CDOM.getElementById(section_id); if (bringUpThisElement == null) { throw new MeleteException("indent_left_fail"); } org.w3c.dom.Node makeSiblingOf = bringUpThisElement.getParentNode(); org.w3c.dom.Node bringUpBeforeThisElement = makeSiblingOf.getNextSibling(); //Clone the node that needs to be moved org.w3c.dom.Node newNode = bringUpThisElement.cloneNode(true); org.w3c.dom.Node nextNode = bringUpThisElement.getNextSibling(); org.w3c.dom.Node prevNode = null; //Iterate through each of the node's siblings and make them its children //In the process, also delete the siblings while (nextNode != null) { org.w3c.dom.Node cNode = nextNode.cloneNode(true); prevNode = nextNode; newNode.appendChild(cNode); nextNode = nextNode.getNextSibling(); prevNode.getParentNode().removeChild(prevNode); } //Insert the new node, inbetween or end of list, takes null or bringUpBeforeThisElement makeSiblingOf.getParentNode().insertBefore(newNode, bringUpBeforeThisElement); //Delete node from original position bringUpThisElement.getParentNode().removeChild(bringUpThisElement); return writeDocumentToString(subSectionW3CDOM); } catch (MeleteException mex) { throw mex; } catch (Exception ex) { if (logger.isDebugEnabled()) { logger.error("some other error on indenting right" + ex.toString()); ex.printStackTrace(); } throw new MeleteException("indent_right_fail"); } }
From source file:org.etudes.component.app.melete.SubSectionUtilImpl.java
public String deleteSection(String sectionsSeqXML, String section_id) throws MeleteException { try {/* ww w . ja va 2 s . c o m*/ org.w3c.dom.Document subSectionW3CDOM = Xml.readDocumentFromString(sectionsSeqXML); org.w3c.dom.Element root = subSectionW3CDOM.getDocumentElement(); org.w3c.dom.Element deleteThisElement = subSectionW3CDOM.getElementById(section_id); if (deleteThisElement != null) { org.w3c.dom.Node deleteElementParent = deleteThisElement.getParentNode(); // child nodes becomes children of parent node if (deleteThisElement.hasChildNodes()) { NodeList children = deleteThisElement.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { org.w3c.dom.Node deleteThisElementChild = children.item(i); if (deleteThisElementChild.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) deleteElementParent.insertBefore(deleteThisElementChild.cloneNode(true), deleteThisElement); } } //remove the element deleteElementParent.removeChild(deleteThisElement); } return writeDocumentToString(subSectionW3CDOM); } catch (Exception ex) { if (logger.isDebugEnabled()) { logger.debug("some other error on delete subsections xml string" + ex.toString()); ex.printStackTrace(); } throw new MeleteException("delete_module_fail"); } }
From source file:org.etudes.component.app.melete.SubSectionUtilImpl.java
public String moveDownSection(String sectionsSeqXML, String section_id) throws MeleteException { try {//from w w w . j a va 2s . c o m org.w3c.dom.Document subSectionW3CDOM = Xml.readDocumentFromString(sectionsSeqXML); org.w3c.dom.Element root = subSectionW3CDOM.getDocumentElement(); org.w3c.dom.Element moveDownThisElement = subSectionW3CDOM.getElementById(section_id); org.w3c.dom.Node afterElementParent = moveDownThisElement.getParentNode(); if (!afterElementParent.getLastChild().equals(moveDownThisElement)) { org.w3c.dom.Node afterElement = moveDownThisElement.getNextSibling(); org.w3c.dom.Node cloneafterElement = afterElement.cloneNode(true); afterElementParent.insertBefore(cloneafterElement, moveDownThisElement); afterElementParent.removeChild(afterElement); } return writeDocumentToString(subSectionW3CDOM); } catch (Exception ex) { if (logger.isDebugEnabled()) { logger.debug("some other error on moving down subsections xml string" + ex.toString()); ex.printStackTrace(); } throw new MeleteException("move_down_fail"); } }
From source file:org.etudes.component.app.melete.SubSectionUtilImpl.java
public String moveAllDownSection(String sectionsSeqXML, String section_id) throws MeleteException { try {//from www . ja v a 2 s .co m org.w3c.dom.Document subSectionW3CDOM = Xml.readDocumentFromString(sectionsSeqXML); org.w3c.dom.Element root = subSectionW3CDOM.getDocumentElement(); org.w3c.dom.Element moveDownThisElement = subSectionW3CDOM.getElementById(section_id); org.w3c.dom.Node cloneMoveElement = moveDownThisElement.cloneNode(true); org.w3c.dom.Node afterElementParent = moveDownThisElement.getParentNode(); org.w3c.dom.Node LastChildOfafterElementParent = afterElementParent.getLastChild(); org.w3c.dom.Node cloneLastChildElement = LastChildOfafterElementParent.cloneNode(true); if (!LastChildOfafterElementParent.equals(moveDownThisElement)) { afterElementParent.replaceChild(cloneMoveElement, LastChildOfafterElementParent); org.w3c.dom.Node newLastChild = afterElementParent.getLastChild(); afterElementParent.insertBefore(cloneLastChildElement, newLastChild); afterElementParent.removeChild(moveDownThisElement); } return writeDocumentToString(subSectionW3CDOM); } catch (Exception ex) { if (logger.isDebugEnabled()) { logger.debug("some other error on moving down subsections xml string" + ex.toString()); ex.printStackTrace(); } throw new MeleteException("move_down_fail"); } }
From source file:org.gvnix.web.screen.roo.addon.AbstractPatternJspMetadataListener.java
/** * Modifies create.jspx or update.jspx generate by Roo based on * {@link RooJspx} param./* www . ja v a2 s. c om*/ * <p> * It wraps field element into ul/li elements and add a hidden param * <code>gvnixpattern</code> and a button * * @param rooJspx */ private void modifyRooJsp(RooJspx rooJspx) { String controllerPath = webScaffoldAnnotationValues.getPath(); Validate.notNull(controllerPath, PATH_IS_NOT_SPECIFIED + webScaffoldAnnotationValues.getGovernorTypeDetails().getName() + "'"); if (!controllerPath.startsWith("/")) { controllerPath = "/".concat(controllerPath); } PathResolver pathResolver = getProjectOperations().getPathResolver(); String docJspx = pathResolver.getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), "WEB-INF/views" + controllerPath + "/" + rooJspx.name() + ".jspx"); if (!getFileManager().exists(docJspx)) { // create.jspx doesn't exist, so nothing to do return; } InputStream docJspxIs = getFileManager().getInputStream(docJspx); Document docJspXml; try { docJspXml = XmlUtils.getDocumentBuilder().parse(docJspxIs); } catch (Exception ex) { throw new IllegalStateException("Could not open " + rooJspx.name() + ".jspx file", ex); } Element docRoot = docJspXml.getDocumentElement(); // Add new tag namesapces Element divMain = XmlUtils.findFirstElement("/div", docRoot); if (rooJspx.equals(RooJspx.create) || rooJspx.equals(RooJspx.update)) { divMain.setAttribute("xmlns:pattern", "urn:jsptagdir:/WEB-INF/tags/pattern"); } String divContPaneId = XmlUtils .convertId(DIV_ID_PREFIX + formbackingType.getFullyQualifiedTypeName() + "_contentPane"); Element divContentPane = XmlUtils .findFirstElement("/div/" + rooJspx.name() + "/div[@id='" + divContPaneId + "']", docRoot); if (null == divContentPane) { divContentPane = new XmlElementBuilder(DIV_ELEMENT, docJspXml).addAttribute(ID_ATTRIBUTE, divContPaneId) .addAttribute(CLASS_ATTRIBUTE, "patternContentPane").build(); } String divFormId = XmlUtils .convertId(DIV_ID_PREFIX + formbackingType.getFullyQualifiedTypeName() + "_formNoedit"); Element divForm = XmlUtils.findFirstElement("/div/" + rooJspx.name() + "/div/div[@id='" + divFormId + "']", docRoot); if (null == divForm) { divForm = new XmlElementBuilder(DIV_ELEMENT, docJspXml).addAttribute(ID_ATTRIBUTE, divFormId) .addAttribute(CLASS_ATTRIBUTE, "formularios boxNoedit").build(); divContentPane.appendChild(divForm); } String idPrefix = rooJspx.equals(RooJspx.create) ? "fc:" : rooJspx.equals(RooJspx.update) ? "fu:" : "ps:"; Element form = XmlUtils.findFirstElement( "/div/" + rooJspx.name() + "[@id='" + XmlUtils.convertId(idPrefix + formbackingType.getFullyQualifiedTypeName()) + "']", docRoot); if (form != null) { // Wrap fields into <ul><li/></ul> NodeList fields = form.getChildNodes(); if (fields.getLength() > 0) { Node thisField; for (int i = 0; i < fields.getLength(); i++) { thisField = fields.item(i); if (thisField.getNodeName().startsWith("field:") && !thisField.getParentNode().getNodeName().equalsIgnoreCase("li")) { if (null != thisField.getAttributes() /* * && null != thisField.getAttributes().getNamedItem( * "type") && * !thisField.getAttributes().getNamedItem("type") * .getNodeValue().equalsIgnoreCase("hidden") */) { Node thisNodeCpy = thisField.cloneNode(true); String fieldAttValue = thisNodeCpy.getAttributes().getNamedItem(FIELD_ATTRIBUTE) .getNodeValue(); Element li = new XmlElementBuilder("li", docJspXml) .addAttribute(CLASS_ATTRIBUTE, "size120") .addAttribute(ID_ATTRIBUTE, XmlUtils.convertId( "li:".concat(formbackingType.getFullyQualifiedTypeName()) .concat(".").concat(fieldAttValue))) .addChild(thisNodeCpy).build(); Element ul = new XmlElementBuilder("ul", docJspXml) .addAttribute(CLASS_ATTRIBUTE, "formInline") .addAttribute(ID_ATTRIBUTE, XmlUtils.convertId( "ul:".concat(formbackingType.getFullyQualifiedTypeName()) .concat(".").concat(fieldAttValue))) .addChild(li).build(); divForm.appendChild(ul); form.removeChild(thisField); // form.replaceChild(ul, thisField); } } } } if (rooJspx.equals(RooJspx.create) || rooJspx.equals(RooJspx.update)) { // Add a hidden field holding gvnixpattern parameter if exists String hiddenFieldId = XmlUtils .convertId("c:" + formbackingType.getFullyQualifiedTypeName() + "_gvnixpattern"); Element hiddenField = XmlUtils.findFirstElement( "/div/" + rooJspx.name() + "/div/div/hiddengvnixpattern[@id='" + hiddenFieldId + "']", docRoot); if (null == hiddenField) { hiddenField = new XmlElementBuilder("pattern:hiddengvnixpattern", docJspXml) .addAttribute(ID_ATTRIBUTE, hiddenFieldId) .addAttribute("value", "${param.gvnixpattern}") .addAttribute(RENDER_ATTRIBUTE, "${not empty param.gvnixpattern}").build(); divForm.appendChild(hiddenField); } // Add a cancel button String cancelId = XmlUtils .convertId(idPrefix + formbackingType.getFullyQualifiedTypeName() + "_cancel"); Element cancelButton = XmlUtils.findFirstElement( "/div/" + rooJspx.name() + "/div/div/cancelbutton[@id='" + cancelId + "']", docRoot); if (null == cancelButton) { cancelButton = new XmlElementBuilder("pattern:cancelbutton", docJspXml) .addAttribute(ID_ATTRIBUTE, cancelId) .addAttribute(RENDER_ATTRIBUTE, "${not empty param.gvnixpattern}").build(); divForm.appendChild(cancelButton); } } form.appendChild(divContentPane); } DomUtils.removeTextNodes(docJspXml); getFileManager().createOrUpdateTextFileIfRequired(docJspx, XmlUtils.nodeToString(docJspXml), true); // writeToDiskIfNecessary(docJspx, docJspXml); }
From source file:org.jahia.services.importexport.ExternalUsersImportUpdater.java
private boolean transform(InputStream inputStream, OutputStream outputStream, Map<String, String> pathMapping) throws IOException, ParserConfigurationException, SAXException, XPathExpressionException, TransformerException {//from ww w.jav a 2s . c om Document doc = JahiaDocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new InputSource(inputStream)); XPath xpath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList) xpath.evaluate( "//*[@*[name()='jcr:primaryType'] = 'jnt:user' and @*[name()='j:external'] = 'true']", doc, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { Node legacyExtUser = nodes.item(i); ArrayList<Node> tree = new ArrayList<Node>(); Element extUser = (Element) legacyExtUser.cloneNode(true); extUser.setAttribute("jcr:primaryType", "jnt:externalUser"); String externalSource = extUser.getAttribute("j:externalSource"); extUser.setAttribute("j:externalSource", externalSource + ".users"); tree.add(extUser); Node parent = legacyExtUser.getParentNode(); parent.removeChild(legacyExtUser); boolean removeParent = !hasChildElement(parent); while (parent != null && !"users".equals(parent.getNodeName())) { tree.add(0, parent.cloneNode(false)); Node n = parent.getParentNode(); if (removeParent) { n.removeChild(parent); removeParent = !hasChildElement(n); } parent = n; } if (parent == null) continue; StringBuilder mappingSrc = new StringBuilder(getNodePath(parent)); StringBuilder mappingDst = new StringBuilder(getNodePath(parent)); NodeList nodeList = ((Element) parent).getElementsByTagName("providers"); if (nodeList.getLength() == 0) { Element e = doc.createElement("providers"); e.setAttribute("jcr:primaryType", "jnt:usersFolder"); e.setAttribute("jcr:mixinTypes", "jmix:hasExternalProviderExtension"); e.setAttribute("j:published", "true"); e.setAttribute("j:publicationStatus", "1"); parent.appendChild(e); parent = e; } else { parent = nodeList.item(0); } mappingDst.append("/").append(parent.getNodeName()); nodeList = ((Element) parent).getElementsByTagName(externalSource); if (nodeList.getLength() == 0) { Element e = doc.createElement(externalSource); e.setAttribute("jcr:primaryType", "jnt:usersFolder"); e.setAttribute("provider", externalSource + ".users"); e.setAttribute("j:publicationStatus", "4"); parent.appendChild(e); parent = e; } else { parent = nodeList.item(0); } mappingDst.append("/").append(parent.getNodeName()); for (Node n : tree) { String nodeName = n.getNodeName(); mappingSrc.append("/").append(nodeName); mappingDst.append("/").append(nodeName); nodeList = ((Element) parent).getElementsByTagName(nodeName); if (nodeList.getLength() == 0) { Node node = parent.appendChild(n); parent = node; } else { parent = nodeList.item(0); } } pathMapping.put(mappingSrc.toString(), mappingDst.toString()); } Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.transform(new DOMSource(doc), new StreamResult(outputStream)); return nodes.getLength() > 0; }