Example usage for org.jdom2 Element getParentElement

List of usage examples for org.jdom2 Element getParentElement

Introduction

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

Prototype

final public Element getParentElement() 

Source Link

Document

A convenience method that returns any parent element for this element, or null if the element is unattached or is a root element.

Usage

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

License:Open Source License

/**
 * This method moves an element (entry-node or bullet-point) one position up- or downwards, depending
 * on the parameter {@code movement}.//from w w w .ja  v a 2 s .c  o m
 * @param movement indicates whether the element should be moved up or down. use following constants:<br>
 * - {@code CConstants.MOVE_UP}<br>
 * - {@code CConstants.MOVE_DOWN}<br>
 * @param timestamp
 */
public void moveElement(int movement, String timestamp) {
    // get the selected element, independent from whether it's a node or a bullet
    Element e = findEntryElementFromTimestamp(getCurrentDesktopElement(), timestamp);
    if (e != null) {
        // get the element's parent
        Element p = e.getParentElement();
        // get the index of the element that should be moved
        int index = p.indexOf(e);
        // remove the element that should be moved
        Element dummy = (Element) p.removeContent(index);
        try {
            // and insert element one index-position below the previous index-position
            p.addContent((Constants.MOVE_UP == movement) ? index - 1 : index + 1, dummy);
            // change modifed state
            setModified(true);
        } catch (IllegalAddException ex) {
            Constants.zknlogger.log(Level.WARNING, ex.getLocalizedMessage());
        }
    }
}

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

License:Open Source License

/**
 * This method adds a new entry (child-node) to the xml-document.
 * //from  w w w.ja  va2  s. c  om
 * @param timestamp the timestamp of the element, where the entry "nr" should be inserted as new child
 * @param nr the entry-number of the entry that should be added
 * @param insertpos the position where the new entry should be inserted. necessary when we have already
 * more children and the entry should be inserted in between, at the beginning or end of the children-list.
 * @return the timestamp of the added entry-element as {@code String} or {@code null} if an error
 * occured.
 */
public String addEntry(String timestamp, String nr, int insertpos) {
    // find the bullet that is described in the treepath
    Element b = findEntryElementFromTimestamp(getCurrentDesktopElement(), timestamp);
    // if we have a valid bullet, add the new enry to the xml-file
    if (b != null) {
        // check whether element is a bullet, if not, retrieve its parent element
        if (!b.getName().equals(ELEMENT_BULLET))
            b = b.getParentElement();
        // create a new element
        Element e = new Element(ELEMENT_ENTRY);
        try {
            e.setAttribute("id", nr);
            // create timestamp
            String ts = Tools.getTimeStampWithMilliseconds();
            // check whether timestamp already exists. this is particulary the
            // case when a user adds several entries at once.
            while (timeStampExists(ts))
                ts = Tools.getTimeStampWithMilliseconds();
            // add timestamp to entry element
            e.setAttribute(ATTR_TIMESTAMP, ts);
            // add new enry to the bullet at insert-position+1 (because at first
            // position in the bullet is always the comment)
            b.addContent(insertpos, e);
            // change modified state
            setModified(true);
            // return timestamp
            return ts;
        } catch (IllegalNameException ex) {
            Constants.zknlogger.log(Level.WARNING, ex.getLocalizedMessage());
        } catch (IllegalDataException ex) {
            Constants.zknlogger.log(Level.WARNING, ex.getLocalizedMessage());
        } catch (IllegalAddException ex) {
            Constants.zknlogger.log(Level.WARNING, ex.getLocalizedMessage());
        }
    }
    return null;
}

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

License:Open Source License

/**
 * This method retrieves the level (depth) of an bullet-element within the tree-hierarchy. This
 * method can be used for example to determine the level of a heading, when exporting desktop-data.
 * /*from w w  w . j a  v  a2s. c om*/
 * @param t the timestamp which should match the timestamp-attribute of the entry-element
 * @return the level (depth) of the bullet within the tree-hierarchy as integer-value,
 * or -1 if an error occured;
 */
public int getBulletLevel(String t) {
    // retrieve requestes bullet-element
    Element el = findEntryElementFromTimestamp(getCurrentDesktopElement(), t);
    // init bullet-level
    int bulletlevel = -1;
    // check for valid returnvalue
    if (el != null) {
        // iterate parents
        while (el.getParentElement() != null) {
            // increase bullet-level
            bulletlevel++;
            // get parent-element
            el = el.getParentElement();
        }
    }
    return bulletlevel;
}

