List of usage examples for org.w3c.dom Element insertBefore
public Node insertBefore(Node newChild, Node refChild) throws DOMException;
newChild
before the existing child node refChild
. From source file:com.netspective.sparx.util.xml.XmlSource.java
/** * Given an element, apply templates to the node. If there is an attribute called "template" then inherit that * template first. Then, search through all of the nodes in the element and try to find all <include-template id="x"> * elements to copy the template elements at those locations. Also, go through each child to see if a tag name * exists that matches a template name -- if it does, then "inherit" that template to replace the element at that * location./* w ww .jav a 2 s .com*/ */ public void processTemplates(Element elem) { inheritNodes(elem, templates, "template", defaultExcludeElementsFromInherit); NodeList includes = elem.getElementsByTagName("include-template"); if (includes != null && includes.getLength() > 0) { for (int n = 0; n < includes.getLength(); n++) { Element include = (Element) includes.item(n); String templateName = include.getAttribute("id"); Element template = (Element) templates.get(templateName); if (template != null) { NodeList incChildren = template.getChildNodes(); for (int c = 0; c < incChildren.getLength(); c++) { Node incCopy = xmlDoc.importNode(incChildren.item(c), true); if (incCopy.getNodeType() == Node.ELEMENT_NODE) ((Element) incCopy).setAttribute("_included-from-template", templateName); elem.insertBefore(incCopy, include); } } } } NodeList children = elem.getChildNodes(); for (int c = 0; c < children.getLength(); c++) { Node childNode = children.item(c); if (childNode.getNodeType() != Node.ELEMENT_NODE) continue; String nodeName = childNode.getNodeName(); if (templates.containsKey(nodeName)) { Element template = (Element) templates.get(nodeName); Node incCopy = xmlDoc.importNode(template, true); if (incCopy.getNodeType() == Node.ELEMENT_NODE) ((Element) incCopy).setAttribute("_included-from-template", nodeName); // make sure that the child's attributes overwrite the attributes in the templates with the same name NamedNodeMap attrsInChild = childNode.getAttributes(); for (int a = 0; a < attrsInChild.getLength(); a++) { Node childAttr = attrsInChild.item(a); ((Element) incCopy).setAttribute(childAttr.getNodeName(), childAttr.getNodeValue()); } // now do the actual replacement inheritNodes((Element) incCopy, templates, "template", defaultExcludeElementsFromInherit); elem.replaceChild(incCopy, childNode); } else inheritNodes((Element) childNode, templates, "template", defaultExcludeElementsFromInherit); } }
From source file:org.gvnix.addon.datatables.addon.DatatablesOperationsImpl.java
/** * Insert a new element of type {@code nodeName} into {@code parent} with * definition declared in {@code subElementsAndValue}. * {@code subElementsAndValue} is composed in pairs of <i>nodeName</i> and * <i>textValue</i>.//w w w . jav a 2 s .c om * * @param doc * @param parent * @param nodeName * @param subElementsAndValue */ private void insertXmlElement(Document doc, Element parent, String nodeName, String... subElementsAndValue) { Validate.isTrue(subElementsAndValue.length % 2 == 0, "subElementsAndValue must be even"); Element newElement = doc.createElement(nodeName); Element subElement; for (int i = 0; i < subElementsAndValue.length - 1; i = i + 2) { subElement = doc.createElement(subElementsAndValue[i]); subElement.setTextContent(subElementsAndValue[i + 1]); newElement.appendChild(subElement); } // insert element as last element of the node type Node inserPosition = null; // Locate last node of this type List<Element> elements = XmlUtils.findElements(nodeName, parent); if (!elements.isEmpty()) { inserPosition = elements.get(elements.size() - 1).getNextSibling(); } // Add node if (inserPosition == null) { parent.appendChild(newElement); } else { parent.insertBefore(newElement, inserPosition); } }
From source file:org.gvnix.service.roo.addon.addon.ws.WSConfigServiceImpl.java
/** * Update web configuration file (web.xml) with CXF configuration. * <ul>// w ww . j a v a 2s .c o m * <li>Add the CXF servlet declaration and mapping with '/services/*' URL to * access published web services. All added before forst servlet mapping</li> * <li>Configure Spring context to load cxf configuration file</li> * </ul> * <p> * If already installed cxf declaration, nothing to do. * </p> */ protected void updateWebConfigurationFile() { // Get web configuration file document and root XML representation MutableFile file = getFileManager().updateFile(getWebConfigFilePath()); Document web = getInputDocument(file.getInputStream()); Element root = web.getDocumentElement(); // If CXF servlet already installed: nothing to do if (XmlUtils.findFirstElement( "/web-app/servlet[servlet-class='org.apache.cxf.transport.servlet.CXFServlet']", root) != null) { return; } // Get first servlet mapping declaration Element firstMapping = XmlUtils.findRequiredElement("/web-app/servlet-mapping", root); // Add CXF servlet definition before first mapping root.insertBefore(getServletDefinition(web), firstMapping.getPreviousSibling()); // Add CXF servlet mapping before first mapping root.insertBefore(getServletMapping(web), firstMapping); // Add CXF configuration file path to Spring context Element context = XmlUtils .findFirstElement("/web-app/context-param[param-name='contextConfigLocation']/param-value", root); context.setTextContent(getCxfConfigRelativeFilePath().concat(" ").concat(context.getTextContent())); // Write modified web.xml to disk XmlUtils.writeXml(file.getOutputStream(), web); }
From source file:com.netspective.sparx.util.xml.XmlSource.java
public Document loadXML(File file) { if (docSource == null) { errors.clear();/* ww w.j a v a 2 s . co m*/ sourceFiles.clear(); metaInfoElem = null; metaInfoOptionsElem = null; } SourceInfo sourceInfo = new SourceInfo(docSource, file); sourceFiles.put(file.getAbsolutePath(), sourceInfo); Document doc = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); doc = parser.parse(file); doc.normalize(); } catch (Exception e) { throw new RuntimeException("XML Parsing error in '" + file.getAbsolutePath() + "': " + e); } if (docSource == null) { xmlDoc = doc; docSource = sourceInfo; } /* find all of the <include file="xyz"> elements and "include" all the elements in that document as children of the main document */ Element rootElem = doc.getDocumentElement(); NodeList includes = rootElem.getElementsByTagName("include"); if (includes != null && includes.getLength() > 0) { for (int n = 0; n < includes.getLength(); n++) { Element include = (Element) includes.item(n); String incFileAttr = include.getAttribute("file"); File incFile = new File(file.getParentFile(), incFileAttr); if (!sourceFiles.containsKey(incFile.getAbsolutePath())) { Document includeDoc = loadXML(incFile); if (includeDoc != null) { Element includeRoot = includeDoc.getDocumentElement(); NodeList incChildren = includeRoot.getChildNodes(); for (int c = 0; c < incChildren.getLength(); c++) { Node incCopy = doc.importNode(incChildren.item(c), true); if (incCopy.getNodeType() == Node.ELEMENT_NODE) ((Element) incCopy).setAttribute("_included-from", incFileAttr); rootElem.insertBefore(incCopy, include); } } } } } /* find all of the <pre-process stylesheet="xyz"> elements and "pre-process" using XSLT stylesheets */ NodeList preProcessors = rootElem.getElementsByTagName("pre-process"); if (preProcessors != null && preProcessors.getLength() > 0) { for (int n = 0; n < preProcessors.getLength(); n++) { Element preProcessor = (Element) preProcessors.item(n); String ppFileAttr = preProcessor.getAttribute("style-sheet"); if (ppFileAttr.length() == 0) { addError("No style-sheet attribute provided for pre-process element"); continue; } File ppFile = new File(file.getParentFile(), ppFileAttr); docSource.addPreProcessor(new SourceInfo(docSource, ppFile)); preProcess(ppFile); } } return doc; }
From source file:com.springsource.hq.plugin.tcserver.plugin.serverconfig.AbstractXmlElementConverter.java
protected void updateServletInitParam(Document document, Element servlet, String attributeName, Object attributeValue, Properties catalinaProperties) { List<Element> initParams = getChildElements(servlet, "init-param"); boolean paramFound = false; for (int i = 0; i < initParams.size(); i++) { Element initParam = (Element) initParams.get(i); final String paramName = getChildElements(initParam, "param-name").get(0).getTextContent(); if (paramName.equals(attributeName)) { paramFound = true;//from www . ja v a2 s . c om if (attributeValue != null && !("".equals(attributeValue))) { Element paramValue = getChildElements(initParam, "param-value").get(0); paramValue.setTextContent( determineNewValue(paramValue.getTextContent(), attributeValue, catalinaProperties)); } else { servlet.removeChild(initParam); } break; } } if (!(paramFound) && attributeValue != null && !("".equals(attributeValue))) { Element newInitParam = document.createElement("init-param"); Element paramName = document.createElement("param-name"); Element paramValue = document.createElement("param-value"); newInitParam.appendChild(paramName); newInitParam.appendChild(paramValue); paramName.setTextContent(attributeName); paramValue.setTextContent( determineNewValue(paramValue.getTextContent(), attributeValue, catalinaProperties)); // This list contains all the elements that are required by the XSD to occur after init-param node List<String> orderedTypes = Arrays.asList("load-on-startup", "enabled", "async-supported", "run-as", "security-role-ref", "multipart-config"); boolean elementInserted = false; for (String orderedType : orderedTypes) { List<Element> foundElement = getChildElements(servlet, orderedType); if (!foundElement.isEmpty()) { servlet.insertBefore(newInitParam, foundElement.get(0)); elementInserted = true; break; } } if (!elementInserted) { servlet.appendChild(newInitParam); } } }
From source file:com.netspective.sparx.util.xml.XmlSource.java
public void inheritElement(Element srcElement, Element destElem, Set excludeElems, String inheritedFromNode) { NamedNodeMap inhAttrs = srcElement.getAttributes(); for (int i = 0; i < inhAttrs.getLength(); i++) { Node attrNode = inhAttrs.item(i); final String nodeName = attrNode.getNodeName(); if (!excludeElems.contains(nodeName) && destElem.getAttribute(nodeName).equals("")) destElem.setAttribute(nodeName, attrNode.getNodeValue()); }//from w w w. j a va 2 s .c om DocumentFragment inheritFragment = xmlDoc.createDocumentFragment(); NodeList inhChildren = srcElement.getChildNodes(); for (int i = inhChildren.getLength() - 1; i >= 0; i--) { Node childNode = inhChildren.item(i); // only add if there isn't an attribute overriding this element final String nodeName = childNode.getNodeName(); if (destElem.getAttribute(nodeName).length() == 0 && (!excludeElems.contains(nodeName))) { Node cloned = childNode.cloneNode(true); if (inheritedFromNode != null && cloned.getNodeType() == Node.ELEMENT_NODE) ((Element) cloned).setAttribute("_inherited-from", inheritedFromNode); inheritFragment.insertBefore(cloned, inheritFragment.getFirstChild()); } } destElem.insertBefore(inheritFragment, destElem.getFirstChild()); }
From source file:com.enonic.vertical.adminweb.MenuHandlerServlet.java
private void moveMenuItemUp(HttpServletRequest request, HttpServletResponse response, HttpSession session, ExtendedMap formItems) throws VerticalAdminException { String menuXML = (String) session.getAttribute("menuxml"); Document doc = XMLTool.domparse(menuXML); String xpath = "//menuitem[@key = '" + formItems.getString("key") + "']"; Element elem = (Element) XMLTool.selectNode(doc, xpath); Element parent = (Element) elem.getParentNode(); Element previousSibling = (Element) elem.getPreviousSibling(); elem = (Element) parent.removeChild(elem); doc.importNode(elem, true);/* ww w .j av a 2 s.c o m*/ if (previousSibling == null) // This is the top element, move it to the bottom { parent.appendChild(elem); } else { parent.insertBefore(elem, previousSibling); } session.setAttribute("menuxml", XMLTool.documentToString(doc)); MultiValueMap queryParams = new MultiValueMap(); queryParams.put("page", formItems.get("page")); queryParams.put("op", "browse"); queryParams.put("keepxml", "yes"); queryParams.put("highlight", formItems.get("key")); queryParams.put("menukey", formItems.get("menukey")); queryParams.put("parentmi", formItems.get("parentmi")); queryParams.put("subop", "shiftmenuitems"); queryParams.put("move_menuitem", formItems.getString("move_menuitem", "")); queryParams.put("move_from_parent", formItems.getString("move_from_parent", "")); queryParams.put("move_to_parent", formItems.getString("move_to_parent", "")); redirectClientToAdminPath("adminpage", queryParams, request, response); }
From source file:com.enonic.vertical.adminweb.MenuHandlerServlet.java
private void moveMenuItemDown(HttpServletRequest request, HttpServletResponse response, HttpSession session, ExtendedMap formItems) throws VerticalAdminException { String menuXML = (String) session.getAttribute("menuxml"); Document doc = XMLTool.domparse(menuXML); String xpath = "/model/menuitems-to-list//menuitem[@key = '" + formItems.getString("key") + "']"; Element movingMenuItemElement = (Element) XMLTool.selectNode(doc, xpath); Element parentElement = (Element) movingMenuItemElement.getParentNode(); Node nextSiblingElement = movingMenuItemElement.getNextSibling(); movingMenuItemElement = (Element) parentElement.removeChild(movingMenuItemElement); doc.importNode(movingMenuItemElement, true); if (nextSiblingElement != null) { // spool forward... for (nextSiblingElement = nextSiblingElement.getNextSibling(); (nextSiblingElement != null && nextSiblingElement .getNodeType() != Node.ELEMENT_NODE); nextSiblingElement = nextSiblingElement .getNextSibling()) { }//ww w. j av a 2 s .com if (nextSiblingElement != null) { parentElement.insertBefore(movingMenuItemElement, nextSiblingElement); } else { parentElement.appendChild(movingMenuItemElement); } } else { // This is the bottom element, move it to the top parentElement.insertBefore(movingMenuItemElement, parentElement.getFirstChild()); } session.setAttribute("menuxml", XMLTool.documentToString(doc)); MultiValueMap queryParams = new MultiValueMap(); queryParams.put("page", formItems.get("page")); queryParams.put("op", "browse"); queryParams.put("keepxml", "yes"); queryParams.put("highlight", formItems.get("key")); queryParams.put("menukey", formItems.get("menukey")); queryParams.put("parentmi", formItems.get("parentmi")); queryParams.put("subop", "shiftmenuitems"); queryParams.put("move_menuitem", formItems.getString("move_menuitem", "")); queryParams.put("move_from_parent", formItems.getString("move_from_parent", "")); queryParams.put("move_to_parent", formItems.getString("move_to_parent", "")); redirectClientToAdminPath("adminpage", queryParams, request, response); }
From source file:eu.europa.ec.markt.dss.applet.view.validationpolicy.EditView.java
private void nodeActionAdd(MouseEvent mouseEvent, final int selectedRow, final TreePath selectedPath, final XmlDomAdapterNode clickedItem, final JTree tree) { final Element clickedElement = (Element) clickedItem.node; // popup menu for list -> add final JPopupMenu popup = new JPopupMenu(); //delete node final JMenuItem menuItemToDelete = new JMenuItem(ResourceUtils.getI18n("DELETE")); menuItemToDelete.addActionListener(new ActionListener() { @Override//from www . ja v a2 s. c o m public void actionPerformed(ActionEvent actionEvent) { // find the order# of the child to delete final int index = clickedItem.getParent().index(clickedItem); Node oldChild = clickedElement.getParentNode().removeChild(clickedElement); if (index > -1) { validationPolicyTreeModel.fireTreeNodesRemoved(selectedPath.getParentPath(), index, oldChild); } } }); popup.add(menuItemToDelete); //Add node/value final Map<XsdNode, Object> xsdTree = validationPolicyTreeModel.getXsdTree(); final List<XsdNode> children = getChildrenToAdd(clickedElement, xsdTree); for (final XsdNode xsdChild : children) { final String xmlName = xsdChild.getLastNameOfPath(); final JMenuItem menuItem = new JMenuItem(ResourceUtils.getI18n("ADD") + " (" + xmlName + " " + xsdChild.getType().toString().toLowerCase() + ")"); popup.add(menuItem); menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { Document document = getModel().getValidationPolicy().getDocument(); final Node newElement; if (xsdChild.getType() == XsdNodeType.TEXT) { // TEXT element always appended (last child) newElement = clickedElement.appendChild(document.createTextNode("VALUE")); } else if (xsdChild.getType() == XsdNodeType.ATTRIBUTE) { newElement = document.createAttributeNS(null, xmlName); ((Attr) newElement).setValue("VALUE"); clickedElement.setAttributeNode((Attr) newElement); } else if (xsdChild.getType() == XsdNodeType.ELEMENT) { final Element childToAdd = document .createElementNS("http://dss.markt.ec.europa.eu/validation/diagnostic", xmlName); // find the correct possition to add the child // Get all allowed children Map<XsdNode, Object> childrenMap = getChild(getXPath(clickedElement), xsdTree); boolean toAddSeen = false; Element elementIsToAddBeforeThisOne = null; for (final XsdNode allowed : childrenMap.keySet()) { if (!toAddSeen && allowed == xsdChild) { toAddSeen = true; continue; } if (toAddSeen) { final NodeList elementsByTagNameNS = clickedElement.getElementsByTagNameNS( "http://dss.markt.ec.europa.eu/validation/diagnostic", allowed.getLastNameOfPath()); if (elementsByTagNameNS.getLength() > 0) { // we found an element that is supposed to be after the one to add elementIsToAddBeforeThisOne = (Element) elementsByTagNameNS.item(0); break; } } } if (elementIsToAddBeforeThisOne != null) { newElement = clickedElement.insertBefore(childToAdd, elementIsToAddBeforeThisOne); } else { newElement = clickedElement.appendChild(childToAdd); } } else { throw new IllegalArgumentException("Unknow XsdNode NodeType " + xsdChild.getType()); } document.normalizeDocument(); int indexOfAddedItem = 0; final int childCount = clickedItem.childCount(); for (int i = 0; i < childCount; i++) { if (clickedItem.child(i).node == newElement) { indexOfAddedItem = i; break; } } TreeModelEvent event = new TreeModelEvent(validationPolicyTreeModel, selectedPath, new int[] { indexOfAddedItem }, new Object[] { newElement }); validationPolicyTreeModel.fireTreeNodesInserted(event); tree.expandPath(selectedPath); //Update model getModel().getValidationPolicy().setXmlDom(new XmlDom(document)); } }); } popup.show(tree, mouseEvent.getX(), mouseEvent.getY()); }
From source file:eu.europa.esig.dss.applet.view.validationpolicy.EditView.java
private void nodeActionAdd(MouseEvent mouseEvent, final int selectedRow, final TreePath selectedPath, final XmlDomAdapterNode clickedItem, final JTree tree) { final Element clickedElement = (Element) clickedItem.node; // popup menu for list -> add final JPopupMenu popup = new JPopupMenu(); //delete node final JMenuItem menuItemToDelete = new JMenuItem(ResourceUtils.getI18n("DELETE")); menuItemToDelete.addActionListener(new ActionListener() { @Override//from w w w. j a v a 2s . c o m public void actionPerformed(ActionEvent actionEvent) { // find the order# of the child to delete final int index = clickedItem.getParent().index(clickedItem); Node oldChild = clickedElement.getParentNode().removeChild(clickedElement); if (index > -1) { validationPolicyTreeModel.fireTreeNodesRemoved(selectedPath.getParentPath(), index, oldChild); } } }); popup.add(menuItemToDelete); //Add node/value final Map<XsdNode, Object> xsdTree = validationPolicyTreeModel.getXsdTree(); final List<XsdNode> children = getChildrenToAdd(clickedElement, xsdTree); for (final XsdNode xsdChild : children) { final String xmlName = xsdChild.getLastNameOfPath(); final JMenuItem menuItem = new JMenuItem(ResourceUtils.getI18n("ADD") + " (" + xmlName + " " + xsdChild.getType().toString().toLowerCase() + ")"); popup.add(menuItem); menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { Document document = getModel().getValidationPolicy().getDocument(); final Node newElement; if (xsdChild.getType() == XsdNodeType.TEXT) { // TEXT element always appended (last child) newElement = clickedElement.appendChild(document.createTextNode("VALUE")); } else if (xsdChild.getType() == XsdNodeType.ATTRIBUTE) { newElement = document.createAttributeNS(null, xmlName); ((Attr) newElement).setValue("VALUE"); clickedElement.setAttributeNode((Attr) newElement); } else if (xsdChild.getType() == XsdNodeType.ELEMENT) { final Element childToAdd = document .createElementNS("http://dss.esig.europa.eu/validation/diagnostic", xmlName); // find the correct possition to add the child // Get all allowed children Map<XsdNode, Object> childrenMap = getChild(getXPath(clickedElement), xsdTree); boolean toAddSeen = false; Element elementIsToAddBeforeThisOne = null; for (final XsdNode allowed : childrenMap.keySet()) { if (!toAddSeen && (allowed == xsdChild)) { toAddSeen = true; continue; } if (toAddSeen) { final NodeList elementsByTagNameNS = clickedElement.getElementsByTagNameNS( "http://dss.esig.europa.eu/validation/diagnostic", allowed.getLastNameOfPath()); if (elementsByTagNameNS.getLength() > 0) { // we found an element that is supposed to be after the one to add elementIsToAddBeforeThisOne = (Element) elementsByTagNameNS.item(0); break; } } } if (elementIsToAddBeforeThisOne != null) { newElement = clickedElement.insertBefore(childToAdd, elementIsToAddBeforeThisOne); } else { newElement = clickedElement.appendChild(childToAdd); } } else { throw new IllegalArgumentException("Unknow XsdNode NodeType " + xsdChild.getType()); } document.normalizeDocument(); int indexOfAddedItem = 0; final int childCount = clickedItem.childCount(); for (int i = 0; i < childCount; i++) { if (clickedItem.child(i).node == newElement) { indexOfAddedItem = i; break; } } TreeModelEvent event = new TreeModelEvent(validationPolicyTreeModel, selectedPath, new int[] { indexOfAddedItem }, new Object[] { newElement }); validationPolicyTreeModel.fireTreeNodesInserted(event); tree.expandPath(selectedPath); //Update model getModel().getValidationPolicy().setXmlDom(new XmlDom(document)); } }); } popup.show(tree, mouseEvent.getX(), mouseEvent.getY()); }