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:org.mycore.datamodel.metadata.validator.MCREditorOutValidator.java

License:Open Source License

/**
 * @throws IOException /* w w w  . ja  v a2 s .c o  m*/
 * @throws JDOMException 
 * 
 */
private void checkObject() throws JDOMException, IOException {
    // add the namespaces (this is a workaround)
    org.jdom2.Element root = input.getRootElement();
    root.addNamespaceDeclaration(XLINK_NAMESPACE);
    root.addNamespaceDeclaration(XSI_NAMESPACE);
    // set the schema
    String mcr_schema = "datamodel-" + id.getTypeId() + ".xsd";
    root.setAttribute("noNamespaceSchemaLocation", mcr_schema, XSI_NAMESPACE);
    // check the label
    String label = root.getAttributeValue("label");
    if (label == null || (label = label.trim()).length() == 0) {
        root.setAttribute("label", id.toString());
    }
    // remove the path elements from the incoming
    org.jdom2.Element pathes = root.getChild("pathes");
    if (pathes != null) {
        root.removeChildren("pathes");
    }
    org.jdom2.Element structure = root.getChild("structure");
    if (structure == null) {
        root.addContent(new Element("structure"));
    } else {
        checkObjectStructure(structure);
    }
    Element metadata = root.getChild("metadata");
    checkObjectMetadata(metadata);
    org.jdom2.Element service = root.getChild("service");
    checkObjectService(root, service);
}

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

License:Open Source License

/**
 *  returns a single classification object
 *
 * @param classID - the classfication id
 * @param format//from   w w w  .  ja va 2  s . co  m
 *   Possible values are: json | xml (required)
 * @param filter
 *     a ';'-separated list of ':'-separated key-value pairs, possible keys are:
 *      - lang - the language of the returned labels, if ommited all labels in all languages will be returned
 *      - root - an id for a category which will be used as root
 *      - nonempty - hide empty categories
 * @param style
 *    a ';'-separated list of values, possible keys are:
 *      - 'checkboxtree' - create a json syntax which can be used as input for a dojo checkboxtree;
 *      - 'checked'   - (together with 'checkboxtree') all checkboxed will be checked
 *      - 'jstree' - create a json syntax which can be used as input for a jsTree
 *      - 'opened' - (together with 'jstree') - all nodes will be opened
 *      - 'disabled' - (together with 'jstree') - all nodes will be disabled
 *      - 'selected' - (together with 'jstree') - all nodes will be selected
 * @param callback used for JSONP - wrap json result into a Javascript function named by callback parameter
 * @return a Jersey Response object
 */