From source file:de.danielluedecke.zettelkasten.DesktopFrame.java

License:Open Source License

/**
 * This method retrieves all entries on the desktop and adds their number to the
 * list {@code liste}. This array of entry-numbers is needed in the export-dialog.
 *
 * @param e the starting point for the jTree-enumeration, either the root elementor a bullet (if only
 * a bullet should be exported, see {@link #exportDesktopBullet() exportDesktopBullet()}).
 * @param liste an array-object that will hold the found entry-nubers
 *//*from w ww  . j a v a 2  s.co  m*/
private void createExportEntries(Element e, ArrayList<Object> liste) {
    // if we have no element, return.
    if (null == e)
        return;
    // get a list with all children of the element
    List<Element> children = e.getChildren();
    // create an iterator
    Iterator<Element> it = children.iterator();
    // go through all children
    while (it.hasNext()) {
        // get the child
        e = it.next();
        // we have to ignore the comment-tags here. comments are no tags that will
        // be displayed in the jtree, but that store comments which will be displayed
        // in the jeditorpane (see "updateDisplay" method for further details)
        if (!e.getName().equals("comment")) {
            // if the child is a bullet...
            if (e.getName().equals("bullet")) {
                // first, we want to retrieve the header-level
                int headerlevel = 1;
                // get bullet's parent
                Element f = e.getParentElement();
                // as long as we have not reached the root, get further parent-elements
                // and increase counter for header-level
                while (!f.isRootElement()) {
                    f = f.getParentElement();
                    headerlevel++;
                }
                // add the element's name-attribute. since headers might consist of only numbers,
                // we add a char here. this is necessary, since the export-methods distinguish
                // between headers and entry-numbers simply by parsing integer-values. if the parsing
                // succeeds, we have an entry, if a NumberFormatException is thrown, we have a headline.
                // to treat headline with numbers only as headlines, we add a char to be sure that every
                // headline will throw an exception when parsing the array's elements to integer.
                liste.add("h" + String.valueOf(headerlevel) + e.getAttributeValue("name"));
            } else {
                // now we know we have an entry. so get the entry number...
                int nr = Integer.parseInt(e.getAttributeValue("id"));
                liste.add(nr);
            }
            // when the new element also has children, call this method again,
            // so we go through the strucuture recursively...
            if (desktopObj.hasChildren(e)) {
                createExportEntries(e, liste);
            }
        }
    }
}

From source file:de.danielluedecke.zettelkasten.util.Tools.java

License:Open Source License

/**
 * This method prepares a message that tells the user which entries already appear in the desktop, and
 * at which position. the complete message is returned as string.
 *
 * @param list a linked list which contains the multiple-entry-data. see
 * {@link #retrieveDoubleEntries(zettelkasten.CDesktopData, java.util.LinkedList) retrieveDoubleEntries(zettelkasten.CDesktopData, java.util.LinkedList)}
 * for more details on how this parameter is created. use the return result of this method as this parameter
 * @return a string with the message which entries are at which position in the desktop-data, or {@code null}
 * if no occurences appear./*from   w w w. j  av a 2 s. c o  m*/
 */
public static String prepareDoubleEntriesMessage(List<Object[]> list) {
    // retrieve system's line-separator
    String lineseparator = System.getProperty("line.separator");
    // get an iterator for the multiple entries and check
    // whether we have any multiple occurences at all. if yes,
    // tell the user about that
    Iterator<Object[]> i = list.iterator();
    // prepare a string builder that will contain the information-message in case
    // we have any multiple occurences of entries...
    StringBuilder multipleOccurencesMessage = new StringBuilder("");
    // go through all entries of the linked list and check
    // whether we have found anything
    while (i.hasNext()) {
        // get element
        Object[] desktopdata = i.next();
        // if second element in array is not null, we have a match. now retrieve
        // the entry's data, so we can inform the user about the
        // entry's details...
        if (desktopdata[1] != null) {
            // retrieve desktop name
            String dn = resourceMap.getString("multipleOccurencesDesktop") + " " + (String) desktopdata[0];
            StringBuilder dnsl = new StringBuilder("");
            // now we add a separator line, so check length of string
            for (int dnl = 0; dnl < dn.length(); dnl++)
                dnsl.append("-");
            // first, append desktop-name
            multipleOccurencesMessage.append(dn).append(lineseparator);
            multipleOccurencesMessage.append(dnsl.toString()).append(lineseparator);
            // now retrieve the elements...
            List<Element> elements = (ArrayList<Element>) desktopdata[1];
            // create iterator for each found element
            Iterator<Element> entryIterator = elements.iterator();
            // go through the found entries in that desktop
            while (entryIterator.hasNext()) {
                // get each found entry as element
                Element entry = entryIterator.next();
                // get the timestamp of the found entry
                String timestamp = entry.getAttributeValue("timestamp");
                // get the entrynumber of the found entry
                String id = entry.getAttributeValue("id");
                // create a linked list that will hold the path to the desktop
                List<String> path = new ArrayList<String>();
                // as long as the found element has parents, we have path-elements/information
                // to add...
                while (entry.getParentElement() != null) {
                    // retrieve parent-element
                    entry = entry.getParentElement();
                    // if it's a bullet, add the path-name to our path-list
                    if (entry.getName().equals("bullet")) {
                        path.add(0, entry.getAttributeValue("name"));
                    }
                }
                // now we can prepare the output string...
                multipleOccurencesMessage.append(
                        resourceMap.getString("multipleOccurencesMsg", id, getProperDate(timestamp, false)));
                multipleOccurencesMessage.append(lineseparator)
                        .append(resourceMap.getString("multipleOccurencesLevel")).append(" ");
                // go through the path-list and append all path-elements, so the user
                // knows where to find the entry
                for (int cnt = 0; cnt < path.size(); cnt++) {
                    // add path
                    multipleOccurencesMessage.append(path.get(cnt));
                    // as long as we have a path-element left, append a separating comma
                    if (cnt < path.size() - 1) {
                        multipleOccurencesMessage.append(" >>> ");
                    }
                }
                // append two line-separators for the next element...
                multipleOccurencesMessage.append(lineseparator).append(lineseparator);
            }
        }
    }
    // delete the last two trailing lineseparators
    if (multipleOccurencesMessage.length() > 0) {
        multipleOccurencesMessage.setLength(multipleOccurencesMessage.length() - 2 * lineseparator.length());
    }
    // if we have any content, return string. else return null
    return (multipleOccurencesMessage.length() > 0) ? multipleOccurencesMessage.toString() : null;
}

From source file:edu.unc.lib.dl.xml.DepartmentOntologyUtil.java

License:Apache License

/**
 * Compares the affiliation values in the given MODS document against the ontology. If a preferred term(s) is found,
 * then it will replace the original. Only the first and last terms in a single hierarchy are kept if there are more
 * than two levels/*ww  w.j  av a 2 s  .  c o m*/
 *
 * @param modsDoc
 * @return Returns true if the mods document was modified by adding or changing affiliations
 * @throws JDOMException
 */
@Override
public boolean updateDocumentTerms(Element docElement) throws JDOMException {
    List<?> nameObjs = namePath.evaluate(docElement);
    boolean modified = false;

    for (Object nameObj : nameObjs) {
        Element nameEl = (Element) nameObj;

        List<?> affiliationObjs = nameEl.getChildren("affiliation", MODS_V3_NS);
        if (affiliationObjs.size() == 0)
            continue;

        // Collect the set of all affiliations for this name so that it can be used to detect duplicates
        Set<String> affiliationSet = new HashSet<>();
        for (Object affiliationObj : affiliationObjs) {
            Element affiliationEl = (Element) affiliationObj;

            affiliationSet.add(affiliationEl.getTextNormalize());
        }

        // Make a snapshot of the list of affiliations so that the original can be modified
        List<?> affilList = new ArrayList<>(affiliationObjs);
        // Get the authoritative department path for each affiliation and overwrite the original
        for (Object affiliationObj : affilList) {
            Element affiliationEl = (Element) affiliationObj;
            String affiliation = affiliationEl.getTextNormalize();

            List<List<String>> departments = getAuthoritativeForm(affiliation);
            if (departments != null && departments.size() > 0) {

                Element parentEl = affiliationEl.getParentElement();
                int affilIndex = parentEl.indexOf(affiliationEl);

                boolean removeOriginal = true;
                // Add each path that matched the affiliation. There can be multiple if there were multiple parents
                for (List<String> deptPath : departments) {
                    String baseDept = deptPath.size() > 1 ? deptPath.get(0) : null;
                    String topDept = deptPath.get(deptPath.size() - 1);

                    // No need to remove the original if it is in the set of departments being added
                    if (affiliation.equals(topDept))
                        removeOriginal = false;

                    modified = addAffiliation(baseDept, parentEl, affilIndex, affiliationSet) || modified;
                    modified = addAffiliation(topDept, parentEl, affilIndex, affiliationSet) || modified;
                }

                // Remove the old affiliation unless it was already in the vocabulary
                if (removeOriginal)
                    parentEl.removeContent(affiliationEl);

            }
        }
    }

    return modified;
}

From source file:egovframework.rte.fdl.xml.AbstractXMLUtility.java

License:Apache License

/**
 * /*from  www. j  a  v a  2 s . c om*/
 * 
 * @param element - ? Element
 * @param name - 
 */
public void removeNode(Element element, String name) {
    List<?> list = element.getChildren();
    if (list.size() != 0) {
        for (int i = 0; i < list.size(); i++) {
            Element tmp = (Element) list.get(i);
            if (tmp.getName().equals(name)) {
                tmp.getParentElement().removeChild(name);
            } else {
                removeNode(tmp, name);
            }
        }
    } else {
        // Visit the children
        // logger.debug("element Name :"+element.getName());
        if (element.getName().equals(name)) {
            element.getParentElement().removeChild(name);
        }
    }
}

From source file:es.upm.dit.xsdinferencer.extraction.extractorImpl.TypesExtractorImpl.java

License:Apache License

/**
 * Returns a path of the element made of the name of the elements and their prefixes (or namespace URIs). 
 * Prefixes (or URIs) are separated from element names by :, so THEY MUST BE REPLACED BY _ if they are 
 * going to be used to build type names.
 * Note that the : WILL always appear, although there is not any namespace prefix.
 * If a solved namespace-prefix mapping is given, the prefix mapped to the namespace of the element will be used instead of the prefix of the element. 
 * @param element the element/*from  w  w w . j a v a 2s  . com*/
 * @param config current inference configuration
 * @param useURI if true, the URI is used to build the path, if false, the prefix is used
 * @param solvedNamespaceToPrefixMapping the solved mappings between the namespace URIs and prefixes
 * @return a list that represents the path. Each element of the list is a path element.
 * @throws NullPointerException if any argument is null
 */
public static List<String> getRealPathOfElementUnfiltered(Element element, XSDInferenceConfiguration config,
        boolean useURI, Map<String, String> solvedNamespaceToPrefixMapping) {
    checkNotNull(element, "'element' must not be null");
    checkNotNull(config, "'config' must not be null");
    LinkedList<String> path = new LinkedList<String>();
    Element currentElement = element;
    do {
        String e;
        if (useURI) {
            e = currentElement.getNamespaceURI() + ":" + currentElement.getName();
        } else {
            String effectivePrefix = solvedNamespaceToPrefixMapping != null
                    ? solvedNamespaceToPrefixMapping.get(currentElement.getNamespaceURI())
                    : currentElement.getNamespacePrefix();
            e = effectivePrefix + ":" + currentElement.getName();
        }
        path.addFirst(e);
    } while ((currentElement = currentElement.getParentElement()) != null);
    return path;
}

From source file:eu.himeros.hocr.HocrInfoAggregator.java

License:Open Source License

