List of usage examples for org.w3c.dom Node removeChild
public Node removeChild(Node oldChild) throws DOMException;
oldChild
from the list of children, and returns it. From source file:org.infoglue.common.contenttypeeditor.actions.ViewContentTypeDefinitionAction.java
/** * This method moves an content type assetKey up one step. *//*from www .java 2s.c o m*/ public String doMoveAssetKeyUp() throws Exception { this.initialize(getContentTypeDefinitionId()); try { Document document = createDocumentFromDefinition(); String attributesXPath = "/xs:schema/xs:simpleType[@name = '" + ContentTypeDefinitionController.ASSET_KEYS + "']/xs:restriction/xs:enumeration[@value='" + this.assetKey + "']"; NodeList anl = XPathAPI.selectNodeList(document.getDocumentElement(), attributesXPath); if (anl != null && anl.getLength() > 0) { Element element = (Element) anl.item(0); Node parentElement = element.getParentNode(); Node previuosSibling = element.getPreviousSibling(); if (previuosSibling != null) { parentElement.removeChild(element); parentElement.insertBefore(element, previuosSibling); } } saveUpdatedDefinition(document); } catch (Exception e) { e.printStackTrace(); } this.initialize(getContentTypeDefinitionId()); return UPDATED; }
From source file:org.infoglue.common.contenttypeeditor.actions.ViewContentTypeDefinitionAction.java
/** * This method moves an content type asset key down one step. *//*from w w w .ja v a 2 s.com*/ public String doMoveAssetKeyDown() throws Exception { this.initialize(getContentTypeDefinitionId()); try { Document document = createDocumentFromDefinition(); String attributesXPath = "/xs:schema/xs:simpleType[@name = '" + ContentTypeDefinitionController.ASSET_KEYS + "']/xs:restriction/xs:enumeration[@value='" + this.assetKey + "']"; NodeList anl = XPathAPI.selectNodeList(document.getDocumentElement(), attributesXPath); if (anl != null && anl.getLength() > 0) { Element element = (Element) anl.item(0); Node parentElement = element.getParentNode(); Node nextSibling = element.getNextSibling(); if (nextSibling != null) { parentElement.removeChild(nextSibling); parentElement.insertBefore(nextSibling, element); } } saveUpdatedDefinition(document); } catch (Exception e) { e.printStackTrace(); } this.initialize(getContentTypeDefinitionId()); return UPDATED; }
From source file:org.infoscoop.request.filter.HTMLFragmentFilter.java
public byte[] fragmentHTML(Document doc, String xpath, String encoding) { if (log.isDebugEnabled()) log.debug("start fragmentHTML : xpath=" + xpath); Element root = doc.getDocumentElement(); if (!"html".equalsIgnoreCase(root.getNodeName())) { NodeList htmlList = root.getElementsByTagName("html"); if (htmlList.getLength() == 0) { log.error("document do not have html tag."); return null; }// w w w. j ava 2s .c o m root = (Element) htmlList.item(0); } if (log.isDebugEnabled()) log.debug("before html : \n" + document2String(doc)); // remove scriptTags /* NodeList scriptTags = XPathAPI.selectNodeList(root, "//script"); int tagsLength = scriptTags.getLength(); for(int i=0;i<tagsLength;i++){ scriptTags.item(i).getParentNode().removeChild(scriptTags.item(i));; } */ NodeList headTags = root.getElementsByTagName("head"); for (int j = 0; j < headTags.getLength(); j++) { Element headTag = (Element) headTags.item(j); NodeList metas = headTag.getElementsByTagName("meta"); for (int i = 0; i < metas.getLength(); i++) { Element tmpTag = (Element) metas.item(i); if (!"Content-Type".equalsIgnoreCase(tmpTag.getAttribute("http-equiv"))) headTag.removeChild(tmpTag); } } Node targetNode = null; Node body = null; byte[] fragmentHTML = null; try { targetNode = XPathAPI.selectSingleNode(root, xpath); body = XPathAPI.selectSingleNode(root, "//body"); } catch (Exception ex) { log.error("fragment failed.", ex); } if (log.isDebugEnabled()) log.debug("target:" + targetNode + " : body:" + body); if (targetNode != null && body != null) { if ("body".equals(targetNode.getNodeName().toLowerCase())) { // No processing } else { NodeList childNodes = body.getChildNodes(); int childLength = childNodes.getLength(); for (int i = childLength - 1; 0 <= i; i--) { body.removeChild(childNodes.item(i)); } body.appendChild(targetNode); } String resultHTML = document2String(doc); //FIXME resultHTML = resultHTML.replaceAll("&", "&"); if (log.isDebugEnabled()) { log.debug("result html : \n" + resultHTML); } try { fragmentHTML = resultHTML.getBytes(encoding); } catch (UnsupportedEncodingException ex) { log.error("Invalid encoding is specified.", ex); throw new IllegalArgumentException("unsupported encoding :[" + encoding + "]"); } } else { log.error("target is null : " + targetNode + " : " + body + " @" + xpath); throw new IllegalArgumentException("node not found :[" + xpath + "]"); } return fragmentHTML; }
From source file:org.infoscoop.service.AdminServiceUtil.java
/** * delete a Node which was appointed in an argument. * /*from w w w .j a v a 2 s .co m*/ * @param node * @return Node */ public static Node removeSelf(Node node) { if (node == null) return null; Node pNode = node.getParentNode(); if (pNode != null) { return pNode.removeChild(node); } return null; }
From source file:org.jahia.services.importexport.ExternalUsersImportUpdater.java
private boolean clean(InputStream inputStream, OutputStream outputStream, Map<String, String> pathMapping) throws IOException, ParserConfigurationException, SAXException, XPathExpressionException, TransformerException {/*from w w w .j ava 2 s. co m*/ Document doc = JahiaDocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new InputSource(inputStream)); XPath xpath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList) xpath.evaluate("//*[@*[name()='jcr:primaryType'] = 'jnt:usersFolder']", doc, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { Node legacyExtUser = nodes.item(i); Node parent = legacyExtUser.getParentNode(); if (!getNodePath(parent).startsWith("/sites/")) { parent.removeChild(legacyExtUser); } } Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.transform(new DOMSource(doc), new StreamResult(outputStream)); return nodes.getLength() > 0; }
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 w w w .ja v 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; }
From source file:org.jboss.pressgang.ccms.contentspec.builder.DocBookBuilder.java
/** * Adds a Topics contents as the introduction text for a Level. * * @param docBookVersion//from w w w. j a va2 s . co m * @param level The level the intro topic is being added for. * @param specTopic The Topic that contains the introduction content. * @param parentNode The DOM parent node the intro content is to be appended to. * @param doc The DOM Document the content is to be added to. */ protected void addTopicContentsToLevelDocument(final DocBookVersion docBookVersion, final Level level, final SpecTopic specTopic, final Element parentNode, final Document doc, final boolean includeInfo) { final Node section = doc.importNode(specTopic.getXMLDocument().getDocumentElement(), true); final String infoName; if (docBookVersion == DocBookVersion.DOCBOOK_50) { infoName = "info"; } else { infoName = DocBookUtilities.TOPIC_ROOT_SECTIONINFO_NODE_NAME; } if (includeInfo && (level.getLevelType() != LevelType.PART)) { // Reposition the sectioninfo final List<Node> sectionInfoNodes = XMLUtilities.getDirectChildNodes(section, infoName); if (sectionInfoNodes.size() != 0) { final String parentInfoName; if (docBookVersion == DocBookVersion.DOCBOOK_50) { parentInfoName = "info"; } else { parentInfoName = parentNode.getNodeName() + "info"; } // Check if the parent already has a info node final List<Node> infoNodes = XMLUtilities.getDirectChildNodes(parentNode, parentInfoName); final Node infoNode; if (infoNodes.size() == 0) { infoNode = doc.createElement(parentInfoName); DocBookUtilities.setInfo(docBookVersion, (Element) infoNode, parentNode); } else { infoNode = infoNodes.get(0); } // Merge the info text final NodeList sectionInfoChildren = sectionInfoNodes.get(0).getChildNodes(); final Node firstNode = infoNode.getFirstChild(); while (sectionInfoChildren.getLength() > 0) { if (firstNode != null) { infoNode.insertBefore(sectionInfoChildren.item(0), firstNode); } else { infoNode.appendChild(sectionInfoChildren.item(0)); } } } } // Remove the title and sectioninfo final List<Node> titleNodes = XMLUtilities.getDirectChildNodes(section, DocBookUtilities.TOPIC_ROOT_TITLE_NODE_NAME, infoName); for (final Node removeNode : titleNodes) { section.removeChild(removeNode); } // Move the contents of the section to the chapter/level final NodeList sectionChildren = section.getChildNodes(); while (sectionChildren.getLength() > 0) { parentNode.appendChild(sectionChildren.item(0)); } }
From source file:org.kalypsodeegree.xml.XMLTools.java
/** * removes all direct child nodes of the submitted node with the also submitted name *//*from www. j av a 2 s . c o m*/ public static Node removeNamedChildNodes(final Node node, final String nodeName) { final NodeList nl = node.getChildNodes(); if (nl != null && nl.getLength() > 0) { for (int i = 0; i < nl.getLength(); i++) { if (nl.item(i).getNodeName().equals(nodeName)) { node.removeChild(nl.item(i)); } } } return node; }
From source file:org.kuali.rice.krad.devtools.maintainablexml.MaintainableXMLConversionServiceImpl.java
private void transformNode(Document document, Node node, Class<?> currentClass, Map<String, String> propertyMappings) throws ClassNotFoundException, XPathExpressionException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException { for (Node childNode = node.getFirstChild(); childNode != null;) { Node nextChild = childNode.getNextSibling(); String propertyName = childNode.getNodeName(); if (childNode.hasAttributes()) { XPath xpath = XPathFactory.newInstance().newXPath(); Node serializationAttribute = childNode.getAttributes().getNamedItem(SERIALIZATION_ATTRIBUTE); if (serializationAttribute != null && StringUtils.equals(serializationAttribute.getNodeValue(), "custom")) { Node classAttribute = childNode.getAttributes().getNamedItem(CLASS_ATTRIBUTE); if (classAttribute != null && StringUtils.equals(classAttribute.getNodeValue(), "org.kuali.rice.kns.util.TypedArrayList")) { ((Element) childNode).removeAttribute(SERIALIZATION_ATTRIBUTE); ((Element) childNode).removeAttribute(CLASS_ATTRIBUTE); XPathExpression listSizeExpression = xpath.compile("//" + propertyName + "/org.apache.ojb.broker.core.proxy.ListProxyDefaultImpl/default/size/text()"); String size = (String) listSizeExpression.evaluate(childNode, XPathConstants.STRING); List<Node> nodesToAdd = new ArrayList<Node>(); if (StringUtils.isNotBlank(size) && Integer.valueOf(size) > 0) { XPathExpression listTypeExpression = xpath.compile("//" + propertyName + "/org.kuali.rice.kns.util.TypedArrayList/default/listObjectType/text()"); String listType = (String) listTypeExpression.evaluate(childNode, XPathConstants.STRING); XPathExpression listContentsExpression = xpath.compile("//" + propertyName + "/org.apache.ojb.broker.core.proxy.ListProxyDefaultImpl/" + listType); NodeList listContents = (NodeList) listContentsExpression.evaluate(childNode, XPathConstants.NODESET); for (int i = 0; i < listContents.getLength(); i++) { Node tempNode = listContents.item(i); transformClassNode(document, tempNode); nodesToAdd.add(tempNode); }/*from w w w.ja v a 2 s .c om*/ } for (Node removeNode = childNode.getFirstChild(); removeNode != null;) { Node nextRemoveNode = removeNode.getNextSibling(); childNode.removeChild(removeNode); removeNode = nextRemoveNode; } for (Node nodeToAdd : nodesToAdd) { childNode.appendChild(nodeToAdd); } } else { ((Element) childNode).removeAttribute(SERIALIZATION_ATTRIBUTE); XPathExpression mapContentsExpression = xpath.compile("//" + propertyName + "/map/string"); NodeList mapContents = (NodeList) mapContentsExpression.evaluate(childNode, XPathConstants.NODESET); List<Node> nodesToAdd = new ArrayList<Node>(); if (mapContents.getLength() > 0 && mapContents.getLength() % 2 == 0) { for (int i = 0; i < mapContents.getLength(); i++) { Node keyNode = mapContents.item(i); Node valueNode = mapContents.item(++i); Node entryNode = document.createElement("entry"); entryNode.appendChild(keyNode); entryNode.appendChild(valueNode); nodesToAdd.add(entryNode); } } for (Node removeNode = childNode.getFirstChild(); removeNode != null;) { Node nextRemoveNode = removeNode.getNextSibling(); childNode.removeChild(removeNode); removeNode = nextRemoveNode; } for (Node nodeToAdd : nodesToAdd) { childNode.appendChild(nodeToAdd); } } } } if (propertyMappings != null && propertyMappings.containsKey(propertyName)) { String newPropertyName = propertyMappings.get(propertyName); if (StringUtils.isNotBlank(newPropertyName)) { document.renameNode(childNode, null, newPropertyName); propertyName = newPropertyName; } else { // If there is no replacement name then the element needs // to be removed and skip all other processing node.removeChild(childNode); childNode = nextChild; continue; } } if (dateRuleMap != null && dateRuleMap.containsKey(propertyName)) { String newDateValue = dateRuleMap.get(propertyName); if (StringUtils.isNotBlank(newDateValue)) { if (childNode.getTextContent().length() == 10) { childNode.setTextContent(childNode.getTextContent() + " " + newDateValue); } } } if (currentClass != null) { if (childNode.hasChildNodes() && !(Collection.class.isAssignableFrom(currentClass) || Map.class.isAssignableFrom(currentClass))) { Class<?> propertyClass = PropertyUtils.getPropertyType(currentClass.newInstance(), propertyName); if (propertyClass != null && classPropertyRuleMap.containsKey(propertyClass.getName())) { transformNode(document, childNode, propertyClass, this.classPropertyRuleMap.get(propertyClass.getName())); } transformNode(document, childNode, propertyClass, classPropertyRuleMap.get("*")); } } childNode = nextChild; } }
From source file:org.kuali.rice.krad.service.impl.MaintainableXMLConversionServiceImpl.java
private void transformNode(Document document, Node node, Class<?> currentClass, Map<String, String> propertyMappings) throws ClassNotFoundException, XPathExpressionException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException { for (Node childNode = node.getFirstChild(); childNode != null;) { Node nextChild = childNode.getNextSibling(); String propertyName = childNode.getNodeName(); if (childNode.hasAttributes()) { XPath xpath = XPathFactory.newInstance().newXPath(); Node serializationAttribute = childNode.getAttributes().getNamedItem(SERIALIZATION_ATTRIBUTE); if (serializationAttribute != null && StringUtils.equals(serializationAttribute.getNodeValue(), "custom")) { Node classAttribute = childNode.getAttributes().getNamedItem(CLASS_ATTRIBUTE); if (classAttribute != null && StringUtils.equals(classAttribute.getNodeValue(), "org.kuali.rice.kns.util.TypedArrayList")) { ((Element) childNode).removeAttribute(SERIALIZATION_ATTRIBUTE); ((Element) childNode).removeAttribute(CLASS_ATTRIBUTE); XPathExpression listSizeExpression = xpath.compile("//" + propertyName + "/org.apache.ojb.broker.core.proxy.ListProxyDefaultImpl/default/size/text()"); String size = (String) listSizeExpression.evaluate(childNode, XPathConstants.STRING); List<Node> nodesToAdd = new ArrayList<Node>(); if (StringUtils.isNotBlank(size) && Integer.valueOf(size) > 0) { XPathExpression listTypeExpression = xpath.compile("//" + propertyName + "/org.kuali.rice.kns.util.TypedArrayList/default/listObjectType/text()"); String listType = (String) listTypeExpression.evaluate(childNode, XPathConstants.STRING); XPathExpression listContentsExpression = xpath.compile("//" + propertyName + "/org.apache.ojb.broker.core.proxy.ListProxyDefaultImpl/" + listType); NodeList listContents = (NodeList) listContentsExpression.evaluate(childNode, XPathConstants.NODESET); for (int i = 0; i < listContents.getLength(); i++) { Node tempNode = listContents.item(i); transformClassNode(document, tempNode); nodesToAdd.add(tempNode); }/*from w ww .j av a2 s .c o m*/ } for (Node removeNode = childNode.getFirstChild(); removeNode != null;) { Node nextRemoveNode = removeNode.getNextSibling(); childNode.removeChild(removeNode); removeNode = nextRemoveNode; } for (Node nodeToAdd : nodesToAdd) { childNode.appendChild(nodeToAdd); } } else { ((Element) childNode).removeAttribute(SERIALIZATION_ATTRIBUTE); XPathExpression mapContentsExpression = xpath.compile("//" + propertyName + "/map/string"); NodeList mapContents = (NodeList) mapContentsExpression.evaluate(childNode, XPathConstants.NODESET); List<Node> nodesToAdd = new ArrayList<Node>(); if (mapContents.getLength() > 0 && mapContents.getLength() % 2 == 0) { for (int i = 0; i < mapContents.getLength(); i++) { Node keyNode = mapContents.item(i); Node valueNode = mapContents.item(++i); Node entryNode = document.createElement("entry"); entryNode.appendChild(keyNode); entryNode.appendChild(valueNode); nodesToAdd.add(entryNode); } } for (Node removeNode = childNode.getFirstChild(); removeNode != null;) { Node nextRemoveNode = removeNode.getNextSibling(); childNode.removeChild(removeNode); removeNode = nextRemoveNode; } for (Node nodeToAdd : nodesToAdd) { childNode.appendChild(nodeToAdd); } } } } if (propertyMappings != null && propertyMappings.containsKey(propertyName)) { String newPropertyName = propertyMappings.get(propertyName); if (StringUtils.isNotBlank(newPropertyName)) { document.renameNode(childNode, null, newPropertyName); propertyName = newPropertyName; } else { // If there is no replacement name then the element needs // to be removed and skip all other processing node.removeChild(childNode); childNode = nextChild; continue; } } if (childNode.hasChildNodes() && !(Collection.class.isAssignableFrom(currentClass) || Map.class.isAssignableFrom(currentClass))) { if (propertyName.equals("principalId") && (node.getNodeName().equals("dataManagerUser") || node.getNodeName().equals("dataStewardUser"))) { currentClass = new org.kuali.rice.kim.impl.identity.PersonImpl().getClass(); } Class<?> propertyClass = PropertyUtils.getPropertyType(currentClass.newInstance(), propertyName); if (propertyClass != null && classPropertyRuleMap.containsKey(propertyClass.getName())) { transformNode(document, childNode, propertyClass, this.classPropertyRuleMap.get(propertyClass.getName())); } transformNode(document, childNode, propertyClass, classPropertyRuleMap.get("*")); } childNode = nextChild; } }