Example usage for org.jdom2 Element removeChildren

List of usage examples for org.jdom2 Element removeChildren

Introduction

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

Prototype

public boolean removeChildren(final String cname) 

Source Link

Document

This removes all child elements (one level deep) with the given local name and belonging to no namespace.

Usage

From source file:com.ohnosequences.xml.model.go.GoTermXML.java

License:Open Source License

public void setProteinAnnotationLeadingToSlimTerm(GoTermXML goTerm) {
    initProteinAnnotationLeadingToSlimTermTag();
    Element elem = this.root.getChild(PROTEIN_ANNOTATION_LEADING_TO_SLIM_TERM);
    elem.removeChildren(GoTermXML.TAG_NAME);
    elem.addContent(goTerm.asJDomElement());
}

From source file:com.ohnosequences.xml.model.PredictedGene.java

License:Open Source License

public void setStartCodon(Codon codon) {
    initStartCodonTag();/*from  w w w .  j  a v  a  2 s  .c om*/
    Element temp = root.getChild(START_CODON_TAG_NAME);
    temp.removeChildren(Codon.TAG_NAME);
    temp.addContent(codon.getRoot());
}

From source file:com.ohnosequences.xml.model.PredictedGene.java

License:Open Source License

public void setStopCodon(Codon codon) {
    initStopCodonTag();//from  ww  w .ja  v  a2s.  co m
    Element temp = root.getChild(STOP_CODON_TAG_NAME);
    temp.removeChildren(Codon.TAG_NAME);
    temp.addContent(codon.getRoot());
}

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

License:Open Source License

/**
 * This method changed an existing entry in the datafile. The needed parameters come from the JDialog
 * "CNewEntry.java". This dialog opens an edit-mask so the user can input the necessary information.
 * If everything is done, the JDialog retrieves all the information as string(-array)-variables
 * and simply passes these as paramaters to this method.
 * <br>/*from ww  w . j  a  v a2  s  .  c  o  m*/
 * <br>
 * What we have to do here is to check whether the keywords or links e.g. partly exist, and if so,
 * find out the related index number. Keywords which until now do not already exist in the keyword
 * file have to be added to the keyword file and the new index number has to be addes to the
 * keyword-element of the entry. and so on...
 * 
 * @param title the entry's title as string
 * @param content the entry's content as string
 * @param authors the entry's authors as string-array, retrieve index number and add it to the entry's author-element
 * @param keywords the entry's keywords as string-array. retrieve index numbers and add those to the entry's keyword-element
 * @param remarks the remarks as string
 * @param links the entry's links as string
 * @param timestamp the current date. in this case, add it as edit date to the timestamp
 * @param entrynumber the number of the entry that should be changed.
 * @return 
 */