@GET
//@Path("/id/{value}{format:(\\.[^/]+?)?}")  -> working, but returns empty string instead of default value
@Path("/{classID}")
@Produces({ MediaType.TEXT_XML + ";charset=UTF-8", MediaType.APPLICATION_JSON + ";charset=UTF-8" })
public Response showObject(@PathParam("classID") String classID,
        @QueryParam("format") @DefaultValue("xml") String format,
        @QueryParam("filter") @DefaultValue("") String filter,
        @QueryParam("style") @DefaultValue("") String style,
        @QueryParam("callback") @DefaultValue("") String callback) {
    String rootCateg = null;
    String lang = null;
    boolean filterNonEmpty = false;
    boolean filterNoChildren = false;

    for (String f : filter.split(";")) {
        if (f.startsWith("root:")) {
            rootCateg = f.substring(5);
        }
        if (f.startsWith("lang:")) {
            lang = f.substring(5);
        }
        if (f.startsWith("nonempty")) {
            filterNonEmpty = true;
        }
        if (f.startsWith("nochildren")) {
            filterNoChildren = true;
        }
    }

    if (format == null || classID == null) {
        return Response.serverError().status(Status.BAD_REQUEST).build();
        //TODO response.sendError(HttpServletResponse.SC_NOT_FOUND, "Please specify parameters format and classid.");
    }
    try {
        MCRCategory cl = DAO.getCategory(MCRCategoryID.rootID(classID), -1);
        if (cl == null) {
            return MCRRestAPIError.create(Response.Status.BAD_REQUEST, "Classification not found.",
                    "There is no classification with the given ID.").createHttpResponse();
        }
        Document docClass = MCRCategoryTransformer.getMetaDataDocument(cl, false);
        Element eRoot = docClass.getRootElement();
        if (rootCateg != null) {
            XPathExpression<Element> xpe = XPathFactory.instance()
                    .compile("//category[@ID='" + rootCateg + "']", Filters.element());
            Element e = xpe.evaluateFirst(docClass);
            if (e != null) {
                eRoot = e;
            } else {
                return MCRRestAPIError
                        .create(Response.Status.BAD_REQUEST, "Category not found.",
                                "The classfication does not contain a category with the given ID.")
                        .createHttpResponse();
            }
        }
        if (filterNonEmpty) {
            Element eFilter = eRoot;
            if (eFilter.getName().equals("mycoreclass")) {
                eFilter = eFilter.getChild("categories");
            }
            filterNonEmpty(docClass.getRootElement().getAttributeValue("ID"), eFilter);
        }
        if (filterNoChildren) {
            eRoot.removeChildren("category");
        }

        if (FORMAT_JSON.equals(format)) {
            String json = writeJSON(eRoot, lang, style);
            //eventually: allow Cross Site Requests: .header("Access-Control-Allow-Origin", "*")
            if (callback.length() > 0) {
                return Response.ok(callback + "(" + json + ")").type("application/javascript; charset=UTF-8")
                        .build();
            } else {
                return Response.ok(json).type("application/json; charset=UTF-8").build();
            }
        }

        if (FORMAT_XML.equals(format)) {
            String xml = writeXML(eRoot, lang);
            return Response.ok(xml).type("application/xml; charset=UTF-8").build();
        }
    } catch (Exception e) {
        LogManager.getLogger(this.getClass()).error("Error outputting classification", e);
        //TODO response.sendError(HttpServletResponse.SC_NOT_FOUND, "Error outputting classification");
    }
    return null;
}

From source file:org.openflexo.foundation.fml.rm.ViewPointResourceImpl.java

License:Open Source License

private static void removeNamedElements(Document document, String elementName) {
    ArrayList<Element> parentElements = new ArrayList<Element>();
    for (Content content : document.getDescendants()) {
        if (content instanceof Element) {
            Element element = (Element) content;
            if (!element.getChildren(elementName).isEmpty()) {
                parentElements.add(element);
            }//from   ww  w  . j  a  v  a  2 s  . co  m
        }
    }
    for (Element parent : parentElements) {
        parent.removeChildren(elementName);
    }
    parentElements = null;
}

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

License:Open Source License

/**
 * get ResourceUtilisationPlan updated with data from request
 *
 * @return/*from   w  w  w .j  a v a 2s  .  c om*/
 */
private void updateRUPFromRequest(Document doc) throws Exception {
    String xpath = XMLUtils.getXPATH_RUP();
    Element rupElement = XMLUtils.getElement(doc, xpath);

    // remove elements from rup for reinsert in next step
    for (Element activity : activities) {
        activity.removeChildren(Constants.XML_RESERVATION);
        activity.removeChildren(Constants.XML_UTILISATIONREL);
        activity.removeChildren(Constants.XML_MSGTRANSFER);
    }

    XMLUtils.removeAttributes(rupElement, XML_ERROR);
    XMLUtils.removeAttributes(rupElement, XML_WARNING);

    // build new parameter list with rup fields only
    Map<String, Object[]> params = new HashMap<String, Object[]>();
    for (String key : new ArrayList<String>(request.getParameterMap().keySet())) {
        if (!key.startsWith(XML_ACTIVITY + "_") || key.contains(XML_RESOURCE_TYPE)
                || key.endsWith("__sexyComboHidden")) {
            continue;
        }

        Object[] values = ((Object[]) request.getParameterMap().get(key));

        // for sexycombo plugin only: write value of key "bla__sexyCombo" to newKey "bla"
        if (key.endsWith("__sexyCombo")) {
            String newKey = key.substring(0, key.length() - "__sexyCombo".length());
            params.put(newKey, values);
        } else if (!params.containsKey(key)) {
            params.put(key, values);
        }
    }

    ArrayList<String> keys = new ArrayList<String>(params.keySet());
    final List<String> possibleActivities = Utils
            .parseCSV(_props.getSchedulingProperty("possibleActivitiesSorted"));
    Collections.sort(keys, new Comparator<String>() {
        public int compare(String a1, String a2) {
            if (a1.startsWith(XML_ACTIVITY)) {
                a1 = a1.substring(XML_ACTIVITY.length() + 1);
                a1 = a1.substring(0, a1.indexOf("_"));
            }
            if (a2.startsWith(XML_ACTIVITY)) {
                a2 = a2.substring(XML_ACTIVITY.length() + 1);
                a2 = a2.substring(0, a2.indexOf("_"));
            }
            return possibleActivities.indexOf(a1) - possibleActivities.indexOf(a2);
        }
    });

    // update RUP with input values
    for (String key : keys) {
        Object[] values = params.get(key);
        String value = (String) values[0];

        StringTokenizer st = new StringTokenizer(key, "_");
        st.nextToken(); // ignore 'Activity.'
        String activityName = st.nextToken();
        xpath = XMLUtils.getXPATH_Activities(activityName);
        Element activity = XMLUtils.getElement(doc, xpath);
        if (activity == null) {
            activity = getTemplate(XML_ACTIVITY);
            Element name = activity.getChild(XML_ACTIVITYNAME);
            name.setText(activityName);
            rupElement.addContent(activity);
        }

        Element var = null;
        String resOrUtilName = st.nextToken();
        if (resOrUtilName.equals(XML_RESERVATION) || resOrUtilName.equals(XML_UTILISATIONREL)
                || resOrUtilName.equals(XML_MSGTRANSFER)) {
            Integer resOrUtilIndex = Integer.valueOf(st.nextToken().substring(1)); // index, remove '#'
            xpath = XMLUtils.getXPATH_ActivityElement(activityName, resOrUtilName, resOrUtilIndex);

            Element resOrUtilElem = XMLUtils.getElement(doc, xpath);

            // insert empty 'dummy' resOrUtils, will be removed later
            while (resOrUtilElem == null) {
                resOrUtilElem = getTemplate(resOrUtilName);
                resOrUtilElem.addContent(new Element(XML_DUMMY));
                activity.addContent(resOrUtilElem);

                resOrUtilElem = XMLUtils.getElement(doc, xpath);
            }
            resOrUtilElem.removeChild(XML_DUMMY); // only if exists one

            String pathName = "";
            while (st.hasMoreTokens()) {
                String elementName = st.nextToken();
                pathName += elementName;
                xpath = XMLUtils.getXPATH_ResOrUtilElement(activityName, resOrUtilName, resOrUtilIndex,
                        pathName);
                var = XMLUtils.getElement(doc, xpath);
                if (var == null) {
                    var = new Element(elementName);
                    resOrUtilElem.addContent(var);
                }
                resOrUtilElem = var;
                pathName += "/";
            }

        } else {
            xpath = XMLUtils.getXPATH_ActivityElement(activityName, resOrUtilName, null);
            var = XMLUtils.getElement(doc, xpath);
            if (var == null) {
                var = new Element(resOrUtilName);
                activity.addContent(var);
            }
        }

        String cssClass = validateElement(var, new ArrayList<Element>());
        if (cssClass.equals(CSS_DATEINPUT)) {
            try {
                Date date = Utils.string2Date(value, isShortForm ? Utils.DATE_PATTERN : Utils.DATETIME_PATTERN);
                XMLUtils.setDateValue(var, date);
            } catch (ParseException e) {
                //_log.error("cannot parse into date" + value);
            }
        } else if (cssClass.equals(CSS_DURATIONINPUT)) {
            try {
                value = Utils.stringMinutes2stringXMLDuration(value);
            } catch (Exception e) {
                //_log.error("cannot parse into duration" + value);
            }
            XMLUtils.setStringValue(var, value);
        } else {
            XMLUtils.setStringValue(var, value);
        }

        validateElement(var, new ArrayList<Element>());
    }

    updateActivities(doc);
}