List of usage examples for org.dom4j Element remove
boolean remove(Text text);
Text
if the node is an immediate child of this element. From source file:nl.tue.gale.ae.processor.xmlmodule.MCModule.java
License:Open Source License
public Element traverse(Element element, Resource resource) throws ProcessorException { try {/*from ww w. ja va 2 s .c o m*/ GaleContext gale = GaleContext.of(resource); Element resultElement = element.element("result"); if (resultElement != null) element.remove(resultElement); processor.traverseChildren(element, resource); if (resultElement != null) element.add(resultElement); Test test = readTest(element); boolean eval = (Boolean) gale.eval(test.expr); if (!eval) { GaleUtil.replaceNode(element, DocumentFactory.getInstance().createText((test.alt == null ? "" : test.alt))); return null; } test.create(); String guid = GaleUtil.newGUID(); gale.req().getSession().setAttribute(guid, test); String url = GaleUtil.getRequestURL(gale.req()); UrlEncodedQueryString qs = UrlEncodedQueryString.parse(URIs.of(url)); if ("true".equals(qs.get("frame"))) { qs.remove("frame"); qs.append("framewait", "true"); } qs.append("plugin", plugin); qs.append("guid", guid); url = qs.apply(URIs.of(url)).toString(); Node n = resource.getTyped(Node.class, "nl.tue.gale.ae.processor.xmlmodule.AdaptLinkModule.content"); Element result = test.toXHTML(url, n); return (Element) GaleUtil.replaceNode(element, result); } catch (Exception e) { e.printStackTrace(); return (Element) GaleUtil.replaceNode(element, GaleUtil.createErrorElement("[" + e.getMessage() + "]")); } }
From source file:org.apache.maven.archetype.common.DefaultPomManager.java
License:Apache License
public void addModule(File pom, String artifactId) throws IOException, XmlPullParserException, DocumentException, InvalidPackaging { boolean found = false; StringWriter writer = new StringWriter(); Reader fileReader = null;/*from ww w . ja va 2 s . c om*/ try { fileReader = ReaderFactory.newXmlReader(pom); SAXReader reader = new SAXReader(); Document document = reader.read(fileReader); Element project = document.getRootElement(); String packaging = null; Element packagingElement = project.element("packaging"); if (packagingElement != null) { packaging = packagingElement.getStringValue(); } if (!"pom".equals(packaging)) { throw new InvalidPackaging( "Unable to add module to the current project as it is not of packaging type 'pom'"); } Element modules = project.element("modules"); if (modules == null) { modules = project.addText(" ").addElement("modules"); modules.setText("\n "); project.addText("\n"); } // TODO: change to while loop for (@SuppressWarnings("unchecked") Iterator<Element> i = modules.elementIterator("module"); i.hasNext() && !found;) { Element module = i.next(); if (module.getText().equals(artifactId)) { found = true; } } if (!found) { Node lastTextNode = null; for (@SuppressWarnings("unchecked") Iterator<Node> i = modules.nodeIterator(); i.hasNext();) { Node node = i.next(); if (node.getNodeType() == Node.ELEMENT_NODE) { lastTextNode = null; } else if (node.getNodeType() == Node.TEXT_NODE) { lastTextNode = node; } } if (lastTextNode != null) { modules.remove(lastTextNode); } modules.addText("\n "); modules.addElement("module").setText(artifactId); modules.addText("\n "); XMLWriter xmlWriter = new XMLWriter(writer); xmlWriter.write(document); FileUtils.fileWrite(pom.getAbsolutePath(), writer.toString()); } // end if } finally { IOUtil.close(fileReader); } }
From source file:org.apache.maven.archetype.old.DefaultOldArchetype.java
License:Apache License
static boolean addModuleToParentPom(String artifactId, Reader fileReader, Writer fileWriter) throws DocumentException, IOException, ArchetypeTemplateProcessingException { SAXReader reader = new SAXReader(); Document document = reader.read(fileReader); Element project = document.getRootElement(); String packaging = null;// w w w . j a v a2 s. c o m Element packagingElement = project.element("packaging"); if (packagingElement != null) { packaging = packagingElement.getStringValue(); } if (!"pom".equals(packaging)) { throw new ArchetypeTemplateProcessingException( "Unable to add module to the current project as it is not of packaging type 'pom'"); } Element modules = project.element("modules"); if (modules == null) { modules = project.addText(" ").addElement("modules"); modules.setText("\n "); project.addText("\n"); } boolean found = false; for (Iterator<?> i = modules.elementIterator("module"); i.hasNext() && !found;) { Element module = (Element) i.next(); if (module.getText().equals(artifactId)) { found = true; } } if (!found) { Node lastTextNode = null; for (Iterator<?> i = modules.nodeIterator(); i.hasNext();) { Node node = (Node) i.next(); if (node.getNodeType() == Node.ELEMENT_NODE) { lastTextNode = null; } else if (node.getNodeType() == Node.TEXT_NODE) { lastTextNode = node; } } if (lastTextNode != null) { modules.remove(lastTextNode); } modules.addText("\n "); modules.addElement("module").setText(artifactId); modules.addText("\n "); XMLWriter writer = new XMLWriter(fileWriter); writer.write(document); } return !found; }
From source file:org.apache.maven.plugin.idea.AbstractIdeaMojo.java
License:Apache License
/** * Remove elements from content (Xpp3Dom). * * @param content Xpp3Dom element// w ww.java 2 s . c o m * @param name Name of the element to be removed */ protected void removeOldElements(Element content, String name) { for (Iterator children = content.elementIterator(); children.hasNext();) { Element child = (Element) children.next(); if (name.equals(child.getName())) { content.remove(child); } } }
From source file:org.apache.maven.plugin.idea.IdeaModuleMojo.java
License:Apache License
public void rewriteModule() throws MojoExecutionException { File moduleFile = new File(executedProject.getBasedir(), executedProject.getArtifactId() + ".iml"); try {/*from w ww . j a v a2 s . c o m*/ Document document = readXmlDocument(moduleFile, "module.xml"); Element module = document.getRootElement(); // TODO: how can we let the WAR/EJBs plugin hook in and provide this? // TODO: merge in ejb-module, etc. if ("war".equals(executedProject.getPackaging())) { addWebModule(module); } else if ("ejb".equals(executedProject.getPackaging())) { addEjbModule(module); } else if ("ear".equals(executedProject.getPackaging())) { addEarModule(module); } else if (ideaPlugin) { addPluginModule(module); } Element component = findComponent(module, "NewModuleRootManager"); Element output = findElement(component, "output"); output.addAttribute("url", getModuleFileUrl(executedProject.getBuild().getOutputDirectory())); Element outputTest = findElement(component, "output-test"); outputTest.addAttribute("url", getModuleFileUrl(executedProject.getBuild().getTestOutputDirectory())); Element content = findElement(component, "content"); removeOldElements(content, "sourceFolder"); for (Iterator i = executedProject.getCompileSourceRoots().iterator(); i.hasNext();) { String directory = (String) i.next(); addSourceFolder(content, directory, false); } for (Iterator i = executedProject.getTestCompileSourceRoots().iterator(); i.hasNext();) { String directory = (String) i.next(); addSourceFolder(content, directory, true); } for (Iterator i = executedProject.getBuild().getResources().iterator(); i.hasNext();) { Resource resource = (Resource) i.next(); String directory = resource.getDirectory(); if (resource.getTargetPath() == null && !resource.isFiltering()) { addSourceFolder(content, directory, false); } else { getLog().info( "Not adding resource directory as it has an incompatible target path or filtering: " + directory); } } for (Iterator i = executedProject.getBuild().getTestResources().iterator(); i.hasNext();) { Resource resource = (Resource) i.next(); String directory = resource.getDirectory(); if (resource.getTargetPath() == null && !resource.isFiltering()) { addSourceFolder(content, directory, true); } else { getLog().info( "Not adding test resource directory as it has an incompatible target path or filtering: " + directory); } } removeOldElements(content, "excludeFolder"); //For excludeFolder File target = new File(executedProject.getBuild().getDirectory()); File classes = new File(executedProject.getBuild().getOutputDirectory()); File testClasses = new File(executedProject.getBuild().getTestOutputDirectory()); List sourceFolders = content.elements("sourceFolder"); List filteredExcludes = new ArrayList(); filteredExcludes.addAll(getExcludedDirectories(target, filteredExcludes, sourceFolders)); filteredExcludes.addAll(getExcludedDirectories(classes, filteredExcludes, sourceFolders)); filteredExcludes.addAll(getExcludedDirectories(testClasses, filteredExcludes, sourceFolders)); if (exclude != null) { String[] dirs = exclude.split("[,\\s]+"); for (int i = 0; i < dirs.length; i++) { File excludedDir = new File(executedProject.getBasedir(), dirs[i]); filteredExcludes.addAll(getExcludedDirectories(excludedDir, filteredExcludes, sourceFolders)); } } // even though we just ran all the directories in the filteredExcludes List through the intelligent // getExcludedDirectories method, we never actually were guaranteed the order that they were added was // in the order required to make the most optimized exclude list. In addition, the smart logic from // that method is entirely skipped if the directory doesn't currently exist. A simple string matching // will do pretty much the same thing and make the list more concise. ArrayList actuallyExcluded = new ArrayList(); Collections.sort(filteredExcludes); for (Iterator i = filteredExcludes.iterator(); i.hasNext();) { String dirToExclude = i.next().toString(); String dirToExcludeTemp = dirToExclude.replace('\\', '/'); boolean addExclude = true; for (Iterator iterator = actuallyExcluded.iterator(); iterator.hasNext();) { String dir = iterator.next().toString(); String dirTemp = dir.replace('\\', '/'); if (dirToExcludeTemp.startsWith(dirTemp + "/")) { addExclude = false; break; } else if (dir.startsWith(dirToExcludeTemp + "/")) { actuallyExcluded.remove(dir); } } if (addExclude) { actuallyExcluded.add(dirToExclude); addExcludeFolder(content, dirToExclude); } } //Remove default exclusion for output dirs if there are sources in it String outputModuleUrl = getModuleFileUrl(executedProject.getBuild().getOutputDirectory()); String testOutputModuleUrl = getModuleFileUrl(executedProject.getBuild().getTestOutputDirectory()); for (Iterator i = content.elements("sourceFolder").iterator(); i.hasNext();) { Element sourceFolder = (Element) i.next(); String sourceUrl = sourceFolder.attributeValue("url").replace('\\', '/'); if (sourceUrl.startsWith(outputModuleUrl + "/") || sourceUrl.startsWith(testOutputModuleUrl)) { component.remove(component.element("exclude-output")); break; } } rewriteDependencies(component); writeXmlDocument(moduleFile, document); } catch (DocumentException e) { throw new MojoExecutionException("Error parsing existing IML file " + moduleFile.getAbsolutePath(), e); } catch (IOException e) { throw new MojoExecutionException("Error parsing existing IML file " + moduleFile.getAbsolutePath(), e); } }
From source file:org.apache.maven.plugin.idea.IdeaModuleMojo.java
License:Apache License
private void rewriteDependencies(Element component) { Map modulesByName = new HashMap(); Map modulesByUrl = new HashMap(); Set unusedModules = new HashSet(); for (Iterator children = component.elementIterator("orderEntry"); children.hasNext();) { Element orderEntry = (Element) children.next(); String type = orderEntry.attributeValue("type"); if ("module".equals(type)) { modulesByName.put(orderEntry.attributeValue("module-name"), orderEntry); } else if ("module-library".equals(type)) { // keep track for later so we know what is left unusedModules.add(orderEntry); Element lib = orderEntry.element("library"); String name = lib.attributeValue("name"); if (name != null) { modulesByName.put(name, orderEntry); } else { Element classesChild = lib.element("CLASSES"); if (classesChild != null) { Element rootChild = classesChild.element("root"); if (rootChild != null) { String url = rootChild.attributeValue("url"); if (url != null) { // Need to ignore case because of Windows drive letters modulesByUrl.put(url.toLowerCase(), orderEntry); }//from w w w . j av a2 s . c om } } } } } List testClasspathElements = executedProject.getTestArtifacts(); for (Iterator i = testClasspathElements.iterator(); i.hasNext();) { Artifact a = (Artifact) i.next(); Library library = findLibrary(a); if (library != null && library.isExclude()) { continue; } String moduleName; if (useFullNames) { moduleName = a.getGroupId() + ':' + a.getArtifactId() + ':' + a.getType() + ':' + a.getVersion(); } else { moduleName = a.getArtifactId(); } Element dep = (Element) modulesByName.get(moduleName); if (dep == null) { // Need to ignore case because of Windows drive letters dep = (Element) modulesByUrl.get(getLibraryUrl(a).toLowerCase()); } if (dep != null) { unusedModules.remove(dep); } else { dep = createElement(component, "orderEntry"); } boolean isIdeaModule = false; if (linkModules) { isIdeaModule = isReactorProject(a.getGroupId(), a.getArtifactId()); if (isIdeaModule) { dep.addAttribute("type", "module"); dep.addAttribute("module-name", moduleName); } } if (a.getFile() != null && !isIdeaModule) { dep.addAttribute("type", "module-library"); Element lib = dep.element("library"); if (lib == null) { lib = createElement(dep, "library"); } if (dependenciesAsLibraries) { lib.addAttribute("name", moduleName); } // replace classes removeOldElements(lib, "CLASSES"); Element classes = createElement(lib, "CLASSES"); if (library != null && library.getSplitClasses().length > 0) { lib.addAttribute("name", moduleName); String[] libraryClasses = library.getSplitClasses(); for (int k = 0; k < libraryClasses.length; k++) { String classpath = libraryClasses[k]; extractMacro(classpath); Element classEl = createElement(classes, "root"); classEl.addAttribute("url", classpath); } } else { createElement(classes, "root").addAttribute("url", getLibraryUrl(a)); } if (library != null && library.getSplitSources().length > 0) { removeOldElements(lib, "SOURCES"); Element sourcesElement = createElement(lib, "SOURCES"); String[] sources = library.getSplitSources(); for (int k = 0; k < sources.length; k++) { String source = sources[k]; extractMacro(source); Element sourceEl = createElement(sourcesElement, "root"); sourceEl.addAttribute("url", source); } } else if (downloadSources) { resolveClassifier(createOrGetElement(lib, "SOURCES"), a, sourceClassifier); } if (library != null && library.getSplitJavadocs().length > 0) { removeOldElements(lib, "JAVADOC"); Element javadocsElement = createElement(lib, "JAVADOC"); String[] javadocs = library.getSplitJavadocs(); for (int k = 0; k < javadocs.length; k++) { String javadoc = javadocs[k]; extractMacro(javadoc); Element sourceEl = createElement(javadocsElement, "root"); sourceEl.addAttribute("url", javadoc); } } else if (downloadJavadocs) { resolveClassifier(createOrGetElement(lib, "JAVADOC"), a, javadocClassifier); } } } for (Iterator i = unusedModules.iterator(); i.hasNext();) { Element orderEntry = (Element) i.next(); component.remove(orderEntry); } }
From source file:org.axonframework.eventstore.legacy.LegacyAxonEventUpcaster.java
License:Apache License
@SuppressWarnings({ "unchecked" }) @Override/*from ww w . ja va 2 s. c o m*/ public Document upcast(Document event) { Element rootNode = event.getRootElement(); if (rootNode.attribute("eventRevision") == null) { rootNode.addAttribute("eventRevision", "0"); Element metaData = rootNode.addElement("metaData").addElement("values"); Iterator<Element> children = rootNode.elementIterator(); while (children.hasNext()) { Element childNode = children.next(); String childName = childNode.getName(); if ("eventIdentifier".equals(childName)) { addMetaDataEntry(metaData, "_identifier", childNode.getTextTrim(), "uuid"); rootNode.remove(childNode); } else if ("timestamp".equals(childName)) { addMetaDataEntry(metaData, "_timestamp", childNode.getTextTrim(), "localDateTime"); rootNode.remove(childNode); } } } return event; }
From source file:org.axonframework.migration.eventstore.LegacyAxonEventUpcaster.java
License:Apache License
@SuppressWarnings({ "unchecked" }) @Override//from www . ja va 2 s . com public IntermediateRepresentation upcast(IntermediateRepresentation event) { Element rootNode = ((Document) event.getContents()).getRootElement(); if (rootNode.attribute("eventRevision") == null) { rootNode.addAttribute("eventRevision", "0"); Element metaData = rootNode.addElement("metaData").addElement("values"); Iterator<Element> children = rootNode.elementIterator(); while (children.hasNext()) { Element childNode = children.next(); String childName = childNode.getName(); if ("eventIdentifier".equals(childName)) { addMetaDataEntry(metaData, "_identifier", childNode.getTextTrim(), "uuid"); rootNode.remove(childNode); } else if ("timestamp".equals(childName)) { addMetaDataEntry(metaData, "_timestamp", childNode.getTextTrim(), "localDateTime"); rootNode.remove(childNode); } } } Document document = new DefaultDocument(); Element newRoot = document.addElement("domain-event"); Element payload = newRoot.addElement("payload"); String objectType = rootNode.getName().replaceAll("\\_\\-", "\\$"); payload.addAttribute("class", objectType); Set<String> forbiddenPayloadElements = new HashSet<String>( Arrays.asList("metaData", "aggregateIdentifier", "sequenceNumber", "timestamp")); for (Object node : rootNode.elements()) { Element element = (Element) node; if (!forbiddenPayloadElements.contains(element.getName())) { payload.add(element.createCopy()); } else { newRoot.add(element.createCopy()); } } newRoot.addElement("timestamp").addText(extractMetaDataValue(newRoot, "_timestamp")); newRoot.addElement("eventIdentifier").addText(extractMetaDataValue(newRoot, "_identifier")); String eventRevision = rootNode.attribute("eventRevision").getValue(); payload.addAttribute("eventRevision", eventRevision); return new Dom4jRepresentation(document, DomainEventMessage.class.getName(), Integer.parseInt(eventRevision)); }
From source file:org.b5chat.crossfire.core.property.XMLProperties.java
License:Open Source License
/** * Sets a property to an array of values. Multiple values matching the same property * is mapped to an XML file as multiple elements containing each value. * For example, using the name "foo.bar.prop", and the value string array containing * {"some value", "other value", "last value"} would produce the following XML: * <pre>//w w w . j a v a 2s.c om * <foo> * <bar> * <prop>some value</prop> * <prop>other value</prop> * <prop>last value</prop> * </bar> * </foo> * </pre> * * @param name the name of the property. * @param values the values for the property (can be empty but not null). */ public void setProperties(String name, List<String> values) { String[] propName = parsePropertyName(name); // Search for this property by traversing down the XML heirarchy, // stopping one short. Element element = document.getRootElement(); for (int i = 0; i < propName.length - 1; i++) { // If we don't find this part of the property in the XML heirarchy // we add it as a new node if (element.element(propName[i]) == null) { element.addElement(propName[i]); } element = element.element(propName[i]); } String childName = propName[propName.length - 1]; // We found matching property, clear all children. List<Element> toRemove = new ArrayList<Element>(); @SuppressWarnings("unchecked") Iterator<Element> iter = element.elementIterator(childName); while (iter.hasNext()) { toRemove.add(iter.next()); } for (iter = toRemove.iterator(); iter.hasNext();) { element.remove(iter.next()); } // Add the new children. for (String value : values) { Element childElement = element.addElement(childName); if (value.startsWith("<![CDATA[")) { @SuppressWarnings("unchecked") Iterator<Node> it = childElement.nodeIterator(); while (it.hasNext()) { Node node = it.next(); if (node instanceof CDATA) { childElement.remove(node); break; } } childElement.addCDATA(value.substring(9, value.length() - 3)); } else { childElement.setText(StringEscapeUtils.escapeXml(value)); } } saveProperties(); // Generate event. Map<String, Object> params = new HashMap<String, Object>(); params.put("value", values); PropertyEventDispatcher.dispatchEvent(name, PropertyEventDispatcher.EventType.xml_property_set, params); }
From source file:org.b5chat.crossfire.core.property.XMLProperties.java
License:Open Source License
/** * Sets the value of the specified property. If the property doesn't * currently exist, it will be automatically created. * * @param name the name of the property to set. * @param value the new value for the property. *///from w w w.j a v a 2s. c o m public synchronized void setProperty(String name, String value) { if (!StringEscapeUtils.escapeXml(name).equals(name)) { throw new IllegalArgumentException("Property name cannot contain XML entities."); } if (name == null) { return; } if (value == null) { value = ""; } // Set cache correctly with prop name and value. propertyCache.put(name, value); String[] propName = parsePropertyName(name); // Search for this property by traversing down the XML heirarchy. Element element = document.getRootElement(); for (String aPropName : propName) { // If we don't find this part of the property in the XML heirarchy // we add it as a new node if (element.element(aPropName) == null) { element.addElement(aPropName); } element = element.element(aPropName); } // Set the value of the property in this node. if (value.startsWith("<![CDATA[")) { @SuppressWarnings("unchecked") Iterator<Node> it = element.nodeIterator(); while (it.hasNext()) { Node node = it.next(); if (node instanceof CDATA) { element.remove(node); break; } } element.addCDATA(value.substring(9, value.length() - 3)); } else { element.setText(value); } // Write the XML properties to disk saveProperties(); // Generate event. Map<String, Object> params = new HashMap<String, Object>(); params.put("value", value); PropertyEventDispatcher.dispatchEvent(name, PropertyEventDispatcher.EventType.xml_property_set, params); }