public boolean changeEntry(String title, String content, String[] authors, String[] keywords, String remarks,
        String[] links, String timestamp, int entrynumber) {
    // create a new zettel-element
    Element zettel = retrieveElement(zknFile, entrynumber);
    // create dummy element
    Element child;
    // if no entry exists, quit
    if (null == zettel)
        return false;
    // first of all, we remove all authors and keywords from the existing entry
    // we do this to update the frequency of the authors and keywords, so when adding
    // authors/keywords to the data-file, which already belonged to the entry, we would
    // increase the frequency although those authors/keywords are not new
    changeFrequencies(entrynumber, -1);
    // then, create form-images
    createFormImagesFromContent(content);
    try {
        //
        // change title
        //
        // retrieve the element
        child = zettel.getChild(ELEMENT_TITLE);
        // if child-element doesn't exist, add it to the zettel
        if (null == child) {
            // create new child element
            child = new Element(ELEMENT_TITLE);
            // and add it
            zettel.addContent(child);
        }
        // set value of the child element
        child.setText(title);
        //
        // change content
        //
        // retrieve the element
        child = zettel.getChild(ELEMENT_CONTENT);
        // if child-element doesn't exist, add it to the zettel
        if (null == child) {
            // create new child element
            child = new Element(ELEMENT_CONTENT);
            // and add it
            zettel.addContent(child);
        }
        // set value of the child element
        child.setText(content);
        //
        // change author
        //
        // retrieve the element
        child = zettel.getChild(ELEMENT_AUTHOR);
        // if child-element doesn't exist, add it to the zettel
        if (null == child) {
            // create new child element
            child = new Element(ELEMENT_AUTHOR);
            // and add it
            zettel.addContent(child);
        }
        // create empty string buffer which stores the index numbers
        // of the converted authors
        StringBuilder newau = new StringBuilder("");
        // check whether we have authors at all
        if ((authors != null) && (authors.length > 0)) {
            // iterate the array and get the index number of each author string
            // if a keauthoryword does not already exist, add it to the authorfile
            for (String aut : authors) {
                // trim leading and trailing spaces
                aut = aut.trim();
                // only proceed for this entry, if it contains a value
                if (!aut.isEmpty()) {
                    // add it to the data file
                    // and store the position of the new added author in the
                    // variable authorPos
                    int authorPos = addAuthor(aut, 1);
                    // append the index number in the string buffer
                    newau.append(String.valueOf(authorPos));
                    // separator for the the index numbers, since more authors
                    // and thus more index numbers might be stored in the author element
                    newau.append(",");
                }
            }
            // shorten the stringbuffer by one char, since we have a
            // superfluous comma char (see for-loop above)
            if (newau.length() > 0)
                newau.setLength(newau.length() - 1);
        }
        // store author index numbers
        child.setText(newau.toString());
        //
        // change keywords
        //
        // retrieve the element
        child = zettel.getChild(ELEMENT_KEYWORD);
        // if child-element doesn't exist, add it to the zettel
        if (null == child) {
            // create new child element
            child = new Element(ELEMENT_KEYWORD);
            // and add it
            zettel.addContent(child);
        }
        // create empty string buffer which stores the index numbers
        // of the converted keywords
        StringBuilder newkw = new StringBuilder("");
        // check whether we have keywords at all
        if ((keywords != null) && (keywords.length > 0)) {
            // iterate the array and get the index number of each keyword string
            // if a keyword does not already exist, add it to the keywordfile
            for (String keyw : keywords) {
                // trim leading and trailing spaces
                keyw = keyw.trim();
                // only proceed for this entry, if it contains a value
                if (!keyw.isEmpty()) {
                    // add it to the data file
                    // and store the position of the new added keyword in the
                    // variable keywordPos
                    int keywordPos = addKeyword(keyw, 1);
                    // append the index number in the string buffer
                    newkw.append(String.valueOf(keywordPos));
                    // separator for the the index numbers, since more keywords
                    // and thus more index numbers might be stored in the keyword element
                    newkw.append(",");
                }
            }
            // shorten the stringbuffer by one char, since we have a
            // superfluous comma char (see for-loop above)
            if (newkw.length() > 0)
                newkw.setLength(newkw.length() - 1);
        }
        // store keyword index numbers
        child.setText(newkw.toString());
        //
        // change manual links
        //
        addManualLink(entrynumber, extractManualLinksFromContent(content));
        //
        // change hyperlinks
        //
        // retrieve the element
        child = zettel.getChild(ELEMENT_ATTACHMENTS);
        // if child-element doesn't exist, add it to the zettel
        if (null == child) {
            // create new child element
            child = new Element(ELEMENT_ATTACHMENTS);
            // and add it
            zettel.addContent(child);
        }
        // first, remove all existing links, since they are completely
        // set again
        child.removeChildren(ELEMENT_ATTCHILD);
        // add each hyperlink string
        // therefor, iterate the array
        for (String l : links) {
            // create a new subchuld-element
            Element sublink = new Element(ELEMENT_ATTCHILD);
            // and add the link-string from the array
            sublink.setText(l);
            child.addContent(sublink);
        }
        //
        // change remarks
        //
        // retrieve the element
        child = zettel.getChild(ELEMENT_REMARKS);
        // if child-element doesn't exist, add it to the zettel
        if (null == child) {
            // create new child element
            child = new Element(ELEMENT_REMARKS);
            // and add it
            zettel.addContent(child);
        }
        // set value of the content element
        child.setText(remarks);
        //
        // change timestamp
        //
        setTimestampEdited(zettel, timestamp);
        //
        // we don't need any changes on the luhmann number or for
        // manual links here...
        //
        // update the current zettel-position
        zettelPos = entrynumber;
        // and add the new position to the history...
        addToHistory();
        // set modified state
        setModified(true);
    } catch (IllegalAddException ex) {
        Constants.zknlogger.log(Level.SEVERE, ex.getLocalizedMessage());
        return false;
    } catch (IllegalDataException ex) {
        Constants.zknlogger.log(Level.SEVERE, ex.getLocalizedMessage());
        return false;
    }
    return true;
}

