Example usage for org.jdom2 Element removeContent

List of usage examples for org.jdom2 Element removeContent

Introduction

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

Prototype

@Override
    public Content removeContent(final int index) 

Source Link

Usage

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

License:Open Source License

private void applyAttributeXPath(Document generatedXml, String xpath, String value) {
    List<Object> matches = XPathFactory.instance().compile(xpath).evaluate(generatedXml.getRootElement());
    if (matches.size() == 0) {
        log(LogLevel.WARN, "XPath expression " + xpath + " did not find any matches");
        return;/*from ww  w. j av a  2 s .c  o m*/
    }
    Object object = matches.get(0);
    if (object instanceof Element) {
        Element element = (Element) object;
        if (value != null) {
            element.setText(value.toString());
        } else {
            if (nullHandling.equals(NULL_HANDLING_REMOVE)) {
                Element parent = element.getParentElement();
                parent.removeContent(element);
            } else if (nullHandling.equalsIgnoreCase(NULL_HANDLING_XML_NIL)) {
                element.setAttribute("nil", "true", getXmlNamespace());
            }
        }
    } else if (object instanceof Attribute) {
        Attribute attribute = (Attribute) object;
        if (value != null) {
            attribute.setValue(value);
        }
    }
}

From source file:org.kdp.word.transformer.ListParagraphTransformer.java

License:Apache License

private void processListItemBatch(Context context, Element parent, List<Element> listItems) {
    boolean ordered = false;
    for (Element el : listItems) {
        removeNestedSpanElements(el);/*from  w  w  w .j a v  a 2s. c  om*/
        normalizeListItemText(el);
        ordered = processItemMarker(el);
        el.getAttributes().clear();
    }
    Element firstItem = listItems.get(0);
    int index = parent.indexOf(firstItem);
    for (Element el : listItems) {
        parent.removeContent(el);
    }
    JDOMFactory factory = context.getJDOMFactory();
    Element ul = factory.element(ordered ? "ol" : "ul");
    for (Element el : listItems) {
        Element li = factory.element("li");
        li.setAttribute("class", "MsoListParagraph");
        for (Content co : el.getContent()) {
            li.addContent(co.clone());
        }
        ul.addContent(li);
    }
    parent.addContent(index, ul);
}

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

License:Open Source License

/**
 * Recursively resolves references by the @ref attribute and
 * replaces them with the referenced component.
 *///www.j a v  a 2 s  .  c o  m
private void resolveReferences() {
    for (Iterator<Element> it = referencing2ref.keySet().iterator(); it.hasNext();) {
        Element referencing = it.next();
        String id = referencing2ref.get(referencing);
        LOGGER.debug("Resolving reference to " + id);

        Element found = id2component.get(id);
        if (found == null) {
            String msg = "Reference to component " + id + " could not be resolved";
            throw new MCRConfigurationException(msg);
        }

        String name = referencing.getName();
        referencing.removeAttribute("ref");
        it.remove();

        if (name.equals("cell") || name.equals("repeater")) {
            if (found.getParentElement().getName().equals("components")) {
                referencing.addContent(0, found.detach());
            } else {
                referencing.addContent(0, (Element) found.clone());
            }
        } else if (name.equals("panel")) {
            if (referencing2ref.containsValue(id)) {
                referencing.addContent(0, found.cloneContent());
            } else {
                found.detach();
                List<Content> content = found.getContent();
                for (int i = 0; !content.isEmpty(); i++) {
                    Content child = content.remove(0);
                    referencing.addContent(i, child);
                }
            }
        } else if (name.equals("include")) {
            Element parent = referencing.getParentElement();
            int pos = parent.indexOf(referencing);
            referencing.detach();

            if (referencing2ref.containsValue(id)) {
                parent.addContent(pos, found.cloneContent());
            } else {
                found.detach();
                List<Content> content = found.getContent();
                for (int i = pos; !content.isEmpty(); i++) {
                    Content child = content.remove(0);
                    parent.addContent(i, child);
                }
            }
        }
    }

    Element components = editor.getChild("components");
    String root = components.getAttributeValue("root");

    for (int i = 0; i < components.getContentSize(); i++) {
        Content child = components.getContent(i);
        if (!(child instanceof Element)) {
            continue;
        }
        if (((Element) child).getName().equals("headline")) {
            continue;
        }
        if (!root.equals(((Element) child).getAttributeValue("id"))) {
            components.removeContent(i--);
        }
    }
}

From source file:org.mycore.mods.MCRMODSMetadataShareAgent.java

License:Open Source License

@Override
public void distributeMetadata(MCRObject holder) throws MCRPersistenceException, MCRAccessException {
    MCRMODSWrapper holderWrapper = new MCRMODSWrapper(holder);
    List<MCRMetaLinkID> children = holder.getStructure().getChildren();
    if (!children.isEmpty()) {
        LOGGER.info("Update inherited metadata");
        for (MCRMetaLinkID childIdRef : children) {
            LOGGER.info("Update: " + childIdRef);
            MCRObject child = MCRMetadataManager.retrieveMCRObject(childIdRef.getXLinkHrefID());
            MCRMODSWrapper childWrapper = new MCRMODSWrapper(child);
            inheritToChild(holderWrapper, childWrapper);
            LOGGER.info("Saving: " + childIdRef);
            try {
                MCRMetadataManager.update(child);
            } catch (MCRActiveLinkException e) {
                throw new MCRPersistenceException("Error while updating inherited metadata", e);
            }/*ww  w.j  a v a 2  s . c  o m*/
        }
    }
    Collection<String> recipientIds = MCRLinkTableManager.instance().getSourceOf(holder.getId(),
            MCRLinkTableManager.ENTRY_TYPE_REFERENCE);
    for (String rId : recipientIds) {
        LOGGER.info("distribute metadata to " + rId);
        MCRObjectID recipientId = MCRObjectID.getInstance(rId);
        MCRObject recipient = MCRMetadataManager.retrieveMCRObject(recipientId);
        MCRMODSWrapper recipientWrapper = new MCRMODSWrapper(recipient);
        for (Element relatedItem : recipientWrapper.getLinkedRelatedItems()) {
            String holderId = relatedItem.getAttributeValue("href", MCRConstants.XLINK_NAMESPACE);
            if (holder.getId().toString().equals(holderId)) {
                @SuppressWarnings("unchecked")
                Filter<Content> sharedMetadata = (Filter<Content>) Filters
                        .element("part", MCRConstants.MODS_NAMESPACE).negate();
                relatedItem.removeContent(sharedMetadata);
                relatedItem.addContent(holderWrapper.getMODS().cloneContent());
                LOGGER.info("Saving: " + recipientId);
                try {
                    MCRMetadataManager.update(recipient);
                } catch (MCRActiveLinkException e) {
                    throw new MCRPersistenceException("Error while updating shared metadata", e);
                }
            }
        }
    }
}

From source file:org.mycore.restapi.v1.MCRRestAPIClassifications.java

License:Open Source License

private void filterNonEmpty(String classId, Element e) {
    SolrClient solrClient = MCRSolrClientFactory.getSolrClient();
    for (int i = 0; i < e.getChildren("category").size(); i++) {
        Element cat = e.getChildren("category").get(i);

        SolrQuery solrQquery = new SolrQuery();
        solrQquery.setQuery("category:\""
                + MCRSolrUtils.escapeSearchValue(classId + ":" + cat.getAttributeValue("ID")) + "\"");
        solrQquery.setRows(0);//from w  w w .j a  v a  2 s.  c  o  m
        try {
            QueryResponse response = solrClient.query(solrQquery);
            SolrDocumentList solrResults = response.getResults();
            if (solrResults.getNumFound() == 0) {
                e.removeContent(cat);
                i--;
            }
        } catch (SolrServerException | IOException exc) {
            LOGGER.error(exc);
        }
    }
    for (int i = 0; i < e.getChildren("category").size(); i++) {
        filterNonEmpty(classId, e.getChildren("category").get(i));
    }
}

From source file:org.rometools.feed.module.sle.io.ItemParser.java

License:Apache License

/**
 * Parses the XML node (JDOM element) extracting module information.
 * <p>/*from  w  w w .j  a v a  2  s.co m*/
 *
 * @param element the XML node (JDOM element) to extract module information from.
 * @return a module instance, <b>null</b> if the element did not have module information.
 */
public Module parse(Element element) {
    SleEntryImpl sle = new SleEntryImpl();
    ArrayList values = new ArrayList();
    List groups = element.getChildren("group", ModuleParser.TEMP);

    for (int i = 0; (groups != null) && (i < groups.size()); i++) {
        Element group = (Element) groups.get(i);
        StringValue value = new StringValue();
        value.setElement(group.getAttributeValue("element"));
        value.setLabel(group.getAttributeValue("label"));
        value.setValue(group.getAttributeValue("value"));
        if (group.getAttributeValue("ns") != null)
            value.setNamespace(Namespace.getNamespace(group.getAttributeValue("ns")));
        else {
            value.setNamespace(element.getDocument().getRootElement().getNamespace());
        }
        values.add(value);
        element.removeContent(group);
    }

    sle.setGroupValues((EntryValue[]) values.toArray(new EntryValue[values.size()]));
    values = (values.size() == 0) ? values : new ArrayList();

    List sorts = new ArrayList(element.getChildren("sort", ModuleParser.TEMP));
    //System.out.println("]]] sorts on element"+sorts.size());
    for (int i = 0; (sorts != null) && (i < sorts.size()); i++) {
        Element sort = (Element) sorts.get(i);
        String dataType = sort.getAttributeValue("data-type");
        //System.out.println("Doing datatype "+dataType +" :: "+sorts.size());
        if ((dataType == null) || dataType.equals(Sort.TEXT_TYPE)) {
            StringValue value = new StringValue();
            value.setElement(sort.getAttributeValue("element"));
            value.setLabel(sort.getAttributeValue("label"));
            value.setValue(sort.getAttributeValue("value"));
            if (sort.getAttributeValue("ns") != null)
                value.setNamespace(Namespace.getNamespace(sort.getAttributeValue("ns")));
            else
                value.setNamespace(element.getDocument().getRootElement().getNamespace());
            values.add(value);

            element.removeContent(sort);

        } else if (dataType.equals(Sort.DATE_TYPE)) {
            DateValue value = new DateValue();
            value.setElement(sort.getAttributeValue("element"));
            value.setLabel(sort.getAttributeValue("label"));
            if (sort.getAttributeValue("ns") != null)
                value.setNamespace(Namespace.getNamespace(sort.getAttributeValue("ns")));
            else
                value.setNamespace(element.getDocument().getRootElement().getNamespace());
            Date dateValue = null;

            try {
                dateValue = DateParser.parseRFC822(sort.getAttributeValue("value"));
                dateValue = (dateValue == null) ? DateParser.parseW3CDateTime(sort.getAttributeValue("value"))
                        : dateValue;
            } catch (Exception e) {
                ; // ignore parse exceptions
            }

            value.setValue(dateValue);
            values.add(value);
            element.removeContent(sort);
        } else if (dataType.equals(Sort.NUMBER_TYPE)) {
            NumberValue value = new NumberValue();
            value.setElement(sort.getAttributeValue("element"));
            value.setLabel(sort.getAttributeValue("label"));
            if (sort.getAttributeValue("ns") != null)
                value.setNamespace(Namespace.getNamespace(sort.getAttributeValue("ns")));
            else
                value.setNamespace(element.getDocument().getRootElement().getNamespace());

            try {
                value.setValue(new BigDecimal(sort.getAttributeValue("value")));
            } catch (NumberFormatException nfe) {
                ; // ignore
                values.add(value);
                element.removeContent(sort);
            }
        } else {
            throw new RuntimeException("Unknown datatype");
        }
    }
    //System.out.println("Values created "+values.size()+" from sorts" +sorts.size());
    sle.setSortValues((EntryValue[]) values.toArray(new EntryValue[values.size()]));

    return sle;
}

From source file:org.xflatdb.xflat.query.XPathUpdate.java

License:Apache License

/**
 * Applies the update operations to the given DOM Element representing
 * the data in a selected row./*from   w w  w  . j ava2 s.  c  o m*/
 * @param rowData The DOM Element representing the data in a selected row.
 * @return true if any updates were applied.
 */
public int apply(Element rowData) {
    int updateCount = 0;

    for (Update update : this.updates) {
        //the update's value will be one or the other, don't know which
        Content asContent = null;
        String asString = null;

        if (update.value instanceof String) {
            asString = (String) update.value;
        }

        if (update.value instanceof Content) {
            asContent = (Content) update.value;
        }

        for (Object node : update.path.evaluate(rowData)) {
            if (node == null)
                continue;

            Parent parent;
            Element parentElement;

            if (update.getUpdateType() == UpdateType.UNSET) {
                if (node instanceof Attribute) {
                    parentElement = ((Attribute) node).getParent();
                    if (parentElement != null) {
                        parentElement.removeAttribute((Attribute) node);
                        updateCount++;
                    }
                } else if (node instanceof Content) {
                    parent = ((Content) node).getParent();
                    //remove this node from its parent element
                    if (parent != null) {
                        parent.removeContent((Content) node);
                        updateCount++;
                    }
                }

                continue;
            }

            //it's a set

            if (node instanceof Attribute) {
                //for attributes we set the value to empty string
                //this way it can still be selected by xpath for future updates
                if (update.value == null) {
                    ((Attribute) node).setValue("");
                    updateCount++;
                } else {
                    if (asString == null) {
                        asString = getStringValue(update.value);
                    }

                    //if we fail conversion then do nothing.
                    if (asString != null) {
                        ((Attribute) node).setValue(asString);
                        updateCount++;
                    }
                }

                continue;
            } else if (!(node instanceof Content)) {
                //can't do anything
                continue;
            }

            Content contentNode = (Content) node;

            //need to convert
            if (update.value != null && asContent == null) {
                asContent = getContentValue(update.value);
                if (asContent == null) {
                    //failed conversion, try text
                    asString = getStringValue(update.value);
                    if (asString != null) {
                        //success!
                        asContent = new Text(asString);
                    }
                }
            }

            if (node instanceof Element) {
                //for elements we also set the value, but the value could be Content
                if (update.value == null) {
                    ((Element) node).removeContent();
                    updateCount++;
                } else if (asContent != null) {
                    if (asContent.getParent() != null) {
                        //we used the content before, need to clone it
                        asContent = asContent.clone();
                    }

                    ((Element) node).setContent(asContent);
                    updateCount++;
                }
                continue;
            }

            //at this point the node is Text, CDATA or something else.
            //The strategy now is to replace the value in its parent.
            parentElement = contentNode.getParentElement();
            if (parentElement == null) {
                //can't do anything
                continue;
            }

            if (update.value == null || asContent != null) {
                //replace this content in the parent element
                int index = parentElement.indexOf(contentNode);
                parentElement.removeContent(index);
                if (update.value != null) {
                    //if it was null then act like an unset, otherwise
                    //its a replace

                    if (asContent.getParent() != null) {
                        //we used the content before, need to clone it
                        asContent = asContent.clone();
                    }

                    parentElement.addContent(index, asContent);
                }
                updateCount++;
            }
        }
    }

    return updateCount;
}

From source file:org.yawlfoundation.yawl.procletService.blockType.BlockPICreate.java

License:Open Source License

private String removeUnneededData(String s, List<EntityID> eids) {
    myLog.debug("REMOVEUNNEEDEDDATA");
    List<Element> eltsRemove = new ArrayList<Element>();
    Element dataList = JDOMUtil.stringToElement(s).clone();
    myLog.debug("dataList:" + JDOMUtil.elementToString(dataList));
    //Element eidData = dataList.getChild("entity");
    Element eidData = dataList;//from   w ww  .  ja  v  a  2s .c om
    if (eidData != null) {
        myLog.debug("have entities");
        List<Element> children = eidData.getChildren("entity");
        for (Element child : children) {
            myLog.debug("have entity");
            Element emid = child.getChild("entity_id");
            String value = emid.getValue().trim();
            myLog.debug("value:" + value);
            // check if this one occurs in eids
            boolean match = false;
            for (EntityID eid : eids) {
                if (eid.getEmid().getValue().equals(value)) {
                    // match
                    myLog.debug("found match");
                    match = true;
                    break;
                }
            }
            if (!match) {
                eltsRemove.add(child);
            }
        }
    }
    myLog.debug("eltsRemove:" + eltsRemove.toString());
    Element eidData2 = dataList;
    if (eidData != null) {
        myLog.debug("have entities");
        for (Element eltSave : eltsRemove) {
            eidData2.removeContent(eltSave);
        }
    }
    String outputStr = JDOMUtil.elementToString(eidData2);
    myLog.debug("outputStr:" + outputStr);
    return outputStr;
}

From source file:org.yawlfoundation.yawl.procletService.state.Performatives.java

License:Open Source License

public static String calculateContent(List<EntityID> eids, WorkItemRecord wir) {
    myLog.debug("CALCULATECONTENT");
    myLog.debug("eids:" + eids);
    Element dataList = wir.getDataList();
    if (dataList != null) {
        dataList = dataList.clone();//from  www  . j a  va2 s  .co m
        myLog.debug("dataList:" + JDOMUtil.elementToString(dataList));
        Element eidData = dataList.getChild("entities");
        List<Element> eltsRemove = new ArrayList<Element>();
        if (eidData != null) {
            myLog.debug("have entities");
            List<Element> children = eidData.getChildren("entity");
            for (Element child : children) {
                myLog.debug("have entity");
                Element emid = child.getChild("entity_id");
                String value = emid.getValue().trim();
                myLog.debug("value:" + value);
                // check if this one occurs in eids
                boolean match = false;
                for (EntityID eid : eids) {
                    if (eid.getEmid().getValue().equals(value)) {
                        // match
                        myLog.debug("found match");
                        match = true;
                        break;
                    }
                }
                if (!match) {
                    eltsRemove.add(child);
                }
            }
        }
        // remove what is not needed
        myLog.debug("eltsRemove:" + eltsRemove.toString());
        Element eidData2 = dataList.getChild("entities");
        if (eidData != null) {
            myLog.debug("have entities");
            for (Element eltSave : eltsRemove) {
                eidData2.removeContent(eltSave);
            }
        }
        //      // create output
        //      Element output = new Element("entities");
        //      for (Element elt : eltsSave) {
        //         output.addContent(elt);
        //      }
        String outputStr = JDOMUtil.elementToString(eidData2);
        myLog.debug("outputStr:" + outputStr);
        return outputStr;
    } else {
        // get from the graphs which entities it concerns
        List<EntityMID> emids = new ArrayList<EntityMID>();
        myLog.debug("wir:" + wir);
        List<InteractionGraph> graphs = InteractionGraphs.getInstance().getGraphs();
        for (InteractionGraph graph : graphs) {
            if (!graph.getEntityMID().getValue().contains("TEMP")) {
                for (InteractionArc arc : graph.getArcs()) {
                    myLog.debug("arc:" + arc);
                    // check the tail
                    if (arc.getTail().getClassID().equals(wir.getSpecURI())
                            && arc.getTail().getProcletID().equals(wir.getCaseID())
                            && arc.getTail().getBlockID().equals(wir.getTaskID())) {
                        myLog.debug("in loop");
                        EntityMID emid = arc.getEntityID().getEmid();
                        // check if not already in emids
                        boolean check = false;
                        for (EntityMID emidC : emids) {
                            if (emidC.getValue().equals(emid.getValue())) {
                                check = true;
                            }
                        }
                        if (!check) {
                            emids.add(emid);
                            myLog.debug("emid added:" + emid);
                        }
                    }
                }
            }
        }
        // have the relevant emids
        Element newEntsElt = new Element("entities");
        for (EntityMID emid : emids) {
            Element newEntElt = new Element("entity");
            Element newEidElt = new Element("entity_id");
            newEidElt.setText(emid.getValue());
            newEntElt.addContent(newEidElt);
            newEntsElt.addContent(newEntElt);
        }
        String outputStr = JDOMUtil.elementToString(newEntsElt);
        myLog.debug("outputStr:" + outputStr);
        return outputStr;
    }
}

From source file:org.yawlfoundation.yawl.scheduling.FormGenerator.java

License:Open Source License

/**
 * - remove empty 'dummy' resOrUtils/* w  w  w. j a  va2 s  .  c  om*/
 * - set RequestType to POU, but only if SOU or EOU is not set
 */
public void updateActivities(Document doc) throws JDOMException {
    activities = XMLUtils.getXMLObjects(doc, XMLUtils.getXPATH_Activities());
    for (Element activity : activities) {
        String xpath = XMLUtils.getXPATH_ActivityElement(activity.getChildText(XML_ACTIVITYNAME),
                "*[count(./" + XML_DUMMY + ")>0]", null);

        List<Element> resOrUtils = XMLUtils.getXMLObjects(doc, xpath);
        for (Element resOrUtil : resOrUtils) {
            activity.removeContent(resOrUtil);
        }

        Element requestType = activity.getChild(XML_REQUESTTYPE);
        if (requestType == null) {
            requestType = new Element(XML_REQUESTTYPE);
            activity.addContent(requestType);
        }
        if (requestType.getText().isEmpty()) {
            requestType.setText(UTILISATION_TYPE_PLAN);
        }
    }
}