Java Code Examples for org.jdom2.Element#getParentElement()

The following examples show how to use org.jdom2.Element#getParentElement() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private boolean handleBeforeAfter(Element container, Element includeRule, String attributeName, int offset,
    int defaultPos) {
    String refID = includeRule.getAttributeValue(attributeName);
    if (refID != null) {
        includeRule.removeAttribute(attributeName);

        Element parent = container;
        int pos = defaultPos;

        Optional<Element> neighbor = findDescendant(container, refID);
        if (neighbor.isPresent()) {
            Element n = neighbor.get();
            parent = n.getParentElement();
            List<Element> children = parent.getChildren();
            pos = children.indexOf(n) + offset;
        }

        LOGGER.debug("including  " + Arrays.toString(includeRule.getAttributes().toArray()) + " at pos " + pos);
        parent.getChildren().add(pos, includeRule.clone());
    }
    return refID != null;
}
 
Example 2
/**
 * Recursivly checks <code>relatedItem</code> and parent &lt;mods:relatedItem&gt; elements for multiple {@link MCRObjectID}s.
 * @param relatedItem &lt;mods:relatedItem&gt;
 * @param idCollected of IDs collected so far
 * @throws MCRPersistenceException if {@link MCRObjectID} of <code>relatedItem</code> is in <code>idCollected</code>
 */
private void checkHierarchy(Element relatedItem, Set<MCRObjectID> idCollected) throws MCRPersistenceException {
    final Attribute href = relatedItem.getAttribute("href", MCRConstants.XLINK_NAMESPACE);
    if (href != null) {
        final String testId = href.getValue();
        LOGGER.debug("Checking relatedItem {}.", testId);
        if (MCRObjectID.isValid(testId)) {
            final MCRObjectID relatedItemId = MCRObjectID.getInstance(testId);
            LOGGER.debug("Checking if {} is in {}.", relatedItemId, idCollected);
            if (!idCollected.add(relatedItemId)) {
                throw new MCRPersistenceException(
                    "Hierarchy of mods:relatedItem contains ciruit by object " + relatedItemId);
            }
        }
    }
    final Element parentElement = relatedItem.getParentElement();
    if (parentElement.getName().equals("relatedItem")) {
        checkHierarchy(parentElement, idCollected);
    }
}
 
Example 3
/**
 * Returns all labels of the ancestor axis for the given item within
 * navigation.xml
 *
 * @param item a navigation item
 * @return Label as String, like "labelRoot &gt; labelChild &gt;
 *         labelChildOfChild"
 */
public static String getAncestorLabels(Element item) {
    StringBuilder label = new StringBuilder();
    String lang = MCRSessionMgr.getCurrentSession().getCurrentLanguage().trim();
    XPathExpression<Element> xpath;
    Element ic = null;
    xpath = XPATH_FACTORY.compile("//.[@href='" + getWebpageID(item) + "']", Filters.element());
    ic = xpath.evaluateFirst(getNavi());
    while (ic.getName().equals("item")) {
        ic = ic.getParentElement();
        String webpageID = getWebpageID(ic);
        Element labelEl = null;
        xpath = XPATH_FACTORY.compile("//.[@href='" + webpageID + "']/label[@xml:lang='" + lang + "']",
            Filters.element());
        labelEl = xpath.evaluateFirst(getNavi());
        if (labelEl != null) {
            if (label.length() == 0) {
                label = new StringBuilder(labelEl.getTextTrim());
            } else {
                label.insert(0, labelEl.getTextTrim() + " > ");
            }
        }
    }
    return label.toString();
}
 
Example 4
/**
 * Verifies, if an item of navigation.xml has a given $permission.
 *
 * @param webpageID
 *            item/@href
 * @param permission
 *            permission to look for
 * @param strategy
 *            ALLTRUE =&gt; all ancestor items of webpageID must have the
 *            permission, ONETRUE_ALLTRUE =&gt; only 1 ancestor item must have
 *            the permission
 * @return true, if access, false if no access
 */
public static boolean getAccess(String webpageID, String permission, int strategy) {
    Element item = getItem(webpageID);
    // check permission according to $strategy
    boolean access = strategy == ALLTRUE;
    if (strategy == ALLTRUE) {
        while (item != null && access) {
            access = itemAccess(permission, item, access);
            item = item.getParentElement();
        }
    } else if (strategy == ONETRUE_ALLTRUE) {
        while (item != null && !access) {
            access = itemAccess(permission, item, access);
            item = item.getParentElement();
        }
    }
    return access;
}
 