From source file:edu.ucla.loni.server.ServerUtils.java

License:Open Source License

/**
 * Updates a Document (XML file) with all the attributes from a Pipefile
 * @throws Exception /*from ww  w . j a va 2s . c  om*/
 */
public static Document updateXML(Document doc, Pipefile pipe) throws Exception {
    Element main = getMainElement(doc);

    // Update name (attribute)
    main.setAttribute("name", pipe.name);
    // Update package (attribute)
    main.setAttribute("package", pipe.packageName);
    // Update description (attribute)
    main.setAttribute("description", pipe.description);

    // Update the tags (children)
    main.removeChildren("tag"); // Remove all old tags
    String tags = pipe.tags;
    if (tags != null && tags.length() > 0) {
        String[] tagArray = tags.split(",");
        for (String tag : tagArray) {
            Element child = new Element("tag");
            child.setText(tag);
            main.addContent(child);
        }
    }

    if (pipe.type.equals("Data")) {
        // Update values (values child => children)
        Element valuesElement = main.getChild("values");
        if (valuesElement == null) {
            valuesElement = new Element("values");
            main.addContent(valuesElement);
        }

        valuesElement.removeChildren("value"); // Remove all old values

        String values = pipe.values;
        if (values != null && values.length() > 0) {
            String[] valueArray = values.split("\n");
            for (String value : valueArray) {
                Element valueElement = new Element("value");
                valueElement.setText(value);
                valuesElement.addContent(valueElement);
            }
        }

        // Update formatType (output child => format child => attribute)
        Element output = main.getChild("output");
        if (output == null) {
            output = new Element("output");
            main.addContent(output);
        }

        Element format = output.getChild("format");
        if (format == null) {
            format = new Element("format");
            main.addContent(format);
        }

        format.setAttribute("type", pipe.formatType);
    }

    if (pipe.type.equals("Modules")) {
        // Update location (attribute)
        main.setAttribute("location", pipe.location);
    }

    if (pipe.type.equals("Modules") || pipe.type.equals("Groups")) {
        // Update uri (child)
        Element uri = main.getChild("uri");

        // If child not present, create
        if (uri == null) {
            uri = new Element("uri");
            main.addContent(uri);
        }

        uri.setText(pipe.uri);
    }

    return doc;
}

From source file:org.apache.ctakes.relationextractor.metastasis.MetastasisAnaforaXMLReader.java

License:Apache License

private static Element removeSingleChild(Element elem, String elemName, String causeID) {
    Element child = getSingleChild(elem, elemName, causeID);
    elem.removeChildren(elemName);
    return child;
}

From source file:org.apache.ctakes.relationextractor.metastasis.MetastasisAnaforaXMLReader.java

License:Apache License

private static String removeSingleChildText(Element elem, String elemName, String causeID) {
    Element child = getSingleChild(elem, elemName, causeID);
    String text = child.getText();
    if (text.isEmpty()) {
        error(String.format("an empty '%s' child", elemName), causeID);
        text = null;/*from   ww w . j a  va 2s. com*/
    }
    elem.removeChildren(elemName);
    return text;
}

From source file:org.apache.ctakes.temporal.ae.DeepPheAnaforaXMLReader.java

License:Apache License

private static String removeSingleChildText(Element elem, String elemName, String causeID) {
    Element child = getSingleChild(elem, elemName, causeID);
    String text = null;//from  w  w w  .  j av  a  2s  .c  o  m
    if (child != null) {
        text = child.getText();
    }
    if (text == null || text.isEmpty()) {
        error(String.format("an empty '%s' child", elemName), causeID);
        text = null;
    }
    elem.removeChildren(elemName);
    return text;
}

From source file:org.apache.ctakes.temporal.ae.THYMEAnaforaXMLReader.java

License:Apache License

private static void processXmlFile(JCas jCas, File xmlFile) throws AnalysisEngineProcessException {
    // load the XML
    Element dataElem;/*from   w  w  w  .  j av a 2  s  . c o  m*/
    try {
        dataElem = new SAXBuilder().build(xmlFile.toURI().toURL()).getRootElement();
    } catch (MalformedURLException e) {
        throw new AnalysisEngineProcessException(e);
    } catch (JDOMException e) {
        throw new AnalysisEngineProcessException(e);
    } catch (IOException e) {
        throw new AnalysisEngineProcessException(e);
    }

    int curEventId = 1;
    int curTimexId = 1;
    int curRelId = 1;
    int docLen = jCas.getDocumentText().length();

    for (Element annotationsElem : dataElem.getChildren("annotations")) {

        Map<String, Annotation> idToAnnotation = Maps.newHashMap();
        for (Element entityElem : annotationsElem.getChildren("entity")) {
            String id = removeSingleChildText(entityElem, "id", null);
            Element spanElem = removeSingleChild(entityElem, "span", id);
            String type = removeSingleChildText(entityElem, "type", id);
            Element propertiesElem = removeSingleChild(entityElem, "properties", id);

            // UIMA doesn't support disjoint spans, so take the span enclosing
            // everything
            int begin = Integer.MAX_VALUE;
            int end = Integer.MIN_VALUE;
            for (String spanString : spanElem.getText().split(";")) {
                String[] beginEndStrings = spanString.split(",");
                if (beginEndStrings.length != 2) {
                    error("span not of the format 'number,number'", id);
                }
                int spanBegin = Integer.parseInt(beginEndStrings[0]);
                int spanEnd = Integer.parseInt(beginEndStrings[1]);
                if (spanBegin < begin) {
                    begin = spanBegin;
                }
                if (spanEnd > end) {
                    end = spanEnd;
                }
            }
            if (begin < 0 || end >= docLen) {
                error("Illegal begin or end boundary", id);
                continue;
            }

            Annotation annotation;
            if (type.equals("EVENT")) {
                String docTimeRel = removeSingleChildText(propertiesElem, "DocTimeRel", id);
                if (docTimeRel == null) {
                    error("no docTimeRel, assuming OVERLAP", id);
                    docTimeRel = "OVERLAP";
                }
                String eventType = removeSingleChildText(propertiesElem, "Type", id);
                String degree = removeSingleChildText(propertiesElem, "Degree", id);
                String polarity = removeSingleChildText(propertiesElem, "Polarity", id);
                String contextualModality = removeSingleChildText(propertiesElem, "ContextualModality", id);
                String contextualAspect = removeSingleChildText(propertiesElem, "ContextualAspect", id);
                String permanence = removeSingleChildText(propertiesElem, "Permanence", id);
                EventMention eventMention = new EventMention(jCas, begin, end);
                Event event = new Event(jCas);
                EventProperties eventProperties = new EventProperties(jCas);
                eventProperties.setDocTimeRel(docTimeRel);
                eventProperties.setCategory(eventType);
                eventProperties.setDegree(degree);
                if (polarity.equals("POS")) {
                    eventProperties.setPolarity(CONST.NE_POLARITY_NEGATION_ABSENT);
                } else if (polarity.equals("NEG")) {
                    eventProperties.setPolarity(CONST.NE_POLARITY_NEGATION_PRESENT);
                } else {
                    error("polarity that was not POS or NEG", id);
                }
                eventProperties.setContextualModality(contextualModality);
                eventProperties.setContextualAspect(contextualAspect);
                eventProperties.setPermanence(permanence);
                eventProperties.addToIndexes();
                event.setConfidence(1.0f);
                event.setDiscoveryTechnique(CONST.NE_DISCOVERY_TECH_GOLD_ANNOTATION);
                event.setProperties(eventProperties);
                event.setMentions(new FSArray(jCas, 1));
                event.setMentions(0, eventMention);
                event.addToIndexes();
                eventMention.setId(curEventId++);
                eventMention.setConfidence(1.0f);
                eventMention.setDiscoveryTechnique(CONST.NE_DISCOVERY_TECH_GOLD_ANNOTATION);
                eventMention.setEvent(event);
                eventMention.addToIndexes();
                annotation = eventMention;

            } else if (type.equals("TIMEX3")) {
                String timeClass = removeSingleChildText(propertiesElem, "Class", id);
                TimeMention timeMention = new TimeMention(jCas, begin, end);
                timeMention.setId(curTimexId++);
                timeMention.setTimeClass(timeClass);
                timeMention.addToIndexes();
                annotation = timeMention;

            } else if (type.equals("DOCTIME")) {
                TimeMention timeMention = new TimeMention(jCas, begin, end);
                timeMention.setId(curTimexId++);
                timeMention.setTimeClass(type);
                timeMention.addToIndexes();
                annotation = timeMention;

            } else if (type.equals("SECTIONTIME")) {
                TimeMention timeMention = new TimeMention(jCas, begin, end);
                timeMention.setId(curTimexId++);
                timeMention.setTimeClass(type);
                timeMention.addToIndexes();
                annotation = timeMention;

            } else if (type.equals("Markable")) {
                while (end >= begin && (jCas.getDocumentText().charAt(end - 1) == '\n'
                        || jCas.getDocumentText().charAt(end - 1) == '\r')) {
                    end--;
                }
                Markable markable = new Markable(jCas, begin, end);
                markable.addToIndexes();
                annotation = markable;

            } else if (type.equals("DUPLICATE")) {
                LOGGER.warn("Ignoring duplicate sections in annotations.");
                continue;
            } else {
                throw new UnsupportedOperationException("unsupported entity type: " + type);
            }

            // match the annotation to it's ID for later use
            idToAnnotation.put(id, annotation);

            // make sure all XML has been consumed
            removeSingleChild(entityElem, "parentsType", id);
            if (!propertiesElem.getChildren().isEmpty() || !entityElem.getChildren().isEmpty()) {
                List<String> children = Lists.newArrayList();
                for (Element child : propertiesElem.getChildren()) {
                    children.add(child.getName());
                }
                for (Element child : entityElem.getChildren()) {
                    children.add(child.getName());
                }
                error("unprocessed children " + children, id);
            }
        }

        for (Element relationElem : annotationsElem.getChildren("relation")) {
            String id = removeSingleChildText(relationElem, "id", null);
            String type = removeSingleChildText(relationElem, "type", id);
            Element propertiesElem = removeSingleChild(relationElem, "properties", id);

            if (type.equals("TLINK")) {
                String sourceID = removeSingleChildText(propertiesElem, "Source", id);
                String targetID = removeSingleChildText(propertiesElem, "Target", id);
                String tlinkType = removeSingleChildText(propertiesElem, "Type", id);
                TemporalTextRelation relation = new TemporalTextRelation(jCas);
                relation.setId(curRelId++);
                addRelation(jCas, relation, sourceID, targetID, tlinkType, idToAnnotation, id);

            } else if (type.equals("ALINK")) {
                String sourceID = removeSingleChildText(propertiesElem, "Source", id);
                String targetID = removeSingleChildText(propertiesElem, "Target", id);
                String alinkType = removeSingleChildText(propertiesElem, "Type", id);
                AspectualTextRelation relation = new AspectualTextRelation(jCas);
                addRelation(jCas, relation, sourceID, targetID, alinkType, idToAnnotation, id);

            } else if (type.equals("Identical")) {
                CollectionTextRelation chain = new CollectionTextRelation(jCas);
                String mention = removeSingleChildText(propertiesElem, "FirstInstance", id);
                NonEmptyFSList list = new NonEmptyFSList(jCas);
                NonEmptyFSList root = list;
                Markable antecedent, anaphor;
                antecedent = (Markable) idToAnnotation.get(mention);
                list.setHead(antecedent);
                List<Element> corefs = propertiesElem.getChildren("Coreferring_String");
                //          while((mention = removeSingleChildText(propertiesElem, "Coreferring_String", id)) != null){
                for (Element coref : corefs) {
                    mention = coref.getText();
                    NonEmptyFSList child = new NonEmptyFSList(jCas);
                    anaphor = (Markable) idToAnnotation.get(mention);
                    child.setHead(anaphor);
                    CoreferenceRelation pair = new CoreferenceRelation(jCas);
                    pair.setCategory("Identity");
                    RelationArgument arg1 = new RelationArgument(jCas);
                    arg1.setArgument(antecedent);
                    arg1.setRole("antecedent");
                    pair.setArg1(arg1);
                    RelationArgument arg2 = new RelationArgument(jCas);
                    arg2.setArgument(anaphor);
                    arg2.setRole("anaphor");
                    pair.setArg2(arg2);
                    pair.addToIndexes();
                    list.setTail(child);
                    list = child;
                    antecedent = anaphor;
                }
                propertiesElem.removeChildren("Coreferring_String");
                EmptyFSList tail = new EmptyFSList(jCas);
                list.setTail(tail);
                root.addToIndexes();
                chain.setMembers(root);
                chain.addToIndexes();
            } else if (type.equals("Set/Subset")) {
                error("This reader has not implemented reading of Set/Subset relations yet", id);

            } else if (type.equals("Whole/Part")) {
                error("This reader has not implemented reading of Whole/Part relations yet", id);

            } else if (type.equals("Appositive")) {
                error("This reader has not implemented reading of Appositive relations yet", id);

            } else {
                throw new UnsupportedOperationException("unsupported relation type: " + type);
            }

            // make sure all XML has been consumed
            removeSingleChild(relationElem, "parentsType", id);
            if (!propertiesElem.getChildren().isEmpty() || !relationElem.getChildren().isEmpty()) {
                List<String> children = Lists.newArrayList();
                for (Element child : propertiesElem.getChildren()) {
                    children.add(child.getName());
                }
                for (Element child : relationElem.getChildren()) {
                    children.add(child.getName());
                }
                error("unprocessed children " + children, id);
            }
        }
    }
}

From source file:org.artifactory.update.security.v6.LowercaseUsernameXmlConverter.java

License:Open Source License

private void addGroupsToUser(Element userElement, Element userToGetGroupsFrom, Namespace namespace) {
    Set<String> existingGroupNames = getUserGroups(userElement);
    Set<String> newGroupNames = getUserGroups(userToGetGroupsFrom);
    existingGroupNames.addAll(newGroupNames);
    Element groupsElement = userElement.getChild("groups");
    if (groupsElement != null) {
        groupsElement.removeChildren("userGroup");
        for (String groupName : existingGroupNames) {
            Element userGroup = new Element("userGroup", namespace);
            userGroup.setText(groupName.toLowerCase());
            groupsElement.addContent(userGroup);
        }/*w  w  w . j  av a2  s  .  co m*/
    }
}