Example usage for org.jdom2 Element detach

List of usage examples for org.jdom2 Element detach

Introduction

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

Prototype

@Override
    public Element detach() 

Source Link

Usage

From source file:org.mycore.datamodel.ifs.MCRFilesystemNode.java

License:Open Source License

/**
 * Stores additional XML data for this node. The name of the data element is
 * used as unique key for storing data. If data with this name already
 * exists, it is overwritten.//from  www  . j a  v a  2  s .c  o  m
 * 
 * @param data
 *            the additional XML data to be saved
 * @throws IOException
 *             if the XML data can not be retrieved
 * @throws JDOMException
 *             if the XML data can not be parsed
 */
public void setAdditionalData(Element data) throws IOException, JDOMException {
    MCRFile dataFile = MCRFile.getRootFile(ID);
    Document doc;
    if (dataFile == null) {
        String name = "MCRFilesystemNode.additionalData";
        dataFile = new MCRFile(name, ID);
        doc = new Document(new Element("additionalData"));
    } else {
        doc = dataFile.getContentAsJDOM();
    }

    Element child = doc.getRootElement().getChild(data.getName());
    if (child != null) {
        child.detach();
    }
    doc.getRootElement().addContent((Element) data.clone());
    dataFile.setContentFrom(doc);
}

From source file:org.mycore.datamodel.ifs.MCRFilesystemNode.java

License:Open Source License

/**
 * Removes additional XML data from this node.
 * // w  w  w  .j  a  va  2 s  .c  o m
 * @param dataName
 *            the name of the additional XML data element to be removed
 * @throws IOException
 *             if the XML data can not be retrieved
 * @throws JDOMException
 *             if the XML data can not be parsed
 */
public void removeAdditionalData(String dataName) throws IOException, JDOMException {
    MCRFile dataFile = MCRFile.getRootFile(ID);
    if (dataFile == null) {
        return;
    }
    Document doc = dataFile.getContentAsJDOM();
    Element child = doc.getRootElement().getChild(dataName);
    if (child != null) {
        child.detach();
    }
    if (doc.getRootElement().getChildren().size() == 0) {
        dataFile.delete();
    } else {
        dataFile.setContentFrom(doc);
    }
}

From source file:org.mycore.datamodel.metadata.validator.MCREditorOutValidator.java

License:Open Source License

/**
 * The method add a default ACL-block.// www  .j  a v  a2  s .  c  o  m
 * 
 * @param service
 * @throws IOException 
 * @throws JDOMException 
 */
private void setDefaultObjectACLs(org.jdom2.Element service) throws JDOMException, IOException {
    if (!MCRConfiguration.instance().getBoolean("MCR.Access.AddObjectDefaultRule", true)) {
        LOGGER.info("Adding object default acl rule is disabled.");
        return;
    }
    String resourcetype = "/editor_default_acls_" + id.getTypeId() + ".xml";
    String resourcebase = "/editor_default_acls_" + id.getBase() + ".xml";
    // Read stylesheet and add user
    InputStream aclxml = MCREditorOutValidator.class.getResourceAsStream(resourcebase);
    if (aclxml == null) {
        aclxml = MCREditorOutValidator.class.getResourceAsStream(resourcetype);
        if (aclxml == null) {
            LOGGER.warn("Can't find default object ACL file " + resourcebase.substring(1) + " or "
                    + resourcetype.substring(1));
            String resource = "/editor_default_acls.xml"; // fallback
            aclxml = MCREditorOutValidator.class.getResourceAsStream(resource);
            if (aclxml == null) {
                return;
            }
        }
    }
    Document xml = SAX_BUILDER.build(aclxml);
    Element acls = xml.getRootElement().getChild("servacls");
    if (acls == null) {
        return;
    }
    for (Element acl : (Iterable<Element>) acls.getChildren()) {
        Element condition = acl.getChild("condition");
        if (condition == null) {
            continue;
        }
        Element rootbool = condition.getChild("boolean");
        if (rootbool == null) {
            continue;
        }
        for (Element orbool : (Iterable<Element>) rootbool.getChildren("boolean")) {
            for (Element firstcond : (Iterable<Element>) orbool.getChildren("condition")) {
                if (firstcond == null) {
                    continue;
                }
                String value = firstcond.getAttributeValue("value");
                if (value == null) {
                    continue;
                }
                if (value.equals("$CurrentUser")) {
                    String thisuser = MCRSessionMgr.getCurrentSession().getUserInformation().getUserID();
                    firstcond.setAttribute("value", thisuser);
                    continue;
                }
                if (value.equals("$CurrentGroup")) {
                    throw new MCRException(
                            "The parameter $CurrentGroup in default ACLs is no more supported since MyCoRe 2014.06 because it is not supported in Servlet API 3.0");
                }
                int i = value.indexOf("$CurrentIP");
                if (i != -1) {
                    String thisip = MCRSessionMgr.getCurrentSession().getCurrentIP();
                    StringBuilder sb = new StringBuilder(64);
                    sb.append(value.substring(0, i)).append(thisip)
                            .append(value.substring(i + 10, value.length()));
                    firstcond.setAttribute("value", sb.toString());
                }
            }
        }
    }
    service.addContent(acls.detach());
}

From source file:org.mycore.datamodel.metadata.validator.MCREditorOutValidator.java

License:Open Source License

/**
 * The method add a default ACL-block./*from w ww . ja  va 2  s  .c om*/
 */
public static void setDefaultDerivateACLs(org.jdom2.Element service) {
    // Read stylesheet and add user
    InputStream aclxml = MCREditorOutValidator.class.getResourceAsStream("/editor_default_acls_derivate.xml");
    if (aclxml == null) {
        LOGGER.warn("Can't find default derivate ACL file editor_default_acls_derivate.xml.");
        return;
    }
    try {
        org.jdom2.Document xml = SAX_BUILDER.build(aclxml);
        org.jdom2.Element acls = xml.getRootElement().getChild("servacls");
        if (acls != null) {
            service.addContent(acls.detach());
        }
    } catch (Exception e) {
        LOGGER.warn("Error while parsing file editor_default_acls_derivate.xml.");
    }
}

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

License:Open Source License

/**
 * Recursively removes include elements that are direct or indirect children
 * of the given container element and replaces them with the included
 * resource. Includes that may be contained in included resources are
 * recursively resolved, too./*from  w  ww  .ja v a2 s  .com*/
 *
 * @param element
 *            The element where to start resolving includes
 */
private boolean resolveIncludes(Element element) {
    boolean replaced = false;

    String ref = element.getAttributeValue("ref", "");
    ref = tokenSubstitutor.substituteTokens(ref);

    if (element.getName().equals("include")) {
        String uri = element.getAttributeValue("uri");
        if (uri != null) {
            uri = tokenSubstitutor.substituteTokens(uri);
            LOGGER.info("Including " + uri + (ref.length() > 0 ? "#" + ref : ""));
            Element parent = element.getParentElement();
            int pos = parent.indexOf(element);

            Element container = MCRURIResolver.instance().resolve(uri);
            List<Content> found;

            if (ref.length() == 0) {
                found = container.cloneContent();
            } else {
                found = findContent(container, ref);
                ref = "";
            }
            replaced = true;
            parent.addContent(pos, found);
            element.detach();
        }
    } else {
        String id = element.getAttributeValue("id", "");
        if (id.length() > 0) {
            id2component.put(id, element);
        }

        setDefaultAttributes(element);
        resolveChildren(element);
    }

    if (ref.length() > 0) {
        referencing2ref.put(element, ref);
    }
    return replaced;
}

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.
 *//*from   w  ww. j  av a  2s .co 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.MCRMODSWrapper.java

License:Open Source License

public void removeElements(String xPath) {
    Iterator<Element> selected;
    try {/*from w w  w  .  j a va  2s  .  c  om*/
        selected = buildXPath(xPath).evaluate(getMODS()).iterator();
    } catch (JDOMException ex) {
        String msg = "Could not remove elements at " + xPath;
        throw new MCRException(msg, ex);
    }

    while (selected.hasNext()) {
        Element element = selected.next();
        element.detach();
    }
}

From source file:org.mycore.oai.MCROAIObjectManager.java

License:Open Source License

public Record getRecord(String mcrID, MetadataFormat format) {
    Element recordElement;/*from w  w  w .  j  a  v  a 2 s.  c  om*/
    try {
        recordElement = getJDOMRecord(mcrID, format);
    } catch (Exception exc) {
        LOGGER.error("unable to get record " + mcrID + " (" + format.getPrefix() + ")");
        return null;
    }
    Element headerElement = recordElement.getChild("header", OAIConstants.NS_OAI);
    if (headerElement == null) {
        LOGGER.error("Header element of record " + mcrID + " (" + format.getPrefix() + ") is null!");
        return null;
    }
    Header header = headerToHeader(headerElement);
    Record record = new Record(header);
    Element metadataElement = recordElement.getChild("metadata", OAIConstants.NS_OAI);
    if (metadataElement != null && !metadataElement.getChildren().isEmpty()) {
        Element metadataChild = (Element) metadataElement.getChildren().get(0);
        record.setMetadata(new SimpleMetadata(metadataChild.detach()));
    }
    Element aboutElement = recordElement.getChild("about", OAIConstants.NS_OAI);
    if (aboutElement != null) {
        for (Element aboutChild : aboutElement.getChildren()) {
            record.getAboutList().add(aboutChild.detach());
        }
    }
    return record;
}

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

License:Open Source License

/**
 * Output xml/*from  w ww  . java 2 s . c o  m*/
 * @param eRoot - the root element
 * @param lang - the language which should be filtered or null for no filter
 * @return a string representation of the XML
 * @throws IOException
 */
private static String writeXML(Element eRoot, String lang) throws IOException {
    StringWriter sw = new StringWriter();
    if (lang != null) {
        // <label xml:lang="en" text="part" />
        XPathExpression<Element> xpE = XPathFactory.instance().compile("//label[@xml:lang!='" + lang + "']",
                Filters.element(), null, Namespace.XML_NAMESPACE);
        for (Element e : xpE.evaluate(eRoot)) {
            e.getParentElement().removeContent(e);
        }
    }
    XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
    Document docOut = new Document(eRoot.detach());
    xout.output(docOut, sw);
    return sw.toString();
}

From source file:org.shaman.rpg.editor.project.elements.JdomElement.java

private void setChildText(String child, String text) {
    org.jdom2.Element e = data.getChild(child, JdomElements.NAMESPACE);
    if (text == null) {
        if (e != null) {
            e.detach();
        }// ww w  . ja v  a  2  s  . c  o m
        return;
    }
    if (e == null) {
        e = new org.jdom2.Element(child);
        e.setNamespace(JdomElements.NAMESPACE);
        data.addContent(e);
    }
    e.setText(text);
}