Example 5
/**
 * Verifies, if an item of navigation.xml has a given $permission with a
 * stop item ($blockerWebpageID)
 *
 * @param webpageID
 *            item/@href
 * @param permission
 *            permission to look for
 * @param strategy
 *            ALL2BLOCKER_TRUE =&gt; all ancestor items of webpageID till and
 *            exlusiv $blockerWebpageID must have the permission
 * @param blockerWebpageID
 *            any ancestor item of webpageID from navigation.xml
 * @return true, if access, false if no access
 */
public static boolean getAccess(String webpageID, String permission, int strategy, String blockerWebpageID) {
    Element item = getItem(webpageID);
    // check permission according to $strategy
    boolean access = false;
    if (strategy == ALL2BLOCKER_TRUE) {
        access = true;
        String itemHref;
        do {
            access = itemAccess(permission, item, access);
            item = item.getParentElement();
            itemHref = getWebpageID(item);
        } while (item != null && access && !(itemHref != null && itemHref.equals(blockerWebpageID)));
    }
    return access;
}
 
Example 6
private static Calendar calcMsgTransferStartTime(Element msgTransfer) {
    Calendar cal = Calendar.getInstance();
    String msgUtilisationType = msgTransfer.getChildText(XML_MSGUTILISATIONTYPE);
    Element activity = msgTransfer.getParentElement();
    if (UTILISATION_TYPE_BEGIN.equals(msgUtilisationType)) {
        cal.setTime(XMLUtils.getDateValue(activity.getChild(XML_FROM), true));
    }
    else {
        cal.setTime(XMLUtils.getDateValue(activity.getChild(XML_TO), true));
    }
    int min = XMLUtils.getDurationValueInMinutes(
            msgTransfer.getChild(XML_MSGDURATION), true);
    if (MSGREL_BEFORE.equals(msgTransfer.getChildText(XML_MSGREL)))	{
        min = 0 - min;
    }
    cal.add(Calendar.MINUTE, min);
    return cal;
}
 
Example 7
/**
 * This method moves an element (entry-node or bullet-point) one position
 * up- or downwards, depending on the parameter {@code movement}.
 *
 * @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());
        }
    }
}
 
Example 8
/**
 * 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.
 *
 * @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;
}
 
Example 9
private static TIntList indexPath(Element child, int size) {
    final Element parent = child.getParentElement();
    if(parent == null) {
        return new TIntArrayList(size);
    } else {
        final TIntList path = indexPath(parent, size + 1);
        final int index = ((BoundedElement) child).indexInParent();
        if(index < 0) {
            throw new IllegalStateException("Parent element " + parent + " does not contain its child element " + child);
        }
        path.add(index);
        return path;
    }
}
 
Example 10
Source Project: mycore   File: MCRBinding.java    License: GNU General Public License v3.0 5 votes vote down vote up
public Element cloneBoundElement(int index) {
    Element template = (Element) (boundNodes.get(index));
    Element newElement = template.clone();
    Element parent = template.getParentElement();
    int indexInParent = parent.indexOf(template) + 1;
    parent.addContent(indexInParent, newElement);
    boundNodes.add(index + 1, newElement);
    trackNodeCreated(newElement);
    return newElement;
}
 
Example 11
private boolean isContainedByUnboundedElement(Element e, Element parentElement) {
    // we may be able to remove this method/logic as the SLI-Edfi schema overrides all types
    // that contain unbounded choice to remove them.
    Element immediateParent = e.getParentElement();
    while (!immediateParent.equals(parentElement)) {
        if (UNBOUNDED.equals(immediateParent.getAttributeValue(MAX_OCCURS))) {
            return true;
        }
        immediateParent = immediateParent.getParentElement();
    }
    return false;
}
 
Example 12
Source Project: rome   File: CCModuleGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void generate(final Module module, final Element element) {
    Element root = element;
    while (root.getParentElement() != null) {
        root = root.getParentElement();
    }
    if (root.getNamespace().equals(RDF) || root.getNamespace().equals(RSS)) {
        generateRSS1((CreativeCommons) module, element);
    } else {
        generateRSS2((CreativeCommons) module, element);
    }
}
 
Example 13
public Map<String, List<Element>> removeReservations(Document rup, String statusToBe)
           throws JDOMException {
	Map<String, List<Element>> res = new HashMap<String, List<Element>>();
	String where = statusToBe == null ? "" : "[" + XML_STATUSTOBE + "='" + statusToBe + "']";
	String xpath = XMLUtils.getXPATH_ActivityElement(null, XML_RESERVATION + where, null);
	List<Element> reservations = XMLUtils.getXMLObjects(rup, xpath);
	for (Element reservation : reservations) {
		Element activity = reservation.getParentElement();
		activity.removeContent(reservation);

		List<Element> l = res.get(activity.getChildText(XML_ACTIVITYNAME));
		if (l == null)	l = new ArrayList<Element>();

		Element reservationId = reservation.getChild(XML_RESERVATIONID);
		if (reservationId == null) {
			reservation.addContent(new Element(XML_RESERVATIONID));
		}
		else {
			reservationId.setText("");
		}

		l.add(reservation);
		res.put(activity.getChildText(XML_ACTIVITYNAME), l);
	}

	return res;
}
 
Example 14
private boolean isContainedByUnboundedElement(Element e, Element parentElement) {
    // we may be able to remove this method/logic as the SLI-Edfi schema overrides all types
    // that contain unbounded choice to remove them.
    Element immediateParent = e.getParentElement();
    while (!immediateParent.equals(parentElement)) {
        if (UNBOUNDED.equals(immediateParent.getAttributeValue(MAX_OCCURS))) {
            return true;
        }
        immediateParent = immediateParent.getParentElement();
    }
    return false;
}
 
Example 15
/**
 * Creates a new element with the same name and attributes as the old one
 * @param element the elment to clone
 * @param defNS the default namespace
 * @return the cloned element
 */
private Element cloneElement(Element element, Namespace defNS) {
    Element cloned = new Element(element.getName(), defNS);
    cloned.setAttributes(cloneAttributes(element, defNS));

    // clone appinfo children literally
    Element parent = element.getParentElement();
    if (parent != null && parent.getName().equals("appinfo")) {
        cloned.setText(element.getText());
    }
    return cloned;
}
 
Example 16
/**
 * This method adds a new entry (child-node) to the xml-document.
 *
 * @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 | IllegalDataException | IllegalAddException ex) {
            Constants.zknlogger.log(Level.WARNING, ex.getLocalizedMessage());
        }
    }
    return null;
}
 
Example 17
Source Project: CardinalPGM   File: FilterParser.java    License: MIT License 5 votes vote down vote up
public FilterParser(final Element element) {
    this.name =
            element.getAttributeValue("name") != null ? element.getAttributeValue("name") :
                    element.getAttributeValue("id") != null ? element.getAttributeValue("id") :
                            element.getParentElement() != null && element.getParentElement().getAttributeValue("name") != null ? element.getParentElement().getAttributeValue("name") :
                                    element.getParentElement() != null && element.getParentElement().getAttributeValue("id") != null ? element.getParentElement().getAttributeValue("id") : null;
    parent = null;
    if (element.getAttributeValue("parents") != null) {
        parent = FilterModuleBuilder.getFilter(element.getAttributeValue("parents"));
    } else if (element.getParentElement() != null && element.getParentElement().getAttributeValue("parents") != null) {
        parent = FilterModuleBuilder.getFilter(element.getParentElement().getAttributeValue("parents"));
    }
}
 
Example 18
public Element parseFromString(String text) {
  if (showRaw)
    System.out.println("Raw ODL=\n" + text);

  Element rootElem = new Element("odl");
  doc = new Document(rootElem);

  Element current = rootElem;
  StringTokenizer lineFinder = new StringTokenizer(text, "\t\n\r\f");
  while (lineFinder.hasMoreTokens()) {
    String line = lineFinder.nextToken();
    if (line == null)
      continue;

    if (line.startsWith("GROUP")) {
      current = startGroup(current, line);

    } else if (line.startsWith("OBJECT")) {
      current = startObject(current, line);

    } else if (line.startsWith("END_OBJECT")) {
      endObject(current, line);
      current = current.getParentElement();
      if (current == null)
        throw new IllegalStateException();

    } else if (line.startsWith("END_GROUP")) {
      endGroup(current, line);
      current = current.getParentElement();
      if (current == null)
        throw new IllegalStateException();

    } else {
      addField(current, line);
    }
  }

  if (show)
    showDoc(new PrintWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8)));
  return rootElem;
}
 
Example 19
@Override
protected boolean canIgnore(Element el) throws InvalidXMLException {
    return super.canIgnore(el) || (el.getName().equals("filter") &&
                                   el.getParentElement() != null &&
                                   "kit".equals(el.getParentElement().getName()));
}
 
Example 20
Source Project: Zettelkasten   File: Tools.java    License: GNU General Public License v3.0 4 votes vote down vote up
/**
 * 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.
 */
public static String prepareDoubleEntriesMessage(List<Object[]> list) {
    // retrieve system's line-separator
    String lineseparator = System.lineSeparator();
    // 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<>();
                // 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;
}