Example usage for org.jdom2 Element clone

List of usage examples for org.jdom2 Element clone

Introduction

In this page you can find the example usage for org.jdom2 Element clone.

Prototype

@Override
public Element clone() 

Source Link

Document

This returns a deep clone of this element.

Usage

From source file:jodtemplate.pptx.style.HtmlStylizer.java

License:Apache License

private Element applyFormatting(final List<org.jsoup.nodes.Element> tags, final Element arPr,
        final Slide slide) {
    final Element formatted;
    if (arPr == null) {
        formatted = new Element(PPTXDocument.RPR_ELEMENT, getDrawingmlNamespace());
    } else {//from   ww w.  j a  va2 s  .com
        formatted = arPr.clone();
    }
    for (org.jsoup.nodes.Element tag : tags) {
        final String tagName = tag.tagName();
        if (U_TAG.equals(tagName) || INS_TAG.equals(tagName)) {
            formatted.setAttribute(U_TAG, SNG);
        } else if (I_TAG.equals(tagName) || EM_TAG.equals(tagName)) {
            formatted.setAttribute(I_TAG, ONE);
        } else if (B_TAG.equals(tagName) || STRONG_TAG.equals(tagName)) {
            formatted.setAttribute(B_TAG, ONE);
        } else if (A_TAG.equals(tagName)) {
            createHyperlink(tag, formatted, slide);
        }
    }
    return formatted;
}

From source file:msi.gama.doc.util.UnifyDoc.java

License:Open Source License

private static Document mergeFiles(final HashMap<String, File> hmFilesPackages) {
    try {//  ww w  .j a  v  a 2 s. co  m

        SAXBuilder builder = new SAXBuilder();
        Document doc = null;

        doc = new Document(new Element(XMLElements.DOC));
        for (String elt : tabEltXML) {
            doc.getRootElement().addContent(new Element(elt));
        }

        for (Entry<String, File> fileDoc : hmFilesPackages.entrySet()) {
            Document docTemp = builder.build(fileDoc.getValue());

            for (String catXML : tabEltXML) {
                if (docTemp.getRootElement().getChild(catXML) != null) {

                    List<Element> existingElt = doc.getRootElement().getChild(catXML).getChildren();

                    for (Element e : docTemp.getRootElement().getChild(catXML).getChildren()) {
                        // Do not add the projectName for every kinds of
                        // categories
                        //      if (!Arrays.asList(tabCategoriesEltXML).contains(catXML)) {
                        e.setAttribute("projectName", fileDoc.getKey());
                        //      }

                        // Test whether the element is already in the merged
                        // doc
                        boolean found = false;
                        for (Element exElt : existingElt) {
                            boolean equals = exElt.getName().equals(e.getName());
                            for (Attribute att : exElt.getAttributes()) {
                                String valueExElt = exElt.getAttribute(att.getName()) != null
                                        ? exElt.getAttributeValue(att.getName())
                                        : "";
                                String valueE = e.getAttribute(att.getName()) != null
                                        ? e.getAttributeValue(att.getName())
                                        : "";
                                equals = equals && valueExElt.equals(valueE);
                            }
                            found = found || equals;
                        }
                        // Add if it is not already in the merged doc
                        if (!found) {
                            doc.getRootElement().getChild(catXML).addContent(e.clone());
                        }
                    }
                }
            }
        }

        // Add an element for the generated types
        doc.getRootElement().getChild(XMLElements.OPERATORS_CATEGORIES)
                .addContent(new Element(XMLElements.CATEGORY).setAttribute(XMLElements.ATT_CAT_ID,
                        new TypeConverter().getProperCategory("Types")));

        return doc;
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:net.exclaimindustries.paste.braket.server.TeamDownloader.java

License:Open Source License

public static Team parseTeam(Document document) throws MalformedURLException {
    // Parse out the details
    Element rootNode = document.getRootElement();

    // I need the espn namespace
    List<Namespace> namespaceList = rootNode.getNamespacesInScope();
    Namespace ns = Namespace.NO_NAMESPACE;
    for (Namespace namespace : namespaceList) {
        if (namespace.getPrefix() == "espn") {
            ns = namespace;/*from   w  w w  .ja v  a2 s.c  o  m*/
            break;
        }
    }

    // Find the "item" element that has the right stuff in it
    Element channel = rootNode.getChild("channel");
    List<Element> items = channel.getChildren("item");
    Element teamElement = null;
    for (Element item : items) {
        if (item.getChild("teamAbbrev", ns) != null) {
            teamElement = item.clone();
            break;
        }
    }

    if (teamElement == null) {
        // Couldn't find any info about the team, so skip it.
        return null;
    }

    // Make sure that the given ID matches the ID in the team (else this
    // is not a real team)
    Long teamId = Long.valueOf(teamElement.getChildText("teamId", ns));

    Team team = new Team();
    team.setId(teamId);

    String abbreviation = digOutCDATA(teamElement, "teamAbbrev", ns);
    String displayName = digOutCDATA(teamElement, "teamDisplayName", ns);
    String location = digOutCDATA(teamElement, "teamLocation", ns);
    String nickname = digOutCDATA(teamElement, "teamNickname", ns);
    String teamNameString = teamElement.getChildText("teamName", ns);
    String teamColorString = "#" + teamElement.getChildText("teamColor", ns);
    String teamLogoUrl = teamElement.getChildText("teamLogo", ns);

    TeamName teamName = new TeamName(location, teamNameString, displayName, nickname, abbreviation);
    team.setName(teamName);

    try {
        if (teamColorString != null) {
            RGBAColor color = RGBAColor.fromCSSString(teamColorString);
            team.setColor(color);
        }
    } catch (Exception e) {
        // TODO Is this okay?
    }

    // Save the image name (should be the same as the downloaded version)
    URL url = new URL(teamLogoUrl);
    File file = new File(url.getPath());
    String teamLogoName = file.getName();
    team.setPicture(teamLogoName);

    return team;
}

From source file:org.artifactory.update.security.v2.RepoPathAclConverter.java

License:Open Source License

@Override
@SuppressWarnings({ "unchecked" })
public void convert(Document doc) {
    Element aclsTag = doc.getRootElement().getChild("acls");
    List<Element> acls = aclsTag.getChildren();
    for (Element acl : acls) {
        if (acl.getName().contains("RepoPathAcl")) {
            acl.setName("acl");
            convertIdentifierToPermissionTarget(acl);
            Element acesTag = acl.getChild(ACES);
            Element aceListTag = acesTag.getChild("list");
            List<Element> aces = aceListTag.getChildren("org.artifactory.security.RepoPathAce");
            Element newAces = new Element(ACES);
            Element aceTemplate = new Element("ace");
            Element groupEl = new Element("group");
            groupEl.setText("false");
            aceTemplate.addContent(new Element(PRINCIPAL)).addContent(groupEl).addContent(new Element(MASK));
            for (Element ace : aces) {
                Element newAce = (Element) aceTemplate.clone();
                newAce.getChild(PRINCIPAL).setText(ace.getChildText(PRINCIPAL));
                Element maskEl = ace.getChild(MASK);
                int mask = Integer.parseInt(maskEl.getText());
                if ((mask & (ArtifactoryPermission.MANAGE.getMask()
                        | ArtifactoryPermission.DEPLOY.getMask())) > 0) {
                    mask |= ArtifactoryPermission.DELETE.getMask();
                }/*from   ww  w  . j a v a 2s. co  m*/
                newAce.getChild(MASK).setText("" + mask);
                newAces.addContent(newAce);
            }
            acl.removeChild(ACES);
            acl.addContent(newAces);
        } else {
            log.warn("Acl tag " + acl + " under acls is not a RepoPAthAcl!");
        }
    }
}

From source file:org.artifactory.update.security.v4.AnnotatePermissionXmlConverter.java

License:Open Source License

@Override
@SuppressWarnings({ "unchecked" })
public void convert(Document doc) {
    Element aclsTag = doc.getRootElement().getChild("acls");
    List<Element> acls = aclsTag.getChildren();
    for (Element acl : acls) {
        Element acesTag = acl.getChild(ACES);
        List<Element> aces = acesTag.getChildren(ACE);
        Element newAces = new Element(ACES);
        Element aceTemplate = new Element(ACE);
        Element groupEl = new Element(GROUP);
        aceTemplate.addContent(new Element(PRINCIPAL)).addContent(groupEl).addContent(new Element(MASK));
        for (Element ace : aces) {
            Element child = ace.getChild("principal");
            Element newAce = (Element) aceTemplate.clone();
            newAce.getChild(PRINCIPAL).setText(ace.getChildText(PRINCIPAL));
            newAce.getChild(GROUP).setText(ace.getChildText(GROUP));

            Element maskEl = ace.getChild(MASK);
            int mask = Integer.parseInt(maskEl.getText());
            if (!child.getText().equals(UserInfo.ANONYMOUS)) {
                if ((mask & (ArtifactoryPermission.MANAGE.getMask()
                        | ArtifactoryPermission.DEPLOY.getMask())) > 0) {
                    mask |= ArtifactoryPermission.ANNOTATE.getMask();
                }/*from ww  w  .j  a v a  2s .  c om*/
            }
            newAce.getChild(MASK).setText("" + mask);
            newAces.addContent(newAce);
        }
        acl.removeChild(ACES);
        acl.addContent(newAces);
    }
}

From source file:org.esa.s2tbx.dataio.s2.gml.GmlFilter.java

License:Open Source License

public Pair<String, List<EopPolygon>> parse(InputStream stream) {
    SAXBuilder builder = new SAXBuilder();
    Document jdomDoc = null;//from w  w  w  .  j av a2s . com

    try {
        jdomDoc = builder.build(stream);

        //get the root element
        Element web_app = jdomDoc.getRootElement();
        String maskEpsg = "";

        Namespace gml = Namespace.getNamespace("http://www.opengis.net/gml/3.2");
        Namespace eop = Namespace.getNamespace("http://www.opengis.net/eop/2.0");

        List<Element> targeted = web_app.getChildren("boundedBy", gml);
        if (!targeted.isEmpty()) {
            Element aEnvelope = targeted.get(0).getChild("Envelope", gml);
            if (aEnvelope != null) {
                maskEpsg = aEnvelope.getAttribute("srsName").getValue();
            }
        }

        List<EopPolygon> recoveredGeometries = new ArrayList<>();

        IteratorIterable<Content> contents = web_app.getDescendants();
        while (contents.hasNext()) {
            Content web_app_content = contents.next();
            if (!web_app_content.getCType().equals(CType.Text)
                    && !web_app_content.getCType().equals(CType.Comment)) {
                boolean withGml = (web_app_content.getNamespacesInScope().get(0).getPrefix().contains("gml"));
                if (withGml) {
                    boolean parentNotGml = !(web_app_content.getParentElement().getNamespace().getPrefix()
                            .contains("gml"));
                    if (parentNotGml) {
                        Element capturedElement = (Element) web_app_content;
                        Attribute attr = null;
                        String polygonId = "";
                        String typeId = "";
                        if (capturedElement.getName().contains("Polygon")) {
                            attr = capturedElement.getAttribute("id", gml);
                            if (attr != null) {
                                polygonId = attr.getValue();
                                if (polygonId.indexOf('.') != -1) {
                                    typeId = polygonId.substring(0, polygonId.indexOf('.'));
                                }
                            }
                        }

                        Document newDoc = new Document(capturedElement.clone().detach());

                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        xmlOutput.output(newDoc, baos);
                        String replacedContent = baos.toString().replace("/www.opengis.net/gml/3.2",
                                "/www.opengis.net/gml");

                        InputStream ois = new ByteArrayInputStream(replacedContent.getBytes());

                        List<Polygon> pols = streamParseGML3(ois);
                        for (Polygon pol : pols) {
                            recoveredGeometries.add(new EopPolygon(polygonId, typeId, pol));
                        }
                    }
                }

            }
        }

        return new Pair<String, List<EopPolygon>>(maskEpsg, recoveredGeometries);
    } catch (JDOMException e) {
        // {@report "parse xml problem !"}
    } catch (IOException e) {
        // {@report "IO problem !"}
    }

    return new Pair<String, List<EopPolygon>>("", new ArrayList<>());
}

From source file:org.isima.carsharing.launcher.Launcher.java

public static void addConfigComment(SettingsDelegate settingsDelegate, File out) {
    try {/*from   ww w  .  j a  v  a  2  s  . c  om*/
        SAXBuilder builder = new SAXBuilder();

        Document doc = (Document) builder.build(out);
        Element rootNode = doc.getRootElement();
        Element rootNodeCopy = rootNode.clone();

        doc.removeContent(rootNode);
        rootNodeCopy.detach();

        Comment comment = new Comment(settingsDelegate.usedConfigsToXMLComment());
        doc.addContent(comment);
        doc.addContent(rootNodeCopy);

        XMLOutputter xmlOutput = new XMLOutputter();
        xmlOutput.setFormat(Format.getPrettyFormat());
        xmlOutput.output(doc, new FileWriter(out));
    } catch (JDOMException | IOException ex) {
        Logger.getLogger(Launcher.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.jumpmind.metl.core.runtime.component.XmlFormatter.java

License:Open Source License

private void addModelAttributeXml(Stack<DocElement> parentStack, String attributeId, Object modelAttrValue,
        Document generatedXml, String entityId) {

    DocElement templateDocElement = entityAttributeDtls.get(attributeId);
    String value = modelAttrValue == null ? null : modelAttrValue.toString();
    Element newElement = null;/*from w w  w  . java  2s.  c om*/
    Element templateParentElement = null;
    String templateParentXPath = null;
    Attribute newAttribute = null;
    Map<Element, Namespace> generatedDocNamespaces = null;
    Map<Element, Namespace> templateNamespaces = null;
    Stack<Element> parentsToAdd = new Stack<Element>();
    DocElement entityDocElement = entityAttributeDtls.get(entityId);

    generatedDocNamespaces = removeNamespaces(generatedXml);
    templateNamespaces = removeNamespaces(templateDoc);

    // we can be passed elements in the model that don't reside in the
    // template. If so, just ignore the field and do nothing
    if (templateDocElement != null) {
        // at this point, our stack should always currently have the entity
        // for this attribute as the top level of the stack

        // set up our new element or attribute to add
        if (templateDocElement.xmlElement != null) {
            // we have to add an element
            newElement = templateDocElement.xmlElement.clone();
            newElement.removeContent();
            removeAllAttributes(newElement);

            if (StringUtils.isEmpty(value)) {
                if (nullHandling.equalsIgnoreCase(NULL_HANDLING_XML_NIL)) {
                    newElement.setAttribute("nil", "true", getXmlNamespace());
                }
            } else {
                newElement.setText(value);
            }
        } else {
            // we have to add an attribute
            newAttribute = templateDocElement.xmlAttribute.clone();
            if (value != null) {
                newAttribute.setValue(value);
            }
        }

        // in this case the attribute is one lower than the entity and
        // should simply be attached to the entity
        if (templateDocElement.level - 1 == parentStack.peek().level) {
            if (newElement != null) {
                applyAttributeXPath(generatedXml, templateDocElement.xpath, value);
            } else {
                parentStack.peek().xmlElement.setAttribute(newAttribute);
            }
        } else {
            // the attribute doesn't hang directly off the entity
            // we must find its parent in the existing doc or fill static
            // content as appropriate

            // first get the parent element for this model attribute, and
            // gets its xpath
            XPathExpression<Element> expression = XPathFactory.instance().compile(templateDocElement.xpath,
                    Filters.element());
            List<Element> matches = expression.evaluate(templateDoc.getRootElement());
            if (matches.size() != 0) {
                templateParentElement = matches.get(0).getParentElement();
            } else {
                // throw an exception, we should always find the element in
                // the template
            }

            // now look for parent elements in the generated xml until we
            // find one
            // or we hit the entity itself
            boolean parentFound = false;
            do {
                templateParentXPath = XPathHelper.getRelativePath(entityDocElement.xmlElement,
                        templateParentElement);
                expression = XPathFactory.instance().compile(templateParentXPath, Filters.element());
                matches = expression.evaluate(parentStack.peek().xmlElement);
                if (matches.size() == 0) {
                    Element elementToAdd = templateParentElement.clone();
                    elementToAdd.removeContent();
                    removeAllAttributes(elementToAdd);
                    parentsToAdd.push(elementToAdd);
                    templateParentElement = templateParentElement.getParentElement();
                } else {
                    parentFound = true;
                }
            } while (parentFound == false);

            // add every parent we couldn't find up to the entity level
            Element elementToAddTo = matches.get(0);
            while (!parentsToAdd.isEmpty()) {
                elementToAddTo.addContent(0, parentsToAdd.peek());
                elementToAddTo = parentsToAdd.pop();
            }

            // add our model attribute to the latest level
            if (newElement != null) {
                applyAttributeXPath(generatedXml, templateDocElement.xpath, value);
            } else {
                elementToAddTo.setAttribute(newAttribute);
            }
        }
    }
    restoreNamespaces(templateDoc, templateNamespaces);
    restoreNamespaces(generatedXml, generatedDocNamespaces);
}

From source file:org.kdp.word.transformer.FootnodeTransformer.java

License:Apache License

@Override
public void transform(Context context) {

    Map<String, Footnode> footnodes = new LinkedHashMap<>();

    Element root = context.getSourceRoot();
    for (Element el : root.getChildren()) {
        findFootnodes(context, el, footnodes);
    }//from   www  .jav  a 2s . c  om

    JDOMFactory factory = context.getJDOMFactory();
    for (Footnode fn : footnodes.values()) {

        // Footnode Ref
        Element fnref = fn.fnref;
        String text = getFootnodeText(fnref);
        Parent parent = fnref.getParent();
        int index = parent.indexOf(fnref);
        parent.removeContent(index);
        Element span = factory.element("span");
        span.setAttribute("class", "MsoFootnoteReference");
        Element a = fnref.clone();
        a.removeContent();
        a.setText(text);
        //a.setAttribute("type", "noteref", OPFTransformer.NS_OPF);
        span.addContent(a);
        parent.addContent(index, span);

        /* Footnode Text
        Element fntxt = fn.fntxt;
        Element p = findMsoFootnoteText(fntxt); 
        text = getFootnodeText(p);
        p.getAttributes().clear();
        p.removeContent();
        p.setText(text);
        String divid = fn.id.substring(1);
        Element div = JDOMUtils.findElement(root, "div", "id", divid);
        IllegalStateAssertion.assertSame(p.getParentElement(), div, "Unexpected parent: " + div);
        Parent divparent = div.getParent();
        Element aside = factory.element("aside");
        aside.setAttribute("type", "footnote", OPFTransformer.NS_OPF);
        aside.setAttribute("id", fn.id);
        index = divparent.indexOf(div);
        divparent.removeContent(div);
        aside.addContent(p.clone());
        divparent.addContent(index, aside);
        */
    }
}

From source file:org.kdp.word.transformer.SectionTransformer.java

License:Apache License

@Override
public void transform(Context context) {
    JDOMFactory factory = context.getJDOMFactory();

    Sections sections = new Sections();
    context.putAttribute(Sections.class, sections);

    Element root = context.getSourceRoot();
    for (Element el : root.getChildren()) {
        findWordSections(context, sections, el);
    }/* w w  w . j a v  a2  s  .  c om*/

    boolean navfound = false;
    Iterator<Section> itsec = sections.iterator();
    while (itsec.hasNext()) {
        Section section = itsec.next();

        if (navfound) {
            itsec.remove();
            continue;
        }
        navfound = section.isnav;

        // Remove the section from the original document
        Element element = section.element;
        Parent parent = element.getParent();
        parent.removeContent(element);

        // Build the target document 
        Element rootClone = root.clone();
        Element bodyClone = JDOMUtils.findElement(rootClone, "body");
        bodyClone.removeContent();
        bodyClone.addContent(element.clone());

        // Write the section document
        Document doc = factory.document(rootClone);
        File outfile = section.target.toFile();
        try {
            outfile.getParentFile().mkdirs();
            FileOutputStream fos = new FileOutputStream(outfile);
            IOUtils.writeDocument(context, doc, fos);
            fos.close();
        } catch (IOException ex) {
            throw new IllegalStateException(ex);
        }
    }
}