private void makeCompliantHocr() {
    xpath = XPathFactory.instance().compile("//ns:span[@id|@idx]", Filters.element(), null,
            Namespace.getNamespace("ns", "http://www.w3.org/1999/xhtml"));
    List<Element> elements = xpath.evaluate(root);
    int spanId = 0;
    for (Element span : elements) {
        if (span.getAttribute("idx") != null) {
            try {
                span = span.getChildren().get(0);
            } catch (Exception ex) {
                //
            }/* w ww  .  ja v  a  2s . c o m*/
        }
        LinkedList<Attribute> attributeLl = new LinkedList(span.getParentElement().getAttributes());
        attributeLl.addFirst(new Attribute("id", "w_" + spanId++));
        span.getParentElement().setAttributes(attributeLl);
        String[] suggestions = null;
        String title = span.getAttributeValue("title");
        if (title != null) {
            suggestions = title.split(" ");
        }
        if (suggestions == null) {
            suggestions = new String[] { "" };
        }
        Element ins = new Element("ins", xmlns);
        ins.setAttribute("class", "alt");
        ins.setAttribute("title", makeNlp(span.getAttributeValue("class")));
        ins.setText(span.getText());
        span.removeContent();
        span.addContent(ins);
        span.setAttribute("class", "alternatives");
        span.removeAttribute("uc");
        span.removeAttribute("occ");
        span.removeAttribute("title");
        span.removeAttribute("anchor");
        span.removeAttribute("anchor-id");
        span.removeAttribute("id");
        span.getParentElement().removeAttribute("idx");
        span.removeAttribute("whole");
        span.getParentElement().removeAttribute("whole");
        if (title == null || "".equals(title)) {
            continue;
        }
        double score = 0.90;
        for (String suggestion : suggestions) {
            if (suggestion == null || "".equals(suggestion)) {
                continue;
            }
            Element del = new Element("del", xmlns);
            del.setAttribute("title", "nlp " + String.format("%.2f", score).replaceAll(",", "."));
            score = score - 0.01;
            suggestion = suggestion.replaceAll(l1PunctMarkFilter, "");
            Matcher leftMatcher = l1LeftPunctMarkPattern.matcher(ins.getText());
            if (leftMatcher.matches()) {
                suggestion = leftMatcher.group(1) + suggestion;
            }
            Matcher rightMatcher = l1RightPunctMarkPattern.matcher(ins.getText());
            if (rightMatcher.matches()) {
                String ngtSymbol = "";
                if (suggestion.endsWith("\u261a")) {
                    ngtSymbol = "\u261a";
                    suggestion = suggestion.substring(0, suggestion.length() - 1);
                }
                suggestion = suggestion + rightMatcher.group(1) + ngtSymbol;
            }
            ///!!!!
            if (suggestion.endsWith("\u261a") && ins.getParentElement().getParentElement()
                    .getAttributeValue("lang", Namespace.XML_NAMESPACE) != null) {
                String buff = suggestion.substring(0, suggestion.length() - 1);
                sa.align(buff, ins.getText());
                double sim = 1 - sa.getEditDistance()
                        / Math.max((double) buff.length(), (double) ins.getText().length());
                if (sim > 0.6) {

                    suggestion = ins.getText() + "\u261b";
                    ins.setText(buff);
                    ins.setAttribute("title", "nlp 0.70");
                }
            }
            del.addContent(suggestion);
            span.addContent(del);
        }
    }
}

From source file:jodtemplate.pptx.postprocessor.StylePostprocessor.java

License:Apache License

private void processComment(final Comment comment, final Element at, final Slide slide,
        final Configuration configuration) throws JODTemplateException {
    String commentText = comment.getText();
    if (commentText.startsWith(STYLIZED_KEYWORD)) {
        commentText = StringUtils.removeStart(commentText, STYLIZED_KEYWORD);
        final String className = StringUtils.substringBefore(commentText, ":");
        commentText = StringUtils.removeStart(commentText, className + ": ");
        final Stylizer stylizer = configuration.getStylizer(className);
        if (stylizer == null) {
            throw new JODTemplateException("Unable to find stylizer");
        }//from www  .  jav  a 2s  .  co  m
        final String text = StringUtils.removeStart(commentText, " stylized: ");
        final Element ar = at.getParentElement();
        final Element ap = ar.getParentElement();
        final int arIndex = ap.indexOf(ar);
        final Element arPr = getArPrElement(ar);
        final Element apPr = getApPrElement(ap);
        final Element sourceApPr = ObjectUtils.clone(apPr);
        cleanApPrElement(apPr);

        final List<Element> stylizedElements = stylizer.stylize(text, arPr, apPr, slide);

        ap.removeContent(ar);
        final List<Element> remains = getRemainingElements(arIndex, ap);
        for (Element el : remains) {
            ap.removeContent(el);
        }

        final int currentApIndex = injectElementsInDocument(stylizedElements, ap, apPr, arIndex);
        injectRemainsInDocument(remains, ap, sourceApPr, currentApIndex);
    }
}