Example usage for org.jdom2 Element getParent

List of usage examples for org.jdom2 Element getParent

Introduction

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

Prototype

public Parent getParent() 

Source Link

Document

Return this child's parent, or null if this child is currently not attached.

Usage

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.mathml2html.FormulaConverter.java

License:Open Source License

/**
 * Replaces all formulas with the html representation of the mapped formula objects
 *
 * @param doc        JDOM Document where to replace the formulas
 * @param formulaMap Map of the indexed Formula Objects
 * @return JDOM Document with replaced formulas
 *//*from w  ww.j  a  va2  s .co m*/
public Document replaceFormulas(Document doc, Map<Integer, Formula> formulaMap) {
    List<Element> foundFormulas = xpath.evaluate(doc);

    if (foundFormulas.size() > 0) {
        Map<String, Element> formulaMarkupMap = new HashMap<>();

        // Initialize markup map
        for (Element element : foundFormulas) {
            formulaMarkupMap.put(element.getAttribute("id").getValue(), element);
        }

        // Replace all found formulas
        Iterator<Integer> formulaIterator = formulaMap.keySet().iterator();
        while (formulaIterator.hasNext()) {
            Integer id = formulaIterator.next();

            Element formulaMarkupRoot = formulaMarkupMap.get(FORMULA_ID_PREFIX + id);
            Formula formula = formulaMap.get(id);

            formulaMarkupRoot.removeAttribute("class");
            formulaMarkupRoot.removeContent();
            formulaMarkupRoot.setName("div");

            Element div = (Element) formulaMarkupRoot.getParent();
            div.setName("div");
            div.setAttribute("class", "formula");

            // Potentially there's text inside the paragraph...
            List<Text> texts = div.getContent(Filters.textOnly());
            if (texts.isEmpty() == false) {
                String textString = "";
                for (Text text : texts) {
                    textString += text.getText();
                }
                Element textSpan = new Element("span");
                textSpan.setAttribute("class", "text");
                textSpan.setText(textString);
                div.addContent(textSpan);

                List<Content> content = div.getContent();
                content.removeAll(texts);
            }

            if (generateDebugMarkup) {
                div.setAttribute("style", "border: 1px solid black;");

                // Header
                Element h4 = new Element("h4");
                h4.setText("DEBUG - Formula #" + formula.getId());
                div.addContent(h4);

                // Render LaTeX source
                Element latexPre = new Element("pre");
                latexPre.setAttribute("class", "debug-latex");
                latexPre.setText(formula.getLatexCode());
                div.addContent(latexPre);

                // Render MathML markup
                Element mathmlPre = new Element("pre");
                mathmlPre.setAttribute("class", "debug-mathml");
                mathmlPre.setText(formula.getMathMl());
                div.addContent(mathmlPre);

                // Render HTML Markup
                Element htmlPre = new Element("pre");
                htmlPre.setAttribute("class", "debug-html");
                XMLOutputter xmlOutputter = new XMLOutputter();
                xmlOutputter.setFormat(Format.getRawFormat());
                htmlPre.setText(xmlOutputter.outputString(formula.getHtml()));

                div.addContent(htmlPre);

            }

            // Set formula into
            formulaMarkupRoot.addContent(formula.getHtml());
        }
    }
    return doc;
}

From source file:com.rometools.modules.content.io.ContentModuleGenerator.java

License:Open Source License

@Override
public void generate(final com.rometools.rome.feed.module.Module module, final org.jdom2.Element element) {
    // this is not necessary, it is done to avoid the namespace definition in every item.
    Element root = element;

    while (root.getParent() != null && root.getParent() instanceof Element) {
        root = (Element) root.getParent();
    }//w  ww.  j av  a 2  s .c  o m

    root.addNamespaceDeclaration(CONTENT_NS);

    if (!(module instanceof ContentModule)) {
        return;
    }

    final ContentModule cm = (ContentModule) module;

    final List<String> encodeds = cm.getEncodeds();

    if (encodeds != null) {
        LOG.debug("{}", cm.getEncodeds().size());
        for (int i = 0; i < encodeds.size(); i++) {
            element.addContent(generateCDATAElement("encoded", encodeds.get(i).toString()));
        }
    }

    final List<ContentItem> contentItems = cm.getContentItems();

    if (contentItems != null && !contentItems.isEmpty()) {
        final Element items = new Element("items", CONTENT_NS);
        final Element bag = new Element("Bag", RDF_NS);
        items.addContent(bag);

        for (int i = 0; i < contentItems.size(); i++) {
            final ContentItem contentItem = contentItems.get(i);
            final Element li = new Element("li", RDF_NS);
            final Element item = new Element("item", CONTENT_NS);

            if (contentItem.getContentAbout() != null) {
                final Attribute about = new Attribute("about", contentItem.getContentAbout(), RDF_NS);
                item.setAttribute(about);
            }

            if (contentItem.getContentFormat() != null) {
                // LOG.debug( "Format");
                final Element format = new Element("format", CONTENT_NS);
                final Attribute formatResource = new Attribute("resource", contentItem.getContentFormat(),
                        RDF_NS);
                format.setAttribute(formatResource);

                item.addContent(format);
            }

            if (contentItem.getContentEncoding() != null) {
                // LOG.debug( "Encoding");
                final Element encoding = new Element("encoding", CONTENT_NS);
                final Attribute encodingResource = new Attribute("resource", contentItem.getContentEncoding(),
                        RDF_NS);
                encoding.setAttribute(encodingResource);
                item.addContent(encoding);
            }

            if (contentItem.getContentValue() != null) {
                final Element value = new Element("value", RDF_NS);

                if (contentItem.getContentValueParseType() != null) {
                    final Attribute parseType = new Attribute("parseType",
                            contentItem.getContentValueParseType(), RDF_NS);
                    value.setAttribute(parseType);
                }

                if (contentItem.getContentValueNamespaces() != null) {
                    final List<Namespace> namespaces = contentItem.getContentValueNamespaces();

                    for (int ni = 0; ni < namespaces.size(); ni++) {
                        value.addNamespaceDeclaration(namespaces.get(ni));
                    }
                }

                final List<Content> detached = new ArrayList<Content>();

                for (int c = 0; c < contentItem.getContentValueDOM().size(); c++) {
                    detached.add(contentItem.getContentValueDOM().get(c).clone().detach());
                }

                value.setContent(detached);
                item.addContent(value);
            } // end value

            li.addContent(item);
            bag.addContent(li);
        } // end contentItems loop

        element.addContent(items);
    }
}

From source file:com.rometools.modules.georss.GMLGenerator.java

License:Apache License

@Override
public void generate(final Module module, final Element element) {
    // this is not necessary, it is done to avoid the namespace definition
    // in every item.
    Element root = element;
    while (root.getParent() != null && root.getParent() instanceof Element) {
        root = (Element) element.getParent();
    }//from   w ww .  jav  a2 s . c o  m
    root.addNamespaceDeclaration(GeoRSSModule.SIMPLE_NS);
    root.addNamespaceDeclaration(GeoRSSModule.GML_NS);

    final Element whereElement = new Element("where", GeoRSSModule.SIMPLE_NS);
    element.addContent(whereElement);

    final GeoRSSModule geoRSSModule = (GeoRSSModule) module;
    final AbstractGeometry geometry = geoRSSModule.getGeometry();

    if (geometry instanceof Point) {
        final Position pos = ((Point) geometry).getPosition();

        final Element pointElement = new Element("Point", GeoRSSModule.GML_NS);
        whereElement.addContent(pointElement);

        final Element posElement = new Element("pos", GeoRSSModule.GML_NS);
        posElement.addContent(String.valueOf(pos.getLatitude()) + " " + String.valueOf(pos.getLongitude()));
        pointElement.addContent(posElement);
    }

    else if (geometry instanceof LineString) {
        final PositionList posList = ((LineString) geometry).getPositionList();

        final Element lineElement = new Element("LineString", GeoRSSModule.GML_NS);
        lineElement.addContent(createPosListElement(posList));
        whereElement.addContent(lineElement);
    } else if (geometry instanceof Polygon) {
        final Element polygonElement = new Element("Polygon", GeoRSSModule.GML_NS);
        {
            final AbstractRing ring = ((Polygon) geometry).getExterior();
            if (ring instanceof LinearRing) {
                final Element exteriorElement = new Element("exterior", GeoRSSModule.GML_NS);
                polygonElement.addContent(exteriorElement);
                final Element ringElement = new Element("LinearRing", GeoRSSModule.GML_NS);
                exteriorElement.addContent(ringElement);
                ringElement.addContent(createPosListElement(((LinearRing) ring).getPositionList()));

            } else {
                System.err
                        .println("GeoRSS GML format can't handle rings of type: " + ring.getClass().getName());
            }
        }
        final List<AbstractRing> interiorList = ((Polygon) geometry).getInterior();
        final Iterator<AbstractRing> it = interiorList.iterator();
        while (it.hasNext()) {
            final AbstractRing ring = it.next();
            if (ring instanceof LinearRing) {
                final Element interiorElement = new Element("interior", GeoRSSModule.GML_NS);
                polygonElement.addContent(interiorElement);
                final Element ringElement = new Element("LinearRing", GeoRSSModule.GML_NS);
                interiorElement.addContent(ringElement);
                ringElement.addContent(createPosListElement(((LinearRing) ring).getPositionList()));

            } else {
                System.err
                        .println("GeoRSS GML format can't handle rings of type: " + ring.getClass().getName());
            }
        }
        whereElement.addContent(polygonElement);
    } else if (geometry instanceof Envelope) {
        final Envelope envelope = (Envelope) geometry;
        final Element envelopeElement = new Element("Envelope", GeoRSSModule.GML_NS);
        whereElement.addContent(envelopeElement);

        final Element lowerElement = new Element("lowerCorner", GeoRSSModule.GML_NS);
        lowerElement.addContent(
                String.valueOf(envelope.getMinLatitude()) + " " + String.valueOf(envelope.getMinLongitude()));
        envelopeElement.addContent(lowerElement);

        final Element upperElement = new Element("upperCorner", GeoRSSModule.GML_NS);
        upperElement.addContent(
                String.valueOf(envelope.getMaxLatitude()) + " " + String.valueOf(envelope.getMaxLongitude()));
        envelopeElement.addContent(upperElement);

    } else {
        System.err
                .println("GeoRSS GML format can't handle geometries of type: " + geometry.getClass().getName());
    }
}

From source file:com.rometools.modules.georss.SimpleGenerator.java

License:Apache License

@Override
public void generate(final Module module, final Element element) {
    // this is not necessary, it is done to avoid the namespace definition
    // in every item.
    Element root = element;
    while (root.getParent() != null && root.getParent() instanceof Element) {
        root = (Element) element.getParent();
    }// w ww.j ava 2  s.  c  o  m
    root.addNamespaceDeclaration(GeoRSSModule.SIMPLE_NS);

    final GeoRSSModule geoRSSModule = (GeoRSSModule) module;

    final AbstractGeometry geometry = geoRSSModule.getGeometry();
    if (geometry instanceof Point) {
        final Position pos = ((Point) geometry).getPosition();

        final Element pointElement = new Element("point", GeoRSSModule.SIMPLE_NS);
        pointElement.addContent(pos.getLatitude() + " " + pos.getLongitude());
        element.addContent(pointElement);
    } else if (geometry instanceof LineString) {
        final PositionList posList = ((LineString) geometry).getPositionList();

        final Element lineElement = new Element("line", GeoRSSModule.SIMPLE_NS);

        lineElement.addContent(posListToString(posList));
        element.addContent(lineElement);
    } else if (geometry instanceof Polygon) {
        final AbstractRing ring = ((Polygon) geometry).getExterior();
        if (ring instanceof LinearRing) {
            final PositionList posList = ((LinearRing) ring).getPositionList();
            final Element polygonElement = new Element("polygon", GeoRSSModule.SIMPLE_NS);

            polygonElement.addContent(posListToString(posList));
            element.addContent(polygonElement);
        } else {
            LOG.error("GeoRSS simple format can't handle rings of type: " + ring.getClass().getName());
        }
        if (((Polygon) geometry).getInterior() != null && !((Polygon) geometry).getInterior().isEmpty()) {
            LOG.error("GeoRSS simple format can't handle interior rings (ignored)");
        }
    } else if (geometry instanceof Envelope) {
        final Envelope envelope = (Envelope) geometry;
        final Element boxElement = new Element("box", GeoRSSModule.SIMPLE_NS);
        boxElement.addContent(envelope.getMinLatitude() + " " + envelope.getMinLongitude() + " "
                + envelope.getMaxLatitude() + " " + envelope.getMaxLongitude());
        element.addContent(boxElement);
    } else {
        LOG.error("GeoRSS simple format can't handle geometries of type: " + geometry.getClass().getName());
    }
}

From source file:com.rometools.modules.georss.W3CGeoGenerator.java

License:Apache License

@Override
public void generate(final Module module, final Element element) {
    // this is not necessary, it is done to avoid the namespace definition
    // in every item.
    Element root = element;
    while (root.getParent() != null && root.getParent() instanceof Element) {
        root = (Element) element.getParent();
    }//w w  w .ja v a  2s .  co  m
    root.addNamespaceDeclaration(GeoRSSModule.W3CGEO_NS);

    Element pointElement = element;
    if (!isShort) {
        pointElement = new Element("Point", GeoRSSModule.W3CGEO_NS);
        element.addContent(pointElement);
    }

    final GeoRSSModule geoRSSModule = (GeoRSSModule) module;
    final AbstractGeometry geometry = geoRSSModule.getGeometry();

    if (geometry instanceof Point) {
        final Position pos = ((Point) geometry).getPosition();

        final Element latElement = new Element("lat", GeoRSSModule.W3CGEO_NS);
        latElement.addContent(String.valueOf(pos.getLatitude()));
        pointElement.addContent(latElement);
        final Element lngElement = new Element("long", GeoRSSModule.W3CGEO_NS);
        lngElement.addContent(String.valueOf(pos.getLongitude()));
        pointElement.addContent(lngElement);
    } else {
        System.err.println("W3C Geo format can't handle geometries of type: " + geometry.getClass().getName());
    }
}

From source file:com.rometools.modules.itunes.io.ITunesGenerator.java

License:Open Source License

@Override
public void generate(final Module module, final Element element) {
    Element root = element;

    while (root.getParent() != null && root.getParent() instanceof Element) {
        root = (Element) root.getParent();
    }/*from w  ww  .  j a v  a  2s .  c  o  m*/

    root.addNamespaceDeclaration(NAMESPACE);

    if (!(module instanceof AbstractITunesObject)) {
        return;
    }

    final AbstractITunesObject itunes = (AbstractITunesObject) module;

    if (itunes instanceof FeedInformationImpl) {
        // Do Channel Specific Stuff.
        final FeedInformationImpl info = (FeedInformationImpl) itunes;
        final Element owner = generateSimpleElement("owner", "");
        final Element email = generateSimpleElement("email", info.getOwnerEmailAddress());
        owner.addContent(email);

        final Element name = generateSimpleElement("name", info.getOwnerName());
        owner.addContent(name);
        element.addContent(owner);

        if (info.getImage() != null) {
            final Element image = generateSimpleElement("image", "");
            image.setAttribute("href", info.getImage().toExternalForm());
            element.addContent(image);
        }

        final List<Category> categories = info.getCategories();
        for (final Category cat : categories) {

            final Element category = generateSimpleElement("category", "");
            category.setAttribute("text", cat.getName());

            if (cat.getSubcategory() != null) {
                final Element subcat = generateSimpleElement("category", "");
                subcat.setAttribute("text", cat.getSubcategory().getName());
                category.addContent(subcat);
            }

            element.addContent(category);
        }
    } else if (itunes instanceof EntryInformationImpl) {
        final EntryInformationImpl info = (EntryInformationImpl) itunes;

        if (info.getDuration() != null) {
            element.addContent(generateSimpleElement("duration", info.getDuration().toString()));
        }
    }

    if (itunes.getAuthor() != null) {
        element.addContent(generateSimpleElement("author", itunes.getAuthor()));
    }

    if (itunes.getBlock()) {
        element.addContent(generateSimpleElement("block", ""));
    }

    if (itunes.getExplicit()) {
        element.addContent(generateSimpleElement("explicit", "yes"));
    } else {
        element.addContent(generateSimpleElement("explicit", "no"));
    }

    if (itunes.getKeywords() != null) {
        final StringBuffer sb = new StringBuffer();

        for (int i = 0; i < itunes.getKeywords().length; i++) {
            if (i != 0) {
                sb.append(", ");
            }

            sb.append(itunes.getKeywords()[i]);
        }

        element.addContent(generateSimpleElement("keywords", sb.toString()));
    }

    if (itunes.getSubtitle() != null) {
        element.addContent(generateSimpleElement("subtitle", itunes.getSubtitle()));
    }

    if (itunes.getSummary() != null) {
        element.addContent(generateSimpleElement("summary", itunes.getSummary()));
    }
}

From source file:com.rometools.modules.opensearch.impl.OpenSearchModuleParser.java

License:Apache License

/** Use feed links and/or xml:base attribute to determine baseURI of feed */
private static URL findBaseURI(final Element root) {
    URL baseURI = null;//from   w ww.  j a  v a 2 s .c  o  m
    final List<Element> linksList = root.getChildren("link", OS_NS);
    if (linksList != null) {
        for (final Element element : linksList) {
            final Element link = element;
            if (!root.equals(link.getParent())) {
                break;
            }
            String href = link.getAttribute("href").getValue();
            if (link.getAttribute("rel", OS_NS) == null
                    || link.getAttribute("rel", OS_NS).getValue().equals("alternate")) {
                href = resolveURI(null, link, href);
                try {
                    baseURI = new URL(href);
                    break;
                } catch (final MalformedURLException e) {
                    System.err.println("Base URI is malformed: " + href);
                }
            }
        }
    }
    return baseURI;
}

From source file:cz.muni.fi.mir.mathmlcanonicalization.modules.MrowNormalizer.java

License:Apache License

/**
 * Removes a mrow element if possible.//  ww  w .jav a 2 s.com
 *
 * @param mrowElement the mrow element
 */
private void checkRemoval(final Element mrowElement) {
    assert mrowElement != null && mrowElement.getName().equals(ROW);
    final Parent parent = mrowElement.getParent();
    if (!(parent instanceof Element)) {
        return; // no parent element
    }
    final Element parentElement = (Element) parent;
    final List<Element> children = mrowElement.getChildren();

    if (children.size() <= 1) {
        removeElement(mrowElement, parentElement);
        LOGGER.log(Level.FINE, "Element {0} removed", mrowElement);
        return;
    }

    final String childCountPropertyName = CHILD_COUNT_PREFIX + parentElement.getName();
    if (!isProperty(childCountPropertyName)) {
        return; // unknown parent element
    }
    final String childCountProperty = getProperty(childCountPropertyName);
    final int childCount;
    try {
        childCount = Integer.parseInt(childCountProperty);
    } catch (NumberFormatException e) {
        LOGGER.log(Level.WARNING, "{0} must be an integer, property ignored", childCountProperty);
        return;
    }

    if (childCount == 1 || // parent can accept any number of elements so we can remove mrow
            children.size() + parentElement.getChildren().size() - 1 == childCount) {
        removeElement(mrowElement, parentElement);
    }
}

From source file:cz.muni.fi.mir.mathmlcanonicalization.modules.MrowNormalizer.java

License:Apache License

/**
 * Add mrow if necessary//w  w w .ja  v a 2s. c  o  m
 */
private void checkAddition(final Element element) {
    assert element != null;
    final Parent parent = element.getParent();
    if (!(parent instanceof Element)) {
        return;
    }
    final Element parentElement = (Element) parent;
    final List<Element> siblings = parentElement.getChildren();

    if (isParenthesis(element, OPENING)) {
        // Need to find matching closing par and register the elements between
        int nesting = 0;

        // list of elements inside parentheses
        final List<Element> fenced = new ArrayList<Element>();

        for (int i = siblings.indexOf(element) + 1; i < siblings.size(); i++) {
            final Element current = siblings.get(i);

            if (isParenthesis(current, OPENING)) {
                nesting++; // opening parenthase reached
            } else if (isParenthesis(current, CLOSING)) { // closing parenthase reached
                if (nesting == 0) {
                    // matching closing parenthase
                    wrapFenced(siblings, fenced, element, current);
                    break;
                } else {
                    nesting--;
                }
            }
            fenced.add(current);
        }
    }
}

From source file:de.danielluedecke.zettelkasten.database.DesktopData.java

License:Open Source License

/**
 * This method removes all entries which entry-number are passed in the int-array {@code entries}
 * from all available desktop-elements./*from   w  w  w.  j  av  a  2 s .  c  o m*/
 * 
 * @param entries an integer-array containing the entry-numbers of those entries that should be
 * removed from the desktop
 * @return 
 */
public boolean deleteEntries(int[] entries) {
    // indicator for deletes entries
    boolean haveDeletedEntries = false;
    // check for valid parameter
    if (entries != null && entries.length > 0 && getCount() > 0) {
        // create linked list which will contain all to be deleted entries...
        LinkedList<Element> finallist = new LinkedList<Element>();
        // go through all desktops (outer loop)...
        for (int cnt = 0; cnt < getCount(); cnt++) {
            // ...and search for all entries in each desktop (inner loop)
            for (int e : entries) {
                // retrieve all found entries within the desktop
                LinkedList<Element> lle = searchForEntry(cnt, e);
                // check whether we have any returned entries...
                if (lle != null && lle.size() > 0) {
                    // create a new iterator for the found results
                    Iterator<Element> prepare = lle.iterator();
                    // iterate them
                    while (prepare.hasNext()) {
                        // get each single entry as element
                        Element entry = prepare.next();
                        // and add it to the final list
                        if (entry != null)
                            finallist.add(entry);
                    }
                }
            }
        }
        // if we found any elements that should be deleted, do
        // this now...
        if (finallist.size() > 0) {
            // create iterator
            Iterator<Element> i = finallist.iterator();
            // go trhough linked list
            while (i.hasNext()) {
                // get each element that should be deleted
                Element entry = i.next();
                // if we have a valid element, go on...
                if (entry != null) {
                    // retrieve timestamp
                    String timestamp = entry.getAttributeValue(ATTR_TIMESTAMP);
                    // check whether we have any modified entry. if so, delete it, since
                    // we no longer need it...
                    deleteModifiedEntry(timestamp);
                    // get the entry's parent
                    Parent p = entry.getParent();
                    // remove entry from parent
                    p.removeContent(entry);
                    // set deleted-indicator to true
                    haveDeletedEntries = true;
                }
            }
        }
    }
    // change modified state
    if (haveDeletedEntries)
        setModified(true);
    // return result
    return haveDeletedEntries;
}