List of usage examples for org.jdom2 Element getParentElement
final public Element getParentElement()
From source file:org.kdp.word.transformer.StyleTransformer.java
License:Apache License
@Override public void transform(Context context) { Parser parser = context.getParser(); Options options = context.getOptions(); Path cssPath = options.getExternalCSS(); if (cssPath == null) return;/*from w w w .j a v a 2 s. c o m*/ // Parse the external styles replacements = parseStyleReplacements(context); parseExternalStyles(context, cssPath); String wltoks = parser.getProperty(Parser.PROPERTY_STYLE_REPLACE_WHITELIST); if (wltoks != null) { for (String tok : wltoks.split(",")) { whitelist.add(tok.trim()); } } // Remove existing style definitions Element root = context.getSourceRoot(); Element elStyle = JDOMUtils.findElement(root, "style"); if (elStyle != null) { elStyle.getParentElement().removeContent(elStyle); } // Copy the CSS to the book dir Path cssName = cssPath.getFileName(); try { Path bookDir = options.getBookDir(); Path cssBook = bookDir.resolve(cssName); bookDir.toFile().mkdirs(); Files.copy(cssPath, cssBook, StandardCopyOption.REPLACE_EXISTING); } catch (IOException ex) { throw new IllegalStateException(ex); } // Add reference to external styles Element elHead = JDOMUtils.findElement(root, "head"); if (elHead != null) { JDOMFactory factory = context.getJDOMFactory(); Element elLink = factory.element("link"); elLink.setAttribute("rel", "stylesheet"); elLink.setAttribute("type", "text/css"); elLink.setAttribute("href", cssName.toString()); elHead.addContent(elLink); transformStyles(context, root); } }
From source file:org.kdp.word.transformer.TOCTransformer.java
License:Apache License
@Override public void transform(Context context) { JDOMFactory factory = context.getJDOMFactory(); Element root = context.getSourceRoot(); for (Element el : root.getChildren()) { transformInternal(context, el);//from w w w. j a v a 2s. c om } Element first = JDOMUtils.findElement(root, "p", "class", "MsoToc1"); if (first != null) { Element parent = first.getParentElement(); List<Element> children = parent.getChildren(); // Add the nav element Element nav = factory.element("nav"); nav.getAttributes().add(factory.attribute("type", "toc", OPFTransformer.NS_OPF)); int index = children.indexOf(first); children.add(index, nav); // Add the ol element Element ol = factory.element("ol"); ol.setAttribute("class", "Toc"); nav.getChildren().add(ol); Iterator<Element> itel = children.iterator(); while (itel.hasNext()) { Element el = itel.next(); if (JDOMUtils.isElement(el, "p", "class", "MsoToc1")) { Element li = factory.element("li"); li.getAttributes().add(factory.attribute("class", "MsoToc1")); li.addContent(el.cloneContent()); ol.getChildren().add(li); itel.remove(); } } } }
From source file:org.kisst.cordys.caas.util.XmlNode.java
License:Open Source License
public Object get(String path) { String[] parts = path.split("/"); Element e = element; for (String part : parts) { if (part.equals("..")) e = e.getParentElement(); else if (part.equals("text()")) return e.getText(); else if (part.startsWith("@")) return e.getAttribute(part.substring(1)).getValue(); else//w w w . ja v a 2 s . co m e = e.getChild(part, null); if (e == null) return null; } return new XmlNode(e); }
From source file:org.kisst.cordys.caas.util.XmlNode.java
License:Open Source License
public Object getWithCreate(String path) { String[] parts = path.split("/"); Element e = element; for (String part : parts) { if (part.equals("..")) e = e.getParentElement(); else if (part.equals("text()")) return e.getText(); else if (part.startsWith("@")) return e.getAttribute(part.substring(1)).getValue(); else {/* w w w . j a v a 2s . c om*/ Element child = e.getChild(part, null); if (child == null) { child = new Element(part, e.getNamespace()); e.addContent(child); } e = child; } } return new XmlNode(e); }
From source file:org.mule.tools.apikit.input.parsers.APIKitRoutersParser.java
License:Open Source License
@Override public Map<String, API> parse(Document document) { Map<String, API> includedApis = new HashMap<String, API>(); XPathExpression<Element> xp = XPathFactory.instance().compile("//*/*[local-name()='router']", Filters.element(APIKitTools.API_KIT_NAMESPACE.getNamespace())); List<Element> elements = xp.evaluate(document); for (Element element : elements) { Attribute configRef = element.getAttribute("config-ref"); String configId = configRef != null ? configRef.getValue() : APIKitFlow.UNNAMED_CONFIG_NAME; APIKitConfig config = apikitConfigs.get(configId); if (config == null) { throw new IllegalStateException("An Apikit configuration is mandatory."); }/*from w ww .j a v a 2 s. c o m*/ for (File yamlPath : yamlPaths) { if (yamlPath.getName().equals(config.getRaml())) { Element listener = element.getParentElement().getChildren().get(0); Attribute httpListenerConfigRef = listener.getAttribute("config-ref"); String httpListenerConfigId = httpListenerConfigRef != null ? httpListenerConfigRef.getValue() : HttpListenerConfig.DEFAULT_CONFIG_NAME; HttpListenerConfig httpListenerConfig = httpListenerConfigs.get(httpListenerConfigId); if (httpListenerConfig == null) { throw new IllegalStateException("An HTTP Listener configuration is mandatory."); } // TODO Unhack, it is assuming that the router will always be in a flow // where the first element is going to be an http listener if (!"listener".equals(listener.getName())) { throw new IllegalStateException("The first element of the main flow must be a listener"); } String path = getPathFromListener(listener); includedApis.put(configId, apiFactory.createAPIBinding(yamlPath, file, config, httpListenerConfig, path)); } } } return includedApis; }
From source file:org.mycore.frontend.editor.MCREditorDefReader.java
License:Open Source License
/** * Recursively removes include elements that are direct or indirect children * of the given container element and replaces them with the included * resource. Includes that may be contained in included resources are * recursively resolved, too./* w w w . ja v a 2 s. c o m*/ * * @param element * The element where to start resolving includes */ private boolean resolveIncludes(Element element) { boolean replaced = false; String ref = element.getAttributeValue("ref", ""); ref = tokenSubstitutor.substituteTokens(ref); if (element.getName().equals("include")) { String uri = element.getAttributeValue("uri"); if (uri != null) { uri = tokenSubstitutor.substituteTokens(uri); LOGGER.info("Including " + uri + (ref.length() > 0 ? "#" + ref : "")); Element parent = element.getParentElement(); int pos = parent.indexOf(element); Element container = MCRURIResolver.instance().resolve(uri); List<Content> found; if (ref.length() == 0) { found = container.cloneContent(); } else { found = findContent(container, ref); ref = ""; } replaced = true; parent.addContent(pos, found); element.detach(); } } else { String id = element.getAttributeValue("id", ""); if (id.length() > 0) { id2component.put(id, element); } setDefaultAttributes(element); resolveChildren(element); } if (ref.length() > 0) { referencing2ref.put(element, ref); } return replaced; }
From source file:org.mycore.frontend.editor.MCREditorDefReader.java
License:Open Source License
/** * Recursively resolves references by the @ref attribute and * replaces them with the referenced component. *//* w w w.ja va2 s.c o m*/ private void resolveReferences() { for (Iterator<Element> it = referencing2ref.keySet().iterator(); it.hasNext();) { Element referencing = it.next(); String id = referencing2ref.get(referencing); LOGGER.debug("Resolving reference to " + id); Element found = id2component.get(id); if (found == null) { String msg = "Reference to component " + id + " could not be resolved"; throw new MCRConfigurationException(msg); } String name = referencing.getName(); referencing.removeAttribute("ref"); it.remove(); if (name.equals("cell") || name.equals("repeater")) { if (found.getParentElement().getName().equals("components")) { referencing.addContent(0, found.detach()); } else { referencing.addContent(0, (Element) found.clone()); } } else if (name.equals("panel")) { if (referencing2ref.containsValue(id)) { referencing.addContent(0, found.cloneContent()); } else { found.detach(); List<Content> content = found.getContent(); for (int i = 0; !content.isEmpty(); i++) { Content child = content.remove(0); referencing.addContent(i, child); } } } else if (name.equals("include")) { Element parent = referencing.getParentElement(); int pos = parent.indexOf(referencing); referencing.detach(); if (referencing2ref.containsValue(id)) { parent.addContent(pos, found.cloneContent()); } else { found.detach(); List<Content> content = found.getContent(); for (int i = pos; !content.isEmpty(); i++) { Content child = content.remove(0); parent.addContent(i, child); } } } } Element components = editor.getChild("components"); String root = components.getAttributeValue("root"); for (int i = 0; i < components.getContentSize(); i++) { Content child = components.getContent(i); if (!(child instanceof Element)) { continue; } if (((Element) child).getName().equals("headline")) { continue; } if (!root.equals(((Element) child).getAttributeValue("id"))) { components.removeContent(i--); } } }
From source file:org.mycore.frontend.xeditor.MCRBinding.java
License:Open Source License
public Element cloneBoundElement(int index) { Element template = (Element) (boundNodes.get(index)); Element newElement = template.clone(); Element parent = template.getParentElement(); int indexInParent = parent.indexOf(template) + 1; parent.addContent(indexInParent, newElement); boundNodes.add(index + 1, newElement); trackNodeCreated(newElement);//from w w w . j av a2s . c om return newElement; }
From source file:org.mycore.restapi.v1.MCRRestAPIClassifications.java
License:Open Source License
/** * Output xml//from w w w . ja v a 2 s. c o m * @param eRoot - the root element * @param lang - the language which should be filtered or null for no filter * @return a string representation of the XML * @throws IOException */ private static String writeXML(Element eRoot, String lang) throws IOException { StringWriter sw = new StringWriter(); if (lang != null) { // <label xml:lang="en" text="part" /> XPathExpression<Element> xpE = XPathFactory.instance().compile("//label[@xml:lang!='" + lang + "']", Filters.element(), null, Namespace.XML_NAMESPACE); for (Element e : xpE.evaluate(eRoot)) { e.getParentElement().removeContent(e); } } XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat()); Document docOut = new Document(eRoot.detach()); xout.output(docOut, sw); return sw.toString(); }
From source file:org.openflexo.foundation.fml.rm.ViewPointResourceImpl.java
License:Open Source License
private static void convertDiagramSpecification16ToVirtualModel17(File file, Document diagram, List<File> oldPaletteFiles, List<File> oldExampleDiagramFiles, ViewPointResource viewPointResource) { // Create the diagram specification and a virtual model with a diagram typed model slot referencing this diagram specification final String ADDRESSED_DIAGRAM_MODEL_SLOT = "AddressedDiagramModelSlot"; final String MODELSLOT_VIRTUAL_MODEL_MODEL_SLOT = "ModelSlot_VirtualModelModelSlot"; final String MODELSLOT_TYPED_DIAGRAM_MODEL_SLOT = "ModelSlot_TypedDiagramModelSlot"; try {//from www . j a v a 2 s .c o m String diagramName = file.getName().replace(".xml", ""); // Create a folder that contains the diagram specification File diagramSpecificationFolder = new File( file.getParentFile() + "/" + diagramName + ".diagramspecification"); diagramSpecificationFolder.mkdir(); // Retrieve diagram drop schemes Iterator<Element> dropSchemeElements = diagram.getDescendants(new ElementFilter("DropScheme")); List<Element> dropSchemes = IteratorUtils.toList(dropSchemeElements); // Retrieve Diagram Model slots references Iterator<? extends Content> thisModelSlotsIterator = diagram.getDescendants( new ElementFilter("DiagramModelSlot").or(new ElementFilter(ADDRESSED_DIAGRAM_MODEL_SLOT))); List<Element> thisModelSlots = IteratorUtils.toList(thisModelSlotsIterator); // Retrieve the DiagramModelSlot (this), and transform it to a virtual model slot with a virtual model uri int thisID = 0; String newThisUri = viewPointResource.getURI() + "/" + diagramName; String diagramSpecificationURI = newThisUri + "/" + diagramName + ".diagramspecification"; Element typedDiagramModelSlot = null; boolean foundThis = false; for (Element thisMs : thisModelSlots) { // Retriev the ID and URI of this DiagramModelSlot if (thisMs.getAttribute("name") != null && thisMs.getAttributeValue("name").equals("this") && !foundThis) { // Store its ID and its URI thisID = thisMs.getAttribute("id").getIntValue(); if (thisMs.getAttributeValue("virtualModelURI") != null) { newThisUri = thisMs.getAttributeValue("virtualModelURI"); thisMs.removeAttribute("virtualModelURI"); thisMs.removeAttribute("name"); thisMs.getAttribute("id").setName("idref"); thisMs.setAttribute("idref", Integer.toString(thisID)); } // Replace by a Typed model slot typedDiagramModelSlot = new Element(MODELSLOT_TYPED_DIAGRAM_MODEL_SLOT); typedDiagramModelSlot.setAttribute("metaModelURI", diagramSpecificationURI); typedDiagramModelSlot.setAttribute("name", "typedDiagramModelSlot"); typedDiagramModelSlot.setAttribute("id", Integer.toString(computeNewID(diagram))); foundThis = true; } } // Replace the Diagram Model Slot by a Virtual Model Model slot for (Element thisMs : thisModelSlots) { if (hasSameID(thisMs, thisID) && thisMs.getName().equals("DiagramModelSlot")) { thisMs.setName("FMLRTModelSlot"); thisMs.getAttributes().add(new Attribute("virtualModelURI", newThisUri)); thisMs.getAttributes().add(new Attribute("name", "virtualModelInstance")); thisMs.getAttributes().add(new Attribute("id", Integer.toString(thisID))); thisMs.removeAttribute("idref"); } } // Update ids for all model slots Iterator<? extends Content> diagramModelSlotsIterator = diagram.getDescendants( new ElementFilter("DiagramModelSlot").or(new ElementFilter(ADDRESSED_DIAGRAM_MODEL_SLOT))); List<Element> thisDiagramModelSlots = IteratorUtils.toList(diagramModelSlotsIterator); for (Element diagramMs : thisDiagramModelSlots) { if (diagramMs.getAttribute("id") != null && typedDiagramModelSlot != null) { diagramMs.setAttribute("id", typedDiagramModelSlot.getAttributeValue("id")); } if (diagramMs.getAttribute("idref") != null) { // Change to TypedDiagramModelSlot if (diagramMs.getParentElement().getName().equals("AddShape") || diagramMs.getParentElement().getName().equals("AddConnector") || diagramMs.getParentElement().getName().equals("AddDiagram") || diagramMs.getParentElement().getName().equals("ContainedShapePatternRole") || diagramMs.getParentElement().getName().equals("ContainedConnectorPatternRole") || diagramMs.getParentElement().getName().equals("ContainedDiagramPatternRole")) { if (typedDiagramModelSlot.getAttributeValue("id") != null) { diagramMs.setAttribute("idref", typedDiagramModelSlot.getAttributeValue("id")); diagramMs.setName("TypedDiagramModelSlot"); } } else { diagramMs.setName(MODELSLOT_VIRTUAL_MODEL_MODEL_SLOT); } } } for (Content content : diagram.getDescendants()) { if (content instanceof Element) { Element element = (Element) content; if (element.getName().equals("AddShape") || element.getName().equals("AddConnector") || element.getName().equals("AddDiagram")) { if (element.getChild("TypedDiagramModelSlot") == null && element.getChild("AddressedDiagramModelSlot") == null) { Element adressedMsElement = new Element("TypedDiagramModelSlot"); Attribute newIdRefAttribute = new Attribute("idref", typedDiagramModelSlot.getAttributeValue("id")); adressedMsElement.getAttributes().add(newIdRefAttribute); element.addContent(adressedMsElement); } } } } // Update DiagramSpecification URI for (Content content : diagram.getDescendants()) { if (content instanceof Element) { Element element = (Element) content; if (element.getAttribute("diagramSpecificationURI") != null) { String oldDiagramSpecificationUri = element.getAttributeValue("diagramSpecificationURI"); String diagramSpecificationName = oldDiagramSpecificationUri .substring(oldDiagramSpecificationUri.lastIndexOf("/")); String newDiagramSpecificationUri = oldDiagramSpecificationUri + diagramSpecificationName + ".diagramspecification"; element.getAttribute("diagramSpecificationURI").setValue(newDiagramSpecificationUri); } } } // Change all the "diagram" binding with "this", and "toplevel" with typedDiagramModelSlot.topLevel" in case of not // DropSchemeAction for (Content content : diagram.getDescendants()) { if (content instanceof Element) { Element element = (Element) content; for (Attribute attribute : element.getAttributes()) { if (attribute.getValue().startsWith("diagram")) { attribute.setValue(attribute.getValue().replace("diagram", "this")); } if (attribute.getValue().startsWith("topLevel")) { boolean diagramScheme = false; Element parentElement = element.getParentElement(); while (parentElement != null) { if (parentElement.getName().equals("DropScheme") || parentElement.getName().equals("LinkScheme")) { diagramScheme = true; } parentElement = parentElement.getParentElement(); } if (!diagramScheme) { attribute.setValue(attribute.getValue().replace("topLevel", "virtualModelInstance.typedDiagramModelSlot")); } } } } } // Create the diagram specificaion xml file File diagramSpecificationFile = new File(diagramSpecificationFolder, file.getName()); Document diagramSpecification = new Document(); Element rootElement = new Element("DiagramSpecification"); Attribute name = new Attribute("name", diagramName); Attribute diagramSpecificationURIAttribute = new Attribute("uri", diagramSpecificationURI); diagramSpecification.addContent(rootElement); rootElement.getAttributes().add(name); rootElement.getAttributes().add(diagramSpecificationURIAttribute); XMLUtils.saveXMLFile(diagramSpecification, diagramSpecificationFile); // Copy the palette files inside diagram specification repository ArrayList<File> newPaletteFiles = new ArrayList<File>(); for (File paletteFile : oldPaletteFiles) { File newFile = new File(diagramSpecificationFolder + "/" + paletteFile.getName()); FileUtils.rename(paletteFile, newFile); newPaletteFiles.add(newFile); Document palette = XMLUtils.readXMLFile(newFile); Attribute diagramSpecUri = new Attribute("diagramSpecificationURI", diagramSpecificationURI); palette.getRootElement().getAttributes().add(diagramSpecUri); convertNames16ToNames17(palette); XMLUtils.saveXMLFile(palette, newFile); } // Copy the example diagram files inside diagram specification repository ArrayList<File> newExampleDiagramFiles = new ArrayList<File>(); for (File exampleDiagramFile : oldExampleDiagramFiles) { File newFile = new File(diagramSpecificationFolder + "/" + exampleDiagramFile.getName()); FileUtils.rename(exampleDiagramFile, newFile); newExampleDiagramFiles.add(newFile); Document exampleDiagram = XMLUtils.readXMLFile(newFile); exampleDiagram.getRootElement().setAttribute("uri", diagramSpecificationURI + "/" + exampleDiagram.getRootElement().getAttributeValue("name")); Attribute diagramSpecUri = new Attribute("diagramSpecificationURI", diagramSpecificationURI); exampleDiagram.getRootElement().getAttributes().add(diagramSpecUri); exampleDiagram.getRootElement().setAttribute("uri", diagramSpecificationURI + "/" + exampleDiagram.getRootElement().getAttributeValue("name")); convertNames16ToNames17(exampleDiagram); XMLUtils.saveXMLFile(exampleDiagram, newFile); } // Update the diagram palette element bindings ArrayList<Element> paletteElementBindings = new ArrayList<Element>(); for (File paletteFile : newPaletteFiles) { Document palette = XMLUtils.readXMLFile(paletteFile); String paletteUri = diagramSpecificationURI + "/" + palette.getRootElement().getAttribute("name").getValue() + ".palette"; Iterator<? extends Content> paletteElements = palette .getDescendants(new ElementFilter("DiagramPaletteElement")); while (paletteElements.hasNext()) { Element paletteElement = (Element) paletteElements.next(); Element binding = createPaletteElementBinding(paletteElement, paletteUri, dropSchemes); if (binding != null) { paletteElementBindings.add(binding); } } XMLUtils.saveXMLFile(palette, paletteFile); } // Add the Palette Element Bindings to the TypedDiagramModelSlot if (!paletteElementBindings.isEmpty()) { typedDiagramModelSlot.addContent(paletteElementBindings); } if (typedDiagramModelSlot != null) { diagram.getRootElement().addContent(typedDiagramModelSlot); } // Update names convertNames16ToNames17(diagram); convertOldNameToNewNames("DiagramSpecification", "VirtualModel", diagram); // Save the files XMLUtils.saveXMLFile(diagram, file); } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }