List of usage examples for org.w3c.dom Element getParentNode
public Node getParentNode();
From source file:com.hp.hpl.inkml.InkMLDOMParser.java
/** * Method to bind Channel element//from w ww.ja v a2 s . co m * * @param channelElement Channel element * @return Channel data object * @throws InkMLException */ protected Channel getChannel(final Element channelElement) throws InkMLException { Channel channel = null; final String chnName = channelElement.getAttribute("name"); if ("".equals(chnName)) { throw new InkMLException("Channel element must have value for 'name' attribute"); } else { channel = new Channel(chnName); } // checking for intermittend channel if ("intermittentChannels".equalsIgnoreCase(channelElement.getParentNode().getLocalName())) { channel.setIntermittent(true); } // Extract and set Attribute values final NamedNodeMap attrMap = channelElement.getAttributes(); final int length = attrMap.getLength(); for (int i = 0; i < length; i++) { final Node attr = attrMap.item(i); channel.setAttribute(attr.getLocalName(), attr.getNodeValue()); } return channel; }
From source file:com.autentia.mvn.plugin.changes.BugzillaChangesMojo.java
/** * Replaces the current release node in the changes.xml document * //from w w w . j a v a 2s . c om * @param elementRelease * @param changesXml * @throws MojoExecutionException */ private void replaceReleaseNode(final Element elementRelease, final byte[] changesXml) throws MojoExecutionException { try { // formamos el documento obtenido final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); final DocumentBuilder db = dbf.newDocumentBuilder(); final ByteArrayInputStream bais = new ByteArrayInputStream(changesXml); final Document docChanges = db.parse(bais); // recuperamos el nodo de la release // slo debe haber un elemento final Node releaseNode = docChanges.getElementsByTagName(ELEMENT_RELEASE).item(0); final Node importNode = elementRelease.getOwnerDocument().importNode(releaseNode, true); elementRelease.getParentNode().replaceChild(importNode, elementRelease); } catch (final ParserConfigurationException e) { this.getLog().error("Error reading file " + this.xmlPath, e); throw new MojoExecutionException("Error reading file " + this.xmlPath, e); } catch (final SAXException e) { this.getLog().error("Error reading file " + this.xmlPath, e); throw new MojoExecutionException("Error reading file " + this.xmlPath, e); } catch (final IOException e) { this.getLog().error("Error reading file " + this.xmlPath, e); throw new MojoExecutionException("Error reading file " + this.xmlPath, e); } }
From source file:jef.tools.XMLUtils.java
/** * ?????//from w w w . j a va2 s .c o m * * @param node * ???? * @param newName * ?? * @return ????DOMElement */ public static Element changeNodeName(Element node, String newName) { Document doc = node.getOwnerDocument(); Element newEle = doc.createElement(newName); Node parent = node.getParentNode(); parent.removeChild(node); parent.appendChild(newEle); for (Node child : toArray(node.getChildNodes())) { node.removeChild(child); newEle.appendChild(child); } return newEle; }
From source file:de.betterform.xml.xforms.action.LoadAction.java
private void handleEmbedding(String absoluteURI, HashMap map, boolean includeCSS, boolean includeScript) throws XFormsException { // if(this.targetAttribute == null) return; //todo: handle multiple params if (absoluteURI.indexOf("?") > 0) { String name = absoluteURI.substring(absoluteURI.indexOf("?") + 1); String value = name.substring(name.indexOf("=") + 1, name.length()); name = name.substring(0, name.indexOf("=")); this.container.getProcessor().setContextParam(name, value); }//from w ww . jav a 2 s . c om if (this.targetAttribute == null) { map.put("uri", absoluteURI); map.put("show", this.showAttribute); // dispatch internal betterform event this.container.dispatch(this.target, BetterFormEventNames.LOAD_URI, map); return; } if (!("embed".equals(this.showAttribute))) { throw new XFormsException("@show must be 'embed' if @target is given but was: '" + this.showAttribute + "' on Element " + DOMUtil.getCanonicalPath(this.element)); } //todo: dirty dirty dirty String evaluatedTarget = evalAttributeValueTemplates(this.targetAttribute, this.element); if (LOGGER.isDebugEnabled()) { LOGGER.debug("targetid evaluated to: " + evaluatedTarget); } Node embed = getEmbeddedDocument(absoluteURI); if (embed == null) { //todo: review: context info params containing a '-' fail during access in javascript! //todo: the following property should have been 'resource-uri' according to spec map.put("resourceUri", absoluteURI); this.container.dispatch(this.target, XFormsEventNames.LINK_EXCEPTION, map); return; } // Check for 'ClientSide' events (DOMFocusIN / DOMFocusOUT / xforms-select) String utilizedEvents = this.getEventsInSubform(embed); // fetch CSS / JavaScript String inlineCssRules = ""; String externalCssRules = ""; String inlineJavaScript = ""; String externalJavaScript = ""; if (includeCSS) { inlineCssRules = getInlineCSS(embed); externalCssRules = getExternalCSS(embed); } if (includeScript) { inlineJavaScript = getInlineJavaScript(embed); externalJavaScript = getExternalJavaScript(embed); } if (Config.getInstance().getProperty("webprocessor.doIncludes", "false").equals("true")) { embed = doIncludes(embed, absoluteURI); } embed = extractFragment(absoluteURI, embed); if (LOGGER.isDebugEnabled()) { DOMUtil.prettyPrintDOM(embed); } Element embeddedNode; Element targetElem = getTargetElement(evaluatedTarget); //Test if targetElem exist. if (targetElem != null) { // destroy existing embedded form within targetNode if (targetElem.hasChildNodes()) { destroyembeddedModels(targetElem); Initializer.disposeUIElements(targetElem); } // import referenced embedded form into host document embeddedNode = (Element) this.container.getDocument().importNode(embed, true); //import namespaces NamespaceResolver.applyNamespaces(targetElem.getOwnerDocument().getDocumentElement(), (Element) embeddedNode); // keep original targetElem id within hostdoc embeddedNode.setAttributeNS(null, "id", targetElem.getAttributeNS(null, "id")); //copy all Attributes that might have been on original mountPoint to embedded node DOMUtil.copyAttributes(targetElem, embeddedNode, null); targetElem.getParentNode().replaceChild(embeddedNode, targetElem); //create model for it this.container.createEmbeddedForm((Element) embeddedNode); // dispatch internal betterform event this.container.dispatch((EventTarget) embeddedNode, BetterFormEventNames.EMBED_DONE, map); if (getModel().isReady()) { map.put("uri", absoluteURI); map.put("show", this.showAttribute); map.put("targetElement", embeddedNode); map.put("nameTarget", evaluatedTarget); map.put("xlinkTarget", getXFormsAttribute(targetElem, "id")); map.put("inlineCSS", inlineCssRules); map.put("externalCSS", externalCssRules); map.put("inlineJavascript", inlineJavaScript); map.put("externalJavascript", externalJavaScript); map.put("utilizedEvents", utilizedEvents); this.container.dispatch((EventTarget) embeddedNode, BetterFormEventNames.EMBED, map); this.container.dispatch(this.target, BetterFormEventNames.LOAD_URI, map); } // storeInContext(absoluteURI, this.showAttribute); } else { String message = "Element reference for targetid: " + this.targetAttribute + " not found. " + DOMUtil.getCanonicalPath(this.element); /* Element div = this.element.getOwnerDocument().createElementNS("", "div"); div.setAttribute("class", "bfException"); div.setTextContent("Element reference for targetid: " + this.targetAttribute + "not found. " + DOMUtil.getCanonicalPath(this.element)); Element body = (Element) this.container.getDocument().getElementsByTagName("body").item(0); body.insertBefore(div, DOMUtil.getFirstChildElement(body)); */ map.put("message", message); map.put("exceptionPath", DOMUtil.getCanonicalPath(this.element)); this.container.dispatch(this.target, BetterFormEventNames.EXCEPTION, map); //throw new XFormsException(message); } }
From source file:de.betterform.xml.xforms.model.Model.java
private void createInstanceObject(Element xformsInstance) throws XFormsException { Instance instance = (Instance) this.container.getElementFactory().createXFormsElement(xformsInstance, this); instance.init();//from w w w. j av a2 s . com this.instances.add(instance); String debug = Config.getInstance().getProperty("betterform.debug-allowed"); if (debug != null && debug.equals("true")) { Map contextInfo = new HashMap(1); contextInfo.put("modelId", XFormsElement.getXFormsAttribute((Element) xformsInstance.getParentNode(), "id")); contextInfo.put("instanceId", XFormsElement.getXFormsAttribute(xformsInstance, "id")); this.container.dispatch(this.target, BetterFormEventNames.INSTANCE_CREATED, contextInfo); } }
From source file:org.alfresco.web.config.WebConfigRuntime.java
/** * @param properties/*from w w w . j av a 2 s . com*/ * @return */ public boolean syncAdvancedSearchOptions(HashMap<String, String> properties) { boolean status = false; String configType = properties.get("config"); if (configType != null) { // check if we have the config node for Advanced Search Element rootElement = (Element) webConfigDocument.getFirstChild(); Element advancedSearchConfigElem = XmlUtils.findFirstElement( "config[@evaluator='string-compare' and @condition='Advanced Search']", rootElement); if (advancedSearchConfigElem == null) { advancedSearchConfigElem = webConfigDocument.createElement("config"); advancedSearchConfigElem.setAttribute("evaluator", "string-compare"); advancedSearchConfigElem.setAttribute("condition", "Advanced Search"); appendChild(rootElement, advancedSearchConfigElem); status = true; } Element advancedSearchElem = XmlUtils.findFirstElement("advanced-search", advancedSearchConfigElem); if (advancedSearchElem == null) { advancedSearchElem = webConfigDocument.createElement("advanced-search"); appendChild(advancedSearchConfigElem, advancedSearchElem); status = true; } Element contentTypesElem = XmlUtils.findFirstElement("content-types", advancedSearchElem); if (contentTypesElem == null) { contentTypesElem = webConfigDocument.createElement("content-types"); appendChild(advancedSearchElem, contentTypesElem); status = true; } Element customPropertiesElem = XmlUtils.findFirstElement("custom-properties", advancedSearchElem); if (customPropertiesElem == null) { customPropertiesElem = webConfigDocument.createElement("custom-properties"); appendChild(advancedSearchElem, customPropertiesElem); status = true; } String typeName = properties.get("type"); String aspectName = properties.get("aspect"); String propertyName = properties.get("property"); String showOption = properties.get("show"); String displayLableId = properties.get("display-label-id"); if (configType.equals("type-property")) { if (typeName != null && propertyName != null && showOption != null) { Element typePropertyElem = XmlUtils.findFirstElement( "meta-data[type='" + typeName + "' and property='" + propertyName + "']", customPropertiesElem); if (typePropertyElem == null && showOption.equals("true")) { typePropertyElem = webConfigDocument.createElement("meta-data"); typePropertyElem.setAttribute("type", typeName); typePropertyElem.setAttribute("property", propertyName); if (displayLableId != null) { typePropertyElem.setAttribute("display-label-id", displayLableId); } appendChild(customPropertiesElem, typePropertyElem); status = true; } if (typePropertyElem != null && showOption.equals("false")) { typePropertyElem.getParentNode().removeChild(typePropertyElem); status = true; } } } if (configType.equals("aspect-property")) { if (aspectName != null && propertyName != null && showOption != null) { Element aspectPropertyElem = XmlUtils.findFirstElement( "meta-data[aspect='" + aspectName + "' and property='" + propertyName + "']", customPropertiesElem); if (aspectPropertyElem == null && showOption.equals("true")) { aspectPropertyElem = webConfigDocument.createElement("meta-data"); aspectPropertyElem.setAttribute("aspect", aspectName); aspectPropertyElem.setAttribute("property", propertyName); if (displayLableId != null) { aspectPropertyElem.setAttribute("display-label-id", displayLableId); } appendChild(customPropertiesElem, aspectPropertyElem); status = true; } if (aspectPropertyElem != null && showOption.equals("false")) { aspectPropertyElem.getParentNode().removeChild(aspectPropertyElem); status = true; } } } if (configType.equals("type")) { if (typeName != null && showOption != null) { Element typeElem = XmlUtils.findFirstElement("type[@name='" + typeName + "']", contentTypesElem); if (typeElem == null && showOption.equals("true")) { typeElem = webConfigDocument.createElement("type"); typeElem.setAttribute("name", typeName); if (displayLableId != null) { typeElem.setAttribute("display-label-id", displayLableId); } appendChild(contentTypesElem, typeElem); status = true; } if (typeElem != null && showOption.equals("false")) { typeElem.getParentNode().removeChild(typeElem); status = true; } } } if (configType.equals("aspect")) { if (aspectName != null && showOption != null) { Element aspectElem = XmlUtils.findFirstElement("aspect[@name='" + aspectName + "']", contentTypesElem); if (aspectElem == null && showOption.equals("true")) { aspectElem = webConfigDocument.createElement("aspect"); aspectElem.setAttribute("name", aspectName); if (displayLableId != null) { aspectElem.setAttribute("display-label-id", displayLableId); } appendChild(contentTypesElem, aspectElem); status = true; } if (aspectElem != null && showOption.equals("false")) { aspectElem.getParentNode().removeChild(aspectElem); status = true; } } } } return status; }
From source file:com.enonic.esl.xml.XMLTool.java
/** * <p/> A generic method that builds the xml block of arbitrary depth. All fields starting with a specified prefix and an '_' character * followed element names separated by '_' characters are translated to nested xml elements where the prefix names the top specified * with the root element. The last element can be specified with one of the following prefix and suffixes: <ul> <li>@ (prefix) - * element text will be set as an attribute to the parent element <li>_CDATA (suffix) - element text will be wrapped in a CDATA element * <li>_XHTML (suffix) - element text will be turned into XHTML elements </ul> When reaching one of the prefix and suffixes, the element * creating process will terminate for this field. </p> <p/> <p>Elements already created with the same path will be reused.</p> <p/> * <p>Example:<br> The key 'contentdata_foo_bar_zot_CDATA' with the value '<b>alpha</b>' will transform into the following xml: * <pre>/*from w w w . j a va 2s . c o m*/ * <contentdata> * <foo> * <bar> * <zot> * <[!CDATA[<b><b>alpha</b></b>]]> * </zot> * </bar> * </foo> * </contentdata> * </pre> * </p> */ public static void buildSubTree(Document doc, Element rootElement, String prefix, ExtendedMap items) throws XMLToolException { for (Object o : items.keySet()) { String key = (String) o; String[] values = items.getStringArray(key); StringTokenizer keyTokenizer = new StringTokenizer(key, "_"); if (prefix.equals(keyTokenizer.nextToken())) { Element tmpRoot = rootElement; while (keyTokenizer.hasMoreTokens()) { String keyToken = keyTokenizer.nextToken(); if ("CDATA".equals(keyToken)) { String data = values[0]; data = StringUtil.replaceAll(data, "\r\n", "\n"); createCDATASection(doc, tmpRoot, data); break; } else if ("XML".equals(keyToken)) { String xmlDoc = values[0]; Document tempDoc = domparse(xmlDoc); tmpRoot.appendChild(doc.importNode(tempDoc.getDocumentElement(), true)); break; } else if ("XHTML".equals(keyToken)) { createXHTMLNodes(doc, tmpRoot, values[0], true); break; } else if ("FILEITEM".equals(keyToken)) { FileItem fileItem = items.getFileItem(key); tmpRoot.setAttribute("field", fileItem.getFieldName()); } else if (keyToken.charAt(0) == '@') { if (values.length == 1) { tmpRoot.setAttribute(keyToken.substring(1), items.getString(key)); } else { Element parentElem = (Element) tmpRoot.getParentNode(); String elementName = tmpRoot.getTagName(); Element[] elements = getElements(parentElem, elementName); for (int i = 0; i < elements.length && i < values.length; i++) { elements[i].setAttribute(keyToken.substring(1), values[i]); } if (elements.length < values.length) { for (int i = elements.length; i < values.length; i++) { Element element = createElement(doc, parentElem, elementName); element.setAttribute(keyToken.substring(1), values[i]); } } } break; } else { if (!keyTokenizer.hasMoreTokens() && values.length > 1) { Element[] elements = getElements(tmpRoot, keyToken); for (int i = 0; i < elements.length && i < values.length; i++) { createTextNode(doc, elements[i], values[i]); } if (elements.length < values.length) { for (int i = elements.length; i < values.length; i++) { createElement(doc, tmpRoot, keyToken, values[i]); } } } else { Element elem = getElement(tmpRoot, keyToken); if (elem == null) { tmpRoot = createElement(doc, tmpRoot, keyToken); } else { tmpRoot = elem; } if (!keyTokenizer.hasMoreTokens()) { createTextNode(doc, tmpRoot, items.getString(key)); break; } } } } } } }
From source file:com.enonic.vertical.adminweb.handlers.xmlbuilders.SimpleContentXMLBuilder.java
public String getContentTitle(Element contentDataElem, int contentTypeKey) { Document ctDoc = XMLTool.domparse(admin.getContentType(contentTypeKey)); Element ctElem = XMLTool.getElement(ctDoc.getDocumentElement(), "contenttype"); Element moduleDataElem = XMLTool.getElement(ctElem, "moduledata"); Element moduleElem = XMLTool.getElement(moduleDataElem, "config"); // find title xpath Element formElem = XMLTool.getElement(moduleElem, "form"); Element titleElem = XMLTool.getElement(formElem, "title"); String titleFieldName = titleElem.getAttribute("name"); String titleXPath = null;/*from ww w. j av a2 s . c om*/ Node[] nodes = XMLTool.filterNodes(formElem.getChildNodes(), Node.ELEMENT_NODE); for (int i = 0; i < nodes.length && titleXPath == null; ++i) { Element elem = (Element) nodes[i]; if (elem.getTagName().equals("block")) { Node[] inputNodes = XMLTool.filterNodes(elem.getChildNodes(), Node.ELEMENT_NODE); for (Node inputNode : inputNodes) { if (titleFieldName.equals(((Element) inputNode).getAttribute("name"))) { titleXPath = XMLTool.getElementText(XMLTool.getElement((Element) inputNode, "xpath")); break; } } } } return XMLTool.getElementText((Element) contentDataElem.getParentNode(), titleXPath); }
From source file:org.gvnix.service.roo.addon.addon.ws.WSConfigServiceImpl.java
/** * {@inheritDoc}// w w w . ja va 2s. co m * <p> * Search the execution element using id defined in * CXF_WSDL2JAVA_EXECUTION_ID field. * </p> */ public void disableWsdlLocation() { // Get pom.xml String pomPath = getPomFilePath(); Validate.notNull(pomPath, POM_FILE_NOT_FOUND); // Get a mutable pom.xml reference to modify it MutableFile pomMutableFile = null; Document pom; try { pomMutableFile = getFileManager().updateFile(pomPath); pom = XmlUtils.getDocumentBuilder().parse(pomMutableFile.getInputStream()); } catch (Exception e) { throw new IllegalStateException(e); } Element root = pom.getDocumentElement(); // Get plugin element Element codegenWsPlugin = XmlUtils.findFirstElement( "/project/build/plugins/plugin[groupId='org.apache.cxf' and artifactId='cxf-codegen-plugin']", root); // If plugin element not exists, message error Validate.notNull(codegenWsPlugin, "Codegen plugin is not defined in the pom.xml, relaunch again this command."); // Checks if already exists the execution. Element oldGenerateSourcesCxfServer = XmlUtils.findFirstElement( "/project/build/plugins/plugin/executions/execution[id='" + CXF_WSDL2JAVA_EXECUTION_ID + "']", root); if (oldGenerateSourcesCxfServer != null) { Element executionPhase = DomUtils.findFirstElementByName(PHASE2, oldGenerateSourcesCxfServer); if (executionPhase != null) { Element newPhase = pom.createElement(PHASE2); newPhase.setTextContent("none"); // Remove existing wsdlOption. executionPhase.getParentNode().replaceChild(newPhase, executionPhase); // Write new XML to disk. XmlUtils.writeXml(pomMutableFile.getOutputStream(), pom); } } }
From source file:org.gvnix.service.roo.addon.addon.ws.WSConfigServiceImpl.java
/** * {@inheritDoc}/* w w w. ja v a 2 s . co m*/ */ public void addToJava2wsPlugin(JavaType serviceClass, String serviceName, String addressName, String fullyQualifiedTypeName) { // Get pom String pomPath = getPomFilePath(); Validate.isTrue(pomPath != null, "Cxf configuration file not found, export again the service."); MutableFile pomMutableFile = getFileManager().updateFile(pomPath); Document pom = getInputDocument(pomMutableFile.getInputStream()); Element root = pom.getDocumentElement(); // Gets java2ws plugin element Element jaxWsPlugin = XmlUtils.findFirstElement( "/project/build/plugins/plugin[groupId='org.apache.cxf' and artifactId='cxf-java2ws-plugin']", root); // Install it if it's missing if (jaxWsPlugin == null) { logger.log(Level.INFO, "Jax-Ws plugin is not defined in the pom.xml. Installing in project."); // Installs jax2ws plugin. addPlugin(); } // Checks if already exists the execution. Element serviceExecution = XmlUtils .findFirstElement("/project/build/plugins/plugin/executions/execution/configuration[className='" .concat(serviceClass.getFullyQualifiedTypeName()).concat("']"), root); if (serviceExecution != null) { logger.log(Level.FINE, "A previous Wsdl generation with CXF plugin for '".concat(serviceName) .concat("' service has been found.")); return; } // Checks if name of java class has been changed comparing current // service class and name declared in annotation boolean classNameChanged = false; if (!serviceClass.getFullyQualifiedTypeName().contentEquals(fullyQualifiedTypeName)) { classNameChanged = true; } // if class has been changed (package or name) update execution if (classNameChanged) { serviceExecution = XmlUtils .findFirstElement("/project/build/plugins/plugin/executions/execution/configuration[className='" .concat(fullyQualifiedTypeName).concat("']"), root); // Update with serviceClass.getFullyQualifiedTypeName(). if (serviceExecution != null && serviceExecution.hasChildNodes()) { Node updateServiceExecution; updateServiceExecution = (serviceExecution.getFirstChild() != null) ? serviceExecution.getFirstChild().getNextSibling() : null; // Find node which contains old class name while (updateServiceExecution != null) { if (updateServiceExecution.getNodeName().contentEquals("className")) { // Update node content with new value updateServiceExecution.setTextContent(serviceClass.getFullyQualifiedTypeName()); // write pom XmlUtils.writeXml(pomMutableFile.getOutputStream(), pom); logger.log(Level.INFO, "Wsdl generation with CXF plugin for '" + serviceName + " service, updated className attribute for '" + serviceClass.getFullyQualifiedTypeName() + "'."); // That's all return; } // Check next node. updateServiceExecution = updateServiceExecution.getNextSibling(); } } } // Prepare Execution configuration String executionID = "${project.basedir}/src/test/resources/generated/wsdl/".concat(addressName) .concat(".wsdl"); serviceExecution = createJava2wsExecutionElement(pom, serviceClass, addressName, executionID); // Checks if already exists the execution. // XXX ??? this is hard difficult because previously it's already // checked // using class name Element oldExecution = XmlUtils.findFirstElement( "/project/build/plugins/plugin/executions/execution[id='" + executionID + "']", root); if (oldExecution != null) { logger.log(Level.FINE, "Wsdl generation with CXF plugin for '" + serviceName + " service, has been configured before."); return; } // Checks if already exists the executions to update or create. Element oldExecutions = DomUtils.findFirstElementByName(EXECUTIONS, jaxWsPlugin); Element newExecutions; // To Update execution definitions It must be replaced in pom.xml to // maintain the format. if (oldExecutions != null) { newExecutions = oldExecutions; newExecutions.appendChild(serviceExecution); oldExecutions.getParentNode().replaceChild(oldExecutions, newExecutions); } else { newExecutions = pom.createElement(EXECUTIONS); newExecutions.appendChild(serviceExecution); jaxWsPlugin.appendChild(newExecutions); } XmlUtils.writeXml(pomMutableFile.getOutputStream(), pom); }