Example usage for org.jdom2 Element removeContent

List of usage examples for org.jdom2 Element removeContent

Introduction

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

Prototype

@Override
public List<Content> removeContent() 

Source Link

Document

Removes all child content from this parent.

Usage

From source file:io.wcm.handler.richtext.impl.RichTextRewriteContentHandlerImpl.java

License:Apache License

/**
 * Checks if the given element has to be rewritten.
 * Is called for every child single element of the parent given to rewriteContent method.
 * @param element Element to check/*from   w ww. ja v a  2s . com*/
 * @return null if nothing is to do with this element.
 *         Return empty list to remove this element.
 *         Return list with other content to replace element with new content.
 */
@Override
public List<Content> rewriteElement(Element element) {

    // rewrite anchor elements
    if (StringUtils.equalsIgnoreCase(element.getName(), "a")) {
        return rewriteAnchor(element);
    }

    // rewrite image elements
    else if (StringUtils.equalsIgnoreCase(element.getName(), "img")) {
        return rewriteImage(element);
    }

    // detect BR elements and turn those into "self-closing" elements
    // since the otherwise generated <br> </br> structures are illegal and
    // are not handled correctly by Internet Explorers
    else if (StringUtils.equalsIgnoreCase(element.getName(), "br")) {
        if (element.getContent().size() > 0) {
            element.removeContent();
        }
        return null;
    }

    // detect empty elements and insert at least an empty string to avoid "self-closing" elements
    // that are not handled correctly by most browsers
    else if (NONSELFCLOSING_TAGS.contains(StringUtils.lowerCase(element.getName()))) {
        if (element.getContent().isEmpty()) {
            element.setText("");
        }
        return null;
    }

    return null;
}

From source file:io.wcm.handler.richtext.util.RichTextUtil.java

License:Apache License

/**
 * Rewrites all children/sub-tree of the given parent element.
 * For rewrite operations the given rewrite content handler is called.
 * @param parent Parent element/*from   ww w .  j  ava 2s. c  o m*/
 * @param rewriteContentHandler Rewrite content handler
 */
public static void rewriteContent(Element parent, RewriteContentHandler rewriteContentHandler) {

    // iterate through content list and build new content list
    List<Content> originalContent = parent.getContent();
    List<Content> newContent = new ArrayList<Content>();
    for (Content contentElement : originalContent) {

        // handle element
        if (contentElement instanceof Element) {
            Element element = (Element) contentElement;

            // check if rewrite is needed for element
            List<Content> rewriteContent = rewriteContentHandler.rewriteElement(element);
            if (rewriteContent != null) {
                // element was removed
                if (rewriteContent.isEmpty()) {
                    // do not add to newContent
                }

                // element is the same - rewrite child elements
                else if (rewriteContent.size() == 1 && rewriteContent.get(0) == element) { //NOPMD
                    rewriteContent(element, rewriteContentHandler);
                    newContent.add(element);
                }

                // element was replaced with other content - rewrite and add instead
                else {
                    for (Content newContentItem : rewriteContent) {
                        if (newContentItem instanceof Element) {
                            Element newElement = (Element) newContentItem;
                            rewriteContent(newElement, rewriteContentHandler);
                        }
                        newContent.add(newContentItem.clone());
                    }
                }
            }

            // nothing to rewrite - do nothing, but rewrite child element
            else {
                rewriteContent(element, rewriteContentHandler);
                newContent.add(element);
            }

        }

        // handle text node
        else if (contentElement instanceof Text) {
            Text text = (Text) contentElement;

            // check if rewrite is needed for text node
            List<Content> rewriteContent = rewriteContentHandler.rewriteText(text);
            if (rewriteContent != null) {
                // element was removed
                if (rewriteContent.isEmpty()) {
                    // do not add to newContent
                }

                // element is the same - ignore
                else if (rewriteContent.size() == 1 && rewriteContent.get(0) == text) { //NOPMD
                    // add original element
                    newContent.add(text);
                }

                // element was replaced with other content - add instead
                else {
                    for (Content newContentItem : rewriteContent) {
                        newContent.add(newContentItem.clone());
                    }
                }
            }

            // nothing to rewrite - do nothing, but add original text element
            else {
                newContent.add(text);
            }

        }

        // unknown element - just add to new content
        else {
            newContent.add(contentElement);
        }

    }

    // replace original content with new content
    parent.removeContent();
    parent.addContent(newContent);

}

From source file:org.artifactory.update.md.v125rc0.MdStatsConverter.java

License:Open Source License

@Override
public void convert(Document doc) {
    Element root = doc.getRootElement();
    Element downloadCount = root.getChild("downloadCount");
    if (downloadCount == null) {
        downloadCount = new Element("downloadCount");
        downloadCount.setText("0");
    }/* w  w w .  j av  a 2s. com*/
    // rename the root to the stats name
    root.setName(STATS_NAME);
    // remove all childer
    root.removeContent();
    // add the download count
    root.addContent(downloadCount);
}

From source file:org.artifactory.version.converter.v136.IndexerCronRemoverConverter.java

License:Open Source License

@Override
public void convert(Document doc) {
    Element root = doc.getRootElement();
    Namespace ns = root.getNamespace();

    /*//w ww.  ja  va  2s.  c  o m
    <indexer>
    <cronExp>0 /1 * * * ?</cronExp>
    </indexer>
    to:
    <indexer>
    <indexingIntervalHours>24</indexingIntervalHours>
    </indexer>
     */
    Element indexerElement = root.getChild("indexer", ns);
    if (indexerElement != null) {
        log.debug("Removing indexer cron expression.");
        indexerElement.removeContent();
        log.debug("Adding default indexer interval.");
        Element intervalElement = new Element("indexingIntervalHours", ns);
        intervalElement.setText("24");
        indexerElement.addContent(0, intervalElement);
    }
}

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

License:Open Source License

private void fillStackWithStaticParentElements(Stack<DocElement> parentStack, DocElement firstDocElement,
        Document generatedXml) {//from  w w w. j a  v a 2 s.  c o m

    Element elementToPutOnStack = null;
    Map<Element, Namespace> namespaces = null;

    // if the generatedXml doc is empty then start a new one and use it for
    // search
    if (!generatedXml.hasRootElement()) {
        Element newRootElement = templateDoc.getRootElement().clone();
        generatedXml.setRootElement(newRootElement);
        namespaces = removeNamespaces(generatedXml);
        XPathExpression<Element> expression = XPathFactory.instance().compile(firstDocElement.xpath,
                Filters.element());
        List<Element> matches = expression.evaluate(generatedXml.getRootElement());
        if (matches.size() != 0) {
            elementToPutOnStack = matches.get(0).getParentElement();
        } else {
            elementToPutOnStack = generatedXml.getRootElement();
        }
        elementToPutOnStack.removeContent();
        removeAllAttributes(elementToPutOnStack);
        parentStack.push(new DocElement(firstDocElement.level - 1, elementToPutOnStack, null, null));
        restoreNamespaces(generatedXml, namespaces);
    } else {
        // we already have a genertedXml going, but need other static
        // elements from the template
        namespaces = removeNamespaces(templateDoc);
        XPathExpression<Element> expression = XPathFactory.instance().compile(firstDocElement.xpath,
                Filters.element());
        List<Element> matches = expression.evaluate(templateDoc.getRootElement());
        // TODO: do something here for when the attribute is more than one
        // level away from the entity
        if (matches.size() != 0) {
            elementToPutOnStack = matches.get(0).getParentElement().clone();
        } else {
            // throw some exception here
        }
        elementToPutOnStack.removeContent();
        removeAllAttributes(elementToPutOnStack);
        parentStack.push(new DocElement(firstDocElement.level - 1, elementToPutOnStack, null, null));
        restoreNamespaces(templateDoc, namespaces);
    }
}

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;
    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());
                }//from  ww w  .  j ava2 s  . co m
            } 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);
    }// w w w  .j  a v  a  2 s.  c o  m

    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 ava 2s  .  c o m

    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);
        }
    }
}

From source file:org.mycore.frontend.editor.MCREditorServlet.java

License:Open Source License

/**
 * Replaces editor elements in static webpage with complete editor
 * definition.//from   www  .  j ava 2s  . com
 * 
 * @param request
 *            the current MCRServletJob
 * @param uri
 *            the uri of the static XML file containing the editor
 * @param xml
 *            the complete XML document of the static webpage
 */
public static void replaceEditorElements(HttpServletRequest request, String uri, Document xml) {
    String sessionID = request.getParameter("XSL.editor.session.id");

    List<Element> editors = new ArrayList<Element>();
    Iterator it = xml.getDescendants(new ElementFilter("editor"));
    while (it.hasNext()) {
        editors.add((Element) it.next());
    }

    for (Element editor : editors) {
        Element editorResolved = null;
        if (sessionID != null) {
            MCREditorSession editorSession = MCREditorSessionCache.instance().getEditorSession(sessionID);
            if (editorSession == null) {
                throw new MCRException("Editor session is invalid:" + sessionID);
            }
            editorResolved = editorSession.getXML();
        }

        if (sessionID == null || editorResolved == null) {
            Map parameters = request.getParameterMap();
            boolean validate = "true".equals(editor.getAttributeValue("validate", "false"));
            String ref = editor.getAttributeValue("id");
            editorResolved = startSession(parameters, ref, uri, validate);
        }

        String clazz1 = editor.getAttributeValue("class");
        String clazz2 = editorResolved.getAttributeValue("class");
        editor.removeContent();
        editor.addContent(editorResolved.cloneContent());
        editor.setAttribute("session", editorResolved.getAttributeValue("session"));
        editor.setAttribute("class", (clazz1 == null ? clazz2 : clazz1));
    }
}

From source file:org.xcri.types.DescriptiveTextType.java

License:Open Source License

@Override
public Element toXml() {
    Element element = super.toXml();
    if (this.getHref() != null)
        element.setAttribute("href", this.getHref());
    if (isXhtml) {
        ////from  w  ww . j  a  v  a 2  s.  c  o  m
        // Remove plain content
        //
        element.removeContent();
        //
        // Add XHTML
        //
        element.addContent(xhtml.detach());
    }
    return element;
}