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:com.photon.phresco.impl.ConfigManagerImpl.java
private void deleteConfigurationByType(String envName, String type) throws ConfigurationException { Node environment = getNode(getXpathEnv(envName).toString()); NodeList childNodes = environment.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { if (childNodes.item(i).getNodeName().equalsIgnoreCase(type)) { environment.removeChild(childNodes.item(i)); }// www. j av a 2s. c o m } }
From source file:Main.java
private static Node replace2TextExceptTags(Document document, Node node, String... tags) { NodeList nodeList = node.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node subNode = nodeList.item(i); if (subNode.getNodeType() == Node.TEXT_NODE) { String text = ((Text) subNode).getTextContent(); text = text.replaceAll("[\t\n]+", "").replaceAll(" +", " "); subNode.setTextContent(text); continue; }//from ww w . j av a 2 s . com if (subNode.getNodeType() != Node.ELEMENT_NODE) { continue; } String nodeName = subNode.getNodeName(); boolean excepted = false; for (String tagName : tags) { if (tagName.equals(nodeName)) { excepted = true; replace2TextExceptTags(document, subNode, tags); break; } } if (excepted) { continue; } subNode = replace2TextExceptTags(document, subNode, tags); NodeList childList = subNode.getChildNodes(); List<Node> tempList = new ArrayList<Node>(); for (int j = 0; j < childList.getLength(); j++) { tempList.add(childList.item(j)); } for (Node child : tempList) { node.insertBefore(child, subNode); } node.removeChild(subNode); } return node; }
From source file:com.photon.phresco.framework.impl.ConfigurationWriter.java
private void deleteConfiguration(String envName, List<String> configNames) throws XPathExpressionException, PhrescoException { Node environment = getNode(getXpathEnv(envName).toString()); if (environment == null) { throw new PhrescoException("Environmnet not found to delete the Configuration"); }//w ww. j av a2 s . c o m for (String configName : configNames) { String delete = "/environments/environment[@name='testEnvironment']/*[@name='TestServer']"; Node configNode = getNode(getXpathConfigByEnv(envName, configName)); if (configNode == null) { throw new PhrescoException("Configuration not found to delete"); } environment.removeChild(configNode); } }
From source file:com.sap.research.roo.addon.nwcloud.NWCloudOperationsImpl.java
/** * This is the command "nwcloud enable-jpa". It will configure the JPA persistence layer in a * way that will use the HANA Cloud persistence service. *//*from w w w. ja va 2 s. co m*/ public void nwcloudEnableJPA() { // TODO // One could check here if ECLIPSELINK is used as JPA provider in persistence.xml // and abort, if something else is used. // 1. Copy the "persistence.xml" from the addon resources to the directory // "src\main\resources\META-INF\persistence.xml" of the project. // -> the existing "persistence.xml" will be overwritten, so we will do // a backup before to be able to revert this operation. // Get the META-INF dir of the current project ("src\main\resources\META-INF") // (Later in the packaged WAR this directory will reside in "WEB-INF\classes\META-INF".) String dirWebMetaInf = this.getPathResolved(Path.SRC_MAIN_RESOURCES, "META-INF"); // Backup "persistence.xml" which is located in this folder this.backup(dirWebMetaInf + File.separatorChar + "persistence.xml", null); // Overwrite the existing "persistence.xml" with the one included in the resources of our addon copyFileFromAddonToProject(dirWebMetaInf, "persistence.xml", "HANA Cloud JPA persistency config (needs EclipseLink)"); // -------------------------------------------------------------------------------- // 2. Backup "src\main\webapp\WEB-INF\web.xml" first, and then modify it by inserting // the following to declare the DataSource which the application server should // fetch from the environment and provide to the web app through JNDI. // <resource-ref> // <res-ref-name>jdbc/DefaultDB</res-ref-name> // <res-type>javax.sql.DataSource</res-type> // </resource-ref> // Get the WEB-INF dir ("src\main\webapp\WEB-INF"), where the "web.xml" is located. String dirWebInf = this.getPathResolved(Path.SRC_MAIN_WEBAPP, "WEB-INF"); String fileWebXml = dirWebInf + File.separatorChar + "web.xml"; // Backup "src\main\webapp\META-INF\web.xml" this.backup(fileWebXml, null); // Insert declaration for app server in "web.xml" to import DataSource from environment to JNDI // Read "web.xml" and store reference to root Element Document document = XmlUtils.readXml(fileManager.getInputStream(fileWebXml)); Element root = document.getDocumentElement(); // Add JNDI ressource definition for JPA data source to use (if it does not yet exist) if (XmlUtils.findFirstElement("/web-app/resource-ref/resource-ref-name[text()='jdbc/DefaultDB']", root) == null) { // Create needed DOM elements String elemNamespace = "http://java.sun.com/xml/ns/javaee"; Element resRefElement = document.createElementNS(elemNamespace, "resource-ref"); Element resRefNameElement = document.createElementNS(elemNamespace, "res-ref-name"); Node resRefNameElementText = document.createTextNode("jdbc/DefaultDB"); Element resRefTypeElement = document.createElementNS(elemNamespace, "res-type"); Node resRefTypeElementText = document.createTextNode("javax.sql.DataSource"); // Connect and insert elements in XML document resRefNameElement.appendChild(resRefNameElementText); resRefTypeElement.appendChild(resRefTypeElementText); resRefElement.appendChild(resRefNameElement); resRefElement.appendChild(resRefTypeElement); root.appendChild(resRefElement); // Update "web.xml" String descriptionOfChange = "Added JNDI ressource for JPA datasource"; fileManager.createOrUpdateTextFileIfRequired(fileWebXml, XmlUtils.nodeToString(document), descriptionOfChange, true); } // -------------------------------------------------------------------------------- // 3. Modify "src\main\resources\META-INF\spring\applicationContext.xml" // - Remove the existing declaration of the "dataSource" bean // <bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource"> // [...] // </bean> // - Insert statement to fetch dataSource from JNDI (as created by application server) // <jee:jndi-lookup id="dataSource" jndi-name="jdbc/DefaultDB" /> // Get the Spring config file of the current project ("src\main\resources\META-INF\spring\applicationContext.xml") // and create a backup of it, so we're able to revert the changes. String fileSpringConf = this.getPathResolved(Path.SPRING_CONFIG_ROOT, "applicationContext.xml"); this.backup(fileSpringConf, null); // Read "applicationContext.xml" and store reference to root Element document = XmlUtils.readXml(fileManager.getInputStream(fileSpringConf)); root = document.getDocumentElement(); // Loop through all bean elements and remove all beans having id "dataSource" String descriptionOfChange = ""; List<Element> beanElements = XmlUtils.findElements("/beans/bean", root); for (Element beanElement : beanElements) { // Did we find the bean with the id "dataSource"? if (beanElement.getAttribute("id").equalsIgnoreCase("dataSource")) { Node parent = beanElement.getParentNode(); parent.removeChild(beanElement); DomUtils.removeTextNodes(parent); descriptionOfChange = "Removed bean storing static datasource"; // We will not break the loop (even though we could theoretically), just in case there is more than one such bean declared } } // Update "applicationContext.xml" file if something has changed fileManager.createOrUpdateTextFileIfRequired(fileSpringConf, XmlUtils.nodeToString(document), descriptionOfChange, true); // Add bean for dynamic JNDI lookup of datasource (if it does not yet exist) if (XmlUtils.findFirstElement("/beans/jndi-lookup[@id='dataSource']", root) == null) { Element newJndiElement = document.createElementNS("http://www.springframework.org/schema/jee", "jee:jndi-lookup"); newJndiElement.setAttribute("id", "dataSource"); newJndiElement.setAttribute("jndi-name", "jdbc/DefaultDB"); root.appendChild(newJndiElement); descriptionOfChange = "Added bean for dynamic JNDI lookup of datasource"; // Update "applicationContext.xml" fileManager.createOrUpdateTextFileIfRequired(fileSpringConf, XmlUtils.nodeToString(document), descriptionOfChange, true); } }
From source file:com.zimbra.common.util.QuotedTextUtil.java
/** * Removes all subsequent siblings of the given node, and then does the same * for its parent. The effect is that all nodes that come after the given * node in a depth-first traversal of the DOM will be removed. * * @param node//from w ww . j ava 2 s.co m * @param clipNode if true, also remove the node */ private void prune(Node node, boolean clipNode) { Node tempNode = null; if (node != null && node.getParentNode() != null) { tempNode = node.getParentNode(); // clip all subsequent nodes while (tempNode.getLastChild() != null && tempNode.getLastChild() != node) { tempNode.removeChild(tempNode.getLastChild()); } // clip the node if asked if (clipNode && tempNode.getLastChild() != null && tempNode.getLastChild() == node) { tempNode.removeChild(tempNode.getLastChild()); } String nodeName = tempNode.getNodeName() != null ? tempNode.getNodeName() : ""; if (!nodeName.equals("body") && !nodeName.equals("html")) { prune(tempNode, false); } } }
From source file:com.collabnet.ccf.core.recovery.HospitalArtifactReplayer.java
private void removeProcessors(Node mapNode) { NodeList entryNodes = ((Element) mapNode).getElementsByTagName("entry"); String sourceComponent = entry.getSourceComponent(); int nodeLength = entryNodes.getLength(); for (int i = 0; i < nodeLength; i++) { Node entryNode = entryNodes.item(i); NamedNodeMap attributes = entryNode.getAttributes(); Node keyRefNode = attributes.getNamedItem("key-ref"); String keyRef = keyRefNode.getNodeValue(); if (keyRef.equals(sourceComponent)) { Node valueRefNode = attributes.getNamedItem("value-ref"); String valueRef = valueRefNode.getNodeValue(); sourceComponent = valueRef;/* w w w . j a v a2 s .com*/ } else { nodeLength--; i--; mapNode.removeChild(entryNode); } } }
From source file:com.hygenics.parser.ManualReplacement.java
private void transform() { log.info("Transforming"); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); for (String fpath : fpaths) { log.info("FILE: " + fpath); try {/* w w w .j a va 2 s . c om*/ // TRANSFORM DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new File(fpath)); Node root = doc.getFirstChild(); XPathFactory xfactory = XPathFactory.newInstance(); XPath xpath = xfactory.newXPath(); String database = null; String path = "//transformation/connection"; log.info("Removing"); for (String dbname : remove) { log.info("XPATH:" + path + "[descendant::name[contains(text(),'" + dbname.trim() + "')]]"); XPathExpression xepr = xpath .compile(path + "[descendant::name[contains(text(),'" + dbname.trim() + "')]]"); Node conn = (Node) xepr.evaluate(doc, XPathConstants.NODE); if (conn != null) { root.removeChild(conn); } } log.info("Transforming"); for (String key : databaseAttributes.keySet()) { database = key; log.info("XPATH:" + path + "[descendant::name[contains(text(),'" + database.trim() + "')]]"); XPathExpression xepr = xpath .compile(path + "[descendant::name[contains(text(),'" + database.trim() + "')]]"); Node conn = (Node) xepr.evaluate(doc, XPathConstants.NODE); if (conn != null) { if (remove.contains(key)) { root.removeChild(conn); } else { Map<String, String> attrs = databaseAttributes.get(database); NodeList nl = conn.getChildNodes(); Set<String> keys = databaseAttributes.get(key).keySet(); for (int i = 0; i < nl.getLength(); i++) { org.w3c.dom.Node n = nl.item(i); if (keys.contains(n.getNodeName().trim())) { n.setNodeValue(attrs.get(n.getNodeName())); } } } } if (!this.log_to_table || (this.log_to_table && this.loggingTables != null)) { log.info("Logging Manipulation"); log.info("PERFORMING LOGGING MANIPULATION: " + (!this.log_to_table) != null ? "Removing Logging Data" : "Adding Logging data"); String[] sections = new String[] { "trans-log-table", "perf-log-table", "channel-log-table", "step-log-table", "metrics-log-table" }; for (String section : sections) { log.info("Changing Settings for " + section); xepr = xpath.compile("//" + section + "/field/enabled"); NodeList nodes = (NodeList) xepr.evaluate(doc, XPathConstants.NODESET); log.info("Nodes Found: " + Integer.toString(nodes.getLength())); for (int i = 0; i < nodes.getLength(); i++) { if (!this.log_to_table) { nodes.item(i).setNodeValue("N"); } else { nodes.item(i).setNodeValue("Y"); } } for (String nodeName : new String[] { "schema", "connection", "table", "size_limit_lines", "interval", "timeout_days" }) { if (!this.log_to_table) { log.info("Changing Settings for Node: " + nodeName); xepr = xpath.compile("//" + section + "/" + nodeName); Node node = (Node) xepr.evaluate(doc, XPathConstants.NODE); if (node != null) { if (!this.log_to_table) { node.setNodeValue(null); } else if (this.loggingTables.containsKey(section) && this.loggingTables.get(section).containsKey(nodeName)) { node.setNodeValue(this.loggingTables.get(section).get(nodeName)); } } } } } } } // SET MAIN CONNECTION if (mainConnection != null) { XPathExpression xepr = xpath.compile(path); NodeList conns = (NodeList) xepr.evaluate(doc, XPathConstants.NODESET); // NodeSet is not a part of // org.w3c it is // actually a NodeList for (int i = 0; i < conns.getLength(); i++) { if (!conns.item(i).hasChildNodes()) {// only connection // elements // without child // nodes have // text content conns.item(i).setNodeValue(mainConnection); } } } if (this.replacements != null) { for (String key : this.replacements.keySet()) { XPathExpression xepr = xpath.compile(key); Node node = (Node) xepr.evaluate(doc, XPathConstants.NODE); if (node != null) { for (String attrVal : this.replacements.get(key).keySet()) { log.info("Replacing Information at " + key + "at " + attrVal); log.info("Replacement Will Be: " + StringEscapeUtils.escapeXml11(this.replacements.get(key).get(attrVal))); if (attrVal.toLowerCase().trim().equals("text")) { node.setNodeValue( StringEscapeUtils.escapeXml11(this.replacements.get(key).get(attrVal))); if (node.getNodeValue() == null) { node.setTextContent(StringEscapeUtils .escapeXml11(this.replacements.get(key).get(attrVal))); } } else { NamedNodeMap nattrs = node.getAttributes(); Node n = nattrs.getNamedItem(attrVal); if (n != null) { n.setNodeValue(StringEscapeUtils .escapeXml11(this.replacements.get(key).get(attrVal))); } else { log.warn("Attribute Not Found " + attrVal); } } } } else { log.warn("Node not found for " + key); } } } // WRITE TO FILE log.info("Writing to File"); TransformerFactory tfact = TransformerFactory.newInstance(); Transformer transformer = tfact.newTransformer(); DOMSource source = new DOMSource(doc); try (FileOutputStream stream = new FileOutputStream(new File(fpath))) { StreamResult result = new StreamResult(stream); transformer.transform(source, result); stream.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } } }
From source file:com.ironiacorp.persistence.datasource.HibernateConfigurationUtil.java
public void save() { NodeList propertiesNodes = config.getElementsByTagName("property"); Node parentNode = config.getElementsByTagName("session-factory").item(0); for (int i = 0; i < propertiesNodes.getLength(); i++) { Node propertyNode = propertiesNodes.item(i); // Get the property name NamedNodeMap attributesNodes = propertyNode.getAttributes(); Node attributeNode = attributesNodes.getNamedItem("name"); String property = attributeNode.getNodeValue(); if (property.equals("connection.driver_class") || property.equals("connection.url") || property.equals("connection.username") || property.equals("connection.password") || property.equals("dialect") || property.equals("hibernate.connection.datasource") || property.equals("hibernate.connection.username") || property.equals("hibernate.connection.password")) { parentNode.removeChild(propertyNode); }// w ww . ja v a2 s. c o m } for (Map.Entry<String, String> property : preferences.entrySet()) { if (property.getValue() != null) { Element propertyNode = config.createElement("property"); propertyNode.setAttribute("name", (String) property.getKey()); // TODO: propertyNode.setTextContent((String) property.getValue()); parentNode.appendChild(propertyNode); } } try { File configFile = new File(contextPath + configFileSufix); Transformer t = TransformerFactory.newInstance().newTransformer(); t.transform(new DOMSource(config), new StreamResult(configFile)); } catch (TransformerConfigurationException tce) { } catch (TransformerException te) { } }
From source file:com.krawler.portal.tools.ServiceBuilder.java
public void createModuleDef(com.krawler.utils.json.base.JSONArray jsonData, String classname) { String result = ""; try {//from w ww.ja v a2 s . c om DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.parse((new ClassPathResource("logic/moduleEx.xml").getFile())); //Document doc = docBuilder.newDocument(); NodeList modules = doc.getElementsByTagName("modules"); Node modulesNode = modules.item(0); Element module_ex = doc.getElementById(classname); if (module_ex != null) { modulesNode.removeChild(module_ex); } Element module = doc.createElement("module"); Element property_list = doc.createElement("property-list"); module.setAttribute("class", "com.krawler.esp.hibernate.impl." + classname); module.setAttribute("type", "pojo"); module.setAttribute("id", classname); for (int cnt = 0; cnt < jsonData.length(); cnt++) { Element propertyNode = doc.createElement("property"); JSONObject jsonObj = jsonData.optJSONObject(cnt); propertyNode.setAttribute("name", jsonObj.optString("varname")); propertyNode.setAttribute("type", jsonObj.optString("modulename").toLowerCase()); property_list.appendChild(propertyNode); } module.appendChild(property_list); modulesNode.appendChild(module); TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//KRAWLER//DTD BUSINESSRULES//EN"); trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://localhost/dtds/module.dtd"); trans.setOutputProperty(OutputKeys.VERSION, "1.0"); trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // create string from xml tree File outputFile = (new ClassPathResource("logic/moduleEx.xml").getFile()); outputFile.setWritable(true); // StringWriter sw = new StringWriter(); StreamResult sresult = new StreamResult(outputFile); DOMSource source = new DOMSource(doc); trans.transform(source, sresult); // result = sw.toString(); } catch (SAXException ex) { logger.warn(ex.getMessage(), ex); } catch (IOException ex) { logger.warn(ex.getMessage(), ex); } catch (TransformerException ex) { logger.warn(ex.getMessage(), ex); } catch (ParserConfigurationException ex) { logger.warn(ex.getMessage(), ex); } }
From source file:com.krawler.portal.tools.ServiceBuilder.java
public void createModuleDef(ArrayList list, String classname) { String result = ""; try {// w ww . j a va 2 s . co m DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.parse((new ClassPathResource("logic/moduleEx.xml").getFile())); //Document doc = docBuilder.newDocument(); NodeList modules = doc.getElementsByTagName("modules"); Node modulesNode = modules.item(0); Element module_ex = doc.getElementById(classname); if (module_ex != null) { modulesNode.removeChild(module_ex); } Element module = doc.createElement("module"); Element property_list = doc.createElement("property-list"); module.setAttribute("class", "com.krawler.esp.hibernate.impl." + classname); module.setAttribute("type", "pojo"); module.setAttribute("id", classname); for (int cnt = 0; cnt < list.size(); cnt++) { Element propertyNode = doc.createElement("property"); Hashtable mapObj = (Hashtable) list.get(cnt); propertyNode.setAttribute("name", mapObj.get("name").toString()); propertyNode.setAttribute("type", mapObj.get("type").toString().toLowerCase()); property_list.appendChild(propertyNode); } module.appendChild(property_list); modulesNode.appendChild(module); TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//KRAWLER//DTD BUSINESSRULES//EN"); trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://192.168.0.4/dtds/module.dtd"); trans.setOutputProperty(OutputKeys.VERSION, "1.0"); trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // create string from xml tree File outputFile = (new ClassPathResource("logic/moduleEx.xml").getFile()); outputFile.setWritable(true); // StringWriter sw = new StringWriter(); StreamResult sresult = new StreamResult(outputFile); DOMSource source = new DOMSource(doc); trans.transform(source, sresult); // result = sw.toString(); } catch (SAXException ex) { logger.warn(ex.getMessage(), ex); } catch (IOException ex) { logger.warn(ex.getMessage(), ex); } catch (TransformerException ex) { logger.warn(ex.getMessage(), ex); } catch (ParserConfigurationException ex) { logger.warn(ex.getMessage(), ex); } finally { // System.out.println(result); // return result; } }