Example usage for org.dom4j Element getTextTrim

List of usage examples for org.dom4j Element getTextTrim

Introduction

In this page you can find the example usage for org.dom4j Element getTextTrim.

Prototype

String getTextTrim();

Source Link

Document

DOCUMENT ME!

Usage

From source file:org.olat.ims.qti.editor.QTIEditHelper.java

License:Apache License

/**
 * Returns a hasmap with responselabel_idents as keys and points as values.
 * //from  w w  w.  j  a  v  a  2 s . c o m
 * @param respconditions
 * @param type
 * @return hasmap with responselabel_idents as keys and points as values.
 */
public static HashMap fetchPoints(final List respconditions, final int type) {
    final HashMap points = new HashMap();
    for (final Iterator i = respconditions.iterator(); i.hasNext();) {
        final Element el_resp_condition = (Element) i.next();
        // /todo
        float fPoints = 0;
        try {
            final Element el_setvar = el_resp_condition.element("setvar");
            if (el_setvar == null) {
                continue;
            }
            if (!el_setvar.attributeValue("action").equals("Add")
                    && !el_setvar.attributeValue("action").equals("Subtract")
                    && !el_setvar.attributeValue("action").equals("Set")) {
                continue;
            }
            fPoints = new Float(el_setvar.getTextTrim()).floatValue();
            if (el_setvar.attributeValue("action").equals("Subtract")) {
                fPoints = fPoints * -1;
            }
        } catch (final NumberFormatException nfe) {
            continue;
        }
        if (fPoints != 0) {
            final Element conditionvar = el_resp_condition.element("conditionvar");
            final Element and = conditionvar.element("and");
            // in and are all choices that are true

            final List tmp_points = (and == null) ? conditionvar.selectNodes(".//varequal")
                    : and.selectNodes(".//varequal");
            for (final Iterator iter = tmp_points.iterator(); iter.hasNext();) {
                final Element el_varequal = (Element) iter.next();
                if (type == Question.TYPE_SC || type == Question.TYPE_MC || type == Question.TYPE_KPRIM) {
                    points.put(el_varequal.getTextTrim(), new Float(fPoints));
                } else if (type == Question.TYPE_FIB) {
                    points.put(el_varequal.attributeValue("respident"), new Float(fPoints));
                }
            }
        }
    }
    return points;
}

From source file:org.olat.ims.qti.export.helper.ItemWithResponseStr.java

License:Apache License

/**
 * Constructor for ItemWithResponseLid.//from ww w  .  j av  a 2 s  .  co  m
 * 
 * @param el_item
 */
public ItemWithResponseStr(final Element el_item) {
    // CELFI#107
    this.itemTitle = el_item.attributeValue("title");
    this.itemIdent = el_item.attributeValue("ident");

    final Element decvar = (Element) el_item.selectSingleNode(".//outcomes/decvar");

    if (decvar != null) {
        this.itemMinValue = decvar.attributeValue("minvalue");
        this.itemMaxValue = decvar.attributeValue("maxvalue");
        this.itemCutValue = decvar.attributeValue("cutvalue");
    }

    final List el_presentationElements = el_item
            .selectNodes(".//presentation//mattext | .//presentation//response_str");

    int i = 1;
    boolean lastWasMattext = false;
    for (final Iterator itPresentations = el_presentationElements.iterator(); itPresentations.hasNext();) {
        final Element el_presentation = (Element) itPresentations.next();
        final String el_qname = el_presentation.getQualifiedName();
        if (el_qname.equalsIgnoreCase("mattext")) {
            this.quetionText += el_presentation.getTextTrim();
            lastWasMattext = true;
        } else {

            responseStrIdents.add(el_presentation.attributeValue("ident"));
            final Element render_fib = el_presentation.element("render_fib");
            if (render_fib != null) {
                isEssay = (render_fib.attributeValue("rows") == null) ? false : true;
                responseColumnHeaders.add((isEssay ? "A" : "B") + i); // A -> Area, B -> Blank

                final Element responseValue = (Element) el_item.selectSingleNode(
                        ".//varequal[@respident='" + el_presentation.attributeValue("ident") + "']");
                if (responseValue != null) {
                    responseLabelMaterials.add(responseValue.getTextTrim());
                    if (lastWasMattext) {
                        this.quetionText += " [" + responseValue.getTextTrim() + "] ";
                        lastWasMattext = false;
                    }
                } else {
                    responseLabelMaterials.add("");
                }

            } else {
                responseColumnHeaders.add("unknownType");

                responseLabelMaterials.add("");
            }
            i++;
        }
    }
    // CELFI#107 END
}

From source file:org.olat.ims.qti.render.ResultsBuilder.java

License:Apache License

/**
 * Method getResDoc./*from   w ww. ja va2  s.c  om*/
 * 
 * @param ai The assessment instance
 * @param locale The users locale
 * @param identity
 * @return Document The XML document
 */
public Document getResDoc(final AssessmentInstance ai, final Locale locale, final Identity identity) {
    final AssessmentContext ac = ai.getAssessmentContext();
    final DocumentFactory df = DocumentFactory.getInstance();
    final Document res_doc = df.createDocument();
    final Element root = df.createElement("qti_result_report");
    res_doc.setRootElement(root);
    final Element result = root.addElement("result");
    final Element extension_result = result.addElement("extension_result");

    // add items (not qti standard, but nice to display original questions ->
    // put it into extensions)
    // extension_result.
    final int sectioncnt = ac.getSectionContextCount();
    for (int i = 0; i < sectioncnt; i++) {
        final SectionContext sc = ac.getSectionContext(i);
        final int itemcnt = sc.getItemContextCount();
        for (int j = 0; j < itemcnt; j++) {
            final ItemContext it = sc.getItemContext(j);
            final Element el_item = it.getEl_item();
            extension_result.add(el_item);
        }
    }

    // add ims cp id for any media references
    addStaticsPath(extension_result, ai);

    // add assessment_result

    // Add User information
    final Element context = result.addElement("context");
    final User user = identity.getUser();
    final String name = user.getProperty(UserConstants.LASTNAME, locale) + " "
            + user.getProperty(UserConstants.FIRSTNAME, locale) + " (" + identity.getName() + ")";
    String instId = user.getProperty(UserConstants.INSTITUTIONALUSERIDENTIFIER, locale);
    final String instName = user.getProperty(UserConstants.INSTITUTIONALNAME, locale);

    if (instId == null) {
        instId = "N/A";
    }
    context.addElement("name").addText(name);

    String institution;
    if (instName == null) {
        institution = "N/A";
    } else {
        institution = instName;
    }
    if (institution == null) {
        institution = "N/A";
    }

    // Add institutional identifier (e.g. Matrikelnummer)
    final Element generic_identifier = context.addElement("generic_identifier");
    generic_identifier.addElement("type_label").addText(institution);
    generic_identifier.addElement("identifier_string").addText(instId);

    // Add start and stop date formatted as datetime
    final Element beginDate = context.addElement("date");
    beginDate.addElement("type_label").addText("Start");
    beginDate.addElement("datetime").addText(Formatter.formatDatetime(new Date(ac.getTimeOfStart())));
    final Element stopDate = context.addElement("date");
    stopDate.addElement("type_label").addText("Stop");
    stopDate.addElement("datetime").addText(Formatter.formatDatetime(new Date(ac.getTimeOfStop())));

    final Element ares = result.addElement("assessment_result");
    ares.addAttribute("ident_ref", ac.getIdent());
    if (ac.getTitle() != null) {
        ares.addAttribute("asi_title", ac.getTitle());
    }

    // process assessment score
    final Element a_score = ares.addElement("outcomes").addElement("score");
    a_score.addAttribute("varname", "SCORE");
    String strVal = StringHelper.formatFloat(ac.getScore(), 2);
    a_score.addElement("score_value").addText(strVal);

    strVal = ac.getMaxScore() == -1.0f ? "N/A" : StringHelper.formatFloat(ac.getMaxScore(), 2);
    a_score.addElement("score_max").addText(strVal);

    strVal = ac.getCutvalue() == -1.0f ? "N/A" : StringHelper.formatFloat(ac.getCutvalue(), 2);
    a_score.addElement("score_cut").addText(strVal);

    addElementText(ares, "duration", QTIHelper.getISODuration(ac.getDuration()));
    addElementText(ares, "num_sections", "" + ac.getSectionContextCount());
    addElementText(ares, "num_sections_presented", "0");
    addElementText(ares, "num_items", "" + ac.getItemContextCount());
    addElementText(ares, "num_items_presented", "" + ac.getItemsPresentedCount());
    addElementText(ares, "num_items_attempted", "" + ac.getItemsAttemptedCount());

    // add section_result
    final int secnt = ac.getSectionContextCount();
    for (int i = 0; i < secnt; i++) {
        final SectionContext secc = ac.getSectionContext(i);
        final Element secres = ares.addElement("section_result");
        secres.addAttribute("ident_ref", secc.getIdent());
        if (secc.getTitle() != null) {
            secres.addAttribute("asi_title", secc.getTitle());
        }
        addElementText(secres, "duration", QTIHelper.getISODuration(secc.getDuration()));
        addElementText(secres, "num_items", "" + secc.getItemContextCount());
        addElementText(secres, "num_items_presented", "" + secc.getItemsPresentedCount());
        addElementText(secres, "num_items_attempted", "" + secc.getItemsAttemptedCount());

        // process section score
        final Element sec_score = secres.addElement("outcomes").addElement("score");
        sec_score.addAttribute("varname", "SCORE");
        strVal = secc.getScore() == -1.0f ? "N/A" : "" + StringHelper.formatFloat(secc.getScore(), 2);
        sec_score.addElement("score_value").addText(strVal);
        strVal = secc.getMaxScore() == -1.0f ? "N/A" : "" + StringHelper.formatFloat(secc.getMaxScore(), 2);
        sec_score.addElement("score_max").addText(strVal);
        strVal = secc.getCutValue() == -1 ? "N/A" : "" + secc.getCutValue();
        sec_score.addElement("score_cut").addText(strVal);

        // iterate over all items in this section context
        final List itemsc = secc.getSectionItemContexts();
        for (final Iterator it_it = itemsc.iterator(); it_it.hasNext();) {
            final ItemContext itemc = (ItemContext) it_it.next();
            final Element itres = secres.addElement("item_result");
            itres.addAttribute("ident_ref", itemc.getIdent());
            itres.addAttribute("asi_title", itemc.getEl_item().attributeValue("title"));
            final Element it_duration = itres.addElement("duration");
            it_duration.addText(QTIHelper.getISODuration(itemc.getTimeSpent()));

            // process item score
            final DecimalVariable scoreVar = (DecimalVariable) (itemc.getVariables().getSCOREVariable());
            final Element it_score = itres.addElement("outcomes").addElement("score");
            it_score.addAttribute("varname", "SCORE");
            it_score.addElement("score_value")
                    .addText(StringHelper.formatFloat(scoreVar.getTruncatedValue(), 2));
            strVal = scoreVar.hasMinValue() ? "" + scoreVar.getMinValue() : "0.0";
            it_score.addElement("score_min").addText(strVal);
            strVal = scoreVar.hasMaxValue() ? "" + scoreVar.getMaxValue() : "N/A";
            it_score.addElement("score_max").addText(strVal);
            strVal = scoreVar.hasCutValue() ? "" + scoreVar.getCutValue() : "N/A";
            it_score.addElement("score_cut").addText(strVal);

            final Element el_item = itemc.getEl_item();
            final Map res_responsehash = new HashMap(3);

            // iterate over all responses of this item
            final List resps = el_item.selectNodes(
                    ".//response_lid|.//response_xy|.//response_str|.//response_num|.//response_grp");
            for (final Iterator it_resp = resps.iterator(); it_resp.hasNext();) {
                final Element resp = (Element) it_resp.next();
                final String ident = resp.attributeValue("ident");
                final String rcardinality = resp.attributeValue("rcardinality");
                final String rtiming = resp.attributeValue("rtiming");

                // add new response
                final Element res_response = itres.addElement("response");
                res_response.addAttribute("ident_ref", ident);
                res_responsehash.put(ident, res_response); // enable lookup of
                // @identref of <response>
                // (needed with <varequal>
                // elements

                // add new response_form
                // <response_lid ident="MR01" rcardinality="Multiple" rtiming="No">
                final Element res_responseform = res_response.addElement("response_form");
                res_responseform.addAttribute("cardinality", rcardinality);
                res_responseform.addAttribute("timing", rtiming);
                final String respName = resp.getName();
                final String type = respName.substring(respName.indexOf("_") + 1);
                res_responseform.addAttribute("response_type", type);

                // add user answer
                final ItemInput itemInp = itemc.getItemInput();
                final Translator trans = Util.createPackageTranslator(QTIModule.class, locale);
                if (itemInp == null) { // user did not answer this question at all
                    res_response.addElement("response_value").addText(trans.translate("ResBuilder.NoAnswer"));
                } else {
                    final List userAnswer = itemInp.getAsList(ident);
                    if (userAnswer == null) { // user did not answer this question at
                        // all
                        res_response.addElement("response_value")
                                .addText(trans.translate("ResBuilder.NoAnswer"));
                    } else { // the user chose at least one option of an answer (did not
                             // simply click send)
                        for (final Iterator it_ans = userAnswer.iterator(); it_ans.hasNext();) {
                            res_response.addElement("response_value").addText((String) it_ans.next());
                        }
                    }
                }

            }

            /*
             * The simple element correct_response can only list correct elements, that is, no "or" or "and" elements may be in the conditionvar. Pragmatic solution:
             * if condition has ors or ands, then put whole conditionvar into <extension_response> (proprietary), and for easier cases (just "varequal" "not"
             * elements) use correct_response.
             */

            final Map corr_answers = new HashMap(); // keys: respIdents, values: HashSet
            // of correct answers for this
            // respIdent
            final List respconds = el_item.selectNodes(".//respcondition");
            for (final Iterator it_respc = respconds.iterator(); it_respc.hasNext();) {
                final Element el_respc = (Element) it_respc.next();

                // check for add/set in setvar elements (check for single instance
                // only -> spec allows for multiple instances)
                final Element el_setvar = (Element) el_respc.selectSingleNode(".//setvar");
                if (el_setvar == null) {
                    continue;
                }
                if (el_setvar.attributeValue("action").equals("Add")
                        || el_setvar.attributeValue("action").equals("Set")) {
                    // This resrocessing gives points -> assume correct answer
                    float numPoints = 0;
                    try {
                        numPoints = Float.parseFloat(el_setvar.getTextTrim());
                    } catch (final NumberFormatException nfe) {
                        //
                    }
                    if (numPoints <= 0) {
                        continue;
                    }
                    Element conditionvar = (Element) el_respc.selectSingleNode(".//conditionvar");
                    // there is an evaluation defined (a "resprocessing" element exists)
                    // if (xpath(count(.//varequal) + count(.//not) = count(.//*)) is
                    // true, then there are only "not" and "varequal" elements
                    final XPath xCanHandle = DocumentHelper
                            .createXPath("count(.//varequal) + count(.//not) = count(.//*)");
                    boolean canHandle = xCanHandle.matches(conditionvar);
                    if (!canHandle) { // maybe we have <condvar> <and> <...>, try again
                        final Element el_and = (Element) conditionvar.selectSingleNode("and");
                        if (el_and != null) {
                            canHandle = xCanHandle.matches(el_and);
                            if (canHandle) { // simultate the el_and to be the conditionvar
                                conditionvar = el_and;
                            }
                        } else { // and finally, maybe we have an <or> element ..
                            final Element el_or = (Element) conditionvar.selectSingleNode("or");
                            if (el_or != null) {
                                canHandle = xCanHandle.matches(el_or);
                                if (canHandle) { // simultate the el_and to be the conditionvar
                                    conditionvar = el_or;
                                }
                            }
                        }
                    }

                    if (!canHandle) {
                        // qti res 1.2.1 can't handle it
                        final Element condcopy = conditionvar.createCopy();
                        itres.addElement("extension_item_result").add(condcopy);
                    } else {
                        /*
                         * easy case: get all varequal directly under the conditionvar element and assume the "not" elements do not contain "not" elements again...
                         * <!ELEMENT response (qti_comment? , response_form? , num_attempts? , response_value* , extension_response?)> <!ELEMENT response_form
                         * (correct_response* , extension_responseform?)> <!ELEMENT correct_response (#PCDATA)>
                         */
                        final List vareqs = conditionvar.selectNodes("./varequal");
                        for (final Iterator it_vareq = vareqs.iterator(); it_vareq.hasNext();) {
                            /*
                             * get the identifier of the response, so that we can attach the <correct_response> to the right <response> element quote: ims qti asi xml
                             * binding :3.6.23.1 <varequal> Element: respident (required). The identifier of the corresponding <response_lid>, <response_xy>, etc.
                             * element (this was assigned using its ident attribute).
                             */
                            final Element vareq = (Element) it_vareq.next();
                            final String respIdent = vareq.attributeValue("respident");
                            Set respIdent_corr_answers = (Set) corr_answers.get(respIdent);
                            if (respIdent_corr_answers == null) {
                                respIdent_corr_answers = new HashSet(3);
                            }
                            respIdent_corr_answers.add(vareq.getText());
                            corr_answers.put(respIdent, respIdent_corr_answers);
                        } // for varequal
                    } // else varequal
                } // add/set setvar
            } // for resprocessing
            final Set resp_ids = corr_answers.keySet();
            for (final Iterator idents = resp_ids.iterator(); idents.hasNext();) {
                final String respIdent = (String) idents.next();
                final Set respIdent_corr_answers = (Set) corr_answers.get(respIdent);
                final Element res_response = (Element) res_responsehash.get(respIdent);
                final Element res_respform = res_response.element("response_form");
                for (final Iterator iter = respIdent_corr_answers.iterator(); iter.hasNext();) {
                    final String answer = (String) iter.next();
                    res_respform.addElement("correct_response").addText(answer);
                }
            }
        } // for response_xy
    }
    return res_doc;
}

From source file:org.onecmdb.core.utils.graph.query.XMLGraphQuery.java

License:Open Source License

private ItemSelector parseXMLSelector(Element el) {
    String id = el.attributeValue("id");
    ItemSelector selector = selectorMap.get(id);
    if (selector != null) {
        return (selector);
    }/*from   w w  w  . ja  va  2  s. c om*/
    if (el.getName().equals("ItemAliasSelector")) {
        ItemAliasSelector aSelector = new ItemAliasSelector();
        aSelector.setId(id);
        selectorMap.put(id, aSelector);

        Element alias = el.element("alias");
        aSelector.setAlias(alias.getTextTrim());
        selector = aSelector;
    } else if (el.getName().equals("ItemRelationSelector")) {
        ItemRelationSelector rSelector = new ItemRelationSelector();
        rSelector.setId(id);
        selectorMap.put(id, rSelector);

        Element source = el.element("source");
        Element target = el.element("target");

        rSelector.setSource(source.getTextTrim());

        rSelector.setTarget(target.getTextTrim());

        selector = rSelector;
    } else if (el.getName().equals("ItemOffspringSelector")) {
        ItemOffspringSelector oSelector = new ItemOffspringSelector();
        oSelector.setId(id);
        selectorMap.put(id, oSelector);

        Element template = el.element("template");
        oSelector.setTemplateAlias(template.getTextTrim());
    }

    ItemConstraint constraint = parseXMLConstraint(el.element("constraint"));
    selector.applyConstraint(constraint);
    return (null);
}

From source file:org.onecmdb.core.utils.graph.query.XMLGraphQuery.java

License:Open Source License

private String getElementText(Element el, String name) {
    Element s = el.element(name);
    if (s == null) {
        throw new IllegalArgumentException("Element " + el.getName() + " missing element " + name);
    }/* w  w  w .ja v  a 2  s.  c  o m*/
    return (s.getTextTrim());
}

From source file:org.onecmdb.core.utils.transform.SimpleTransformProvider.java

License:Open Source License

/**
 * XML helper functions/*from  w w w  .  j av a  2 s  . c  o m*/
 */
private String getElementValue(Element sel, String elementName, boolean requiered) {

    Element el = sel.element(elementName);
    if (el == null) {
        if (requiered) {
            throw new IllegalArgumentException("Element <" + elementName + "> is missing in <" + sel.getName()
                    + "> [" + sel.getPath() + "]");
        }
        return (null);
    }
    String text = el.getTextTrim();
    if (requiered && (text == null || text.length() == 0)) {
        throw new IllegalArgumentException("Element <" + elementName + "> has no value in <" + sel.getName()
                + "> [" + sel.getPath() + "]");
    }
    return (text);
}

From source file:org.onecmdb.core.utils.xml.XmlParser.java

License:Open Source License

public CiBean parseBlueprint(Element ci) {
    if (!ci.getName().equals(TEMPLATE_ELEMENT.getName())) {
        throw new IllegalAccessError(
                "Unknown element <" + ci.getName() + "> must be <" + TEMPLATE_ELEMENT.getName() + ">");
    }//from   w  w w . j  a v  a2 s  . c o m
    String alias = getAttributeValue(ci, ALIAS_ATTR, null);
    if (alias == null) {
        throw new IllegalAccessError("Alias must be specified on element <" + ci.getName() + ">");
    }
    String instanceNameExpression = getAttributeValue(ci, INSTANCE_NAME_EXPRESSION_ATTR, null);
    //log.debug("found template " + alias);

    String id = getAttributeValue(ci, ID_ATTR, null);
    CiBean ciBean = new CiBean();
    ciBean.setAlias(alias);
    ciBean.setDisplayNameExpression(instanceNameExpression);
    ciBean.setTemplate(true);

    String group = getAttributeValue(ci, GROUP_ATTR, null);
    ciBean.setGroup(group);

    if (id != null) {
        ciBean.setId(Long.parseLong(id));
    }

    List<Element> attributes = ci.elements();
    List<AttributeBean> aBeans = new ArrayList<AttributeBean>();
    for (Element el : attributes) {
        if (el.getName().equals(ATTRIBUTE_ELEMENT.getName())) {
            String attrAlias = getAttributeValue(el, ATT_ALIAS_ATTR, null);
            String name = getAttributeValue(el, NAME_ATTR, null);
            String derived = getAttributeValue(el, ATTR_DERIVED, "false");
            String attrId = getAttributeValue(el, ID_ATTR, null);

            AttributeBean aBean = new AttributeBean();
            aBean.setDisplayName(name);
            aBean.setAlias(attrAlias);
            aBean.setDerived(Boolean.parseBoolean(derived));
            if (attrId != null) {
                aBean.setId(Long.parseLong(attrId));
            }
            for (Element aEl : (List<Element>) el.elements()) {
                if (aEl.getName().equals(SIMPLE_TYPE_ELEMENT.getName())) {
                    aBean.setType(aEl.getTextTrim());
                    aBean.setComplexType(false);
                }
                if (aEl.getName().equals(POLICY_ELEMENT.getName())) {
                    Element max = aEl.element(MAX_OCCURS_ELEMENT.getName());
                    if (max != null) {
                        aBean.setMaxOccurs(max.getTextTrim());
                    }
                    Element min = aEl.element(MIN_OCCURS_ELEMENT.getName());
                    if (min != null) {
                        aBean.setMinOccurs(min.getTextTrim());
                    }
                }
                if (aEl.getName().equals(COMPLEX_TYPE_ELEMENT.getName())) {
                    Element ref = aEl.element(REF_ELEMENT.getName());
                    if (ref == null) {
                        throw new IllegalAccessError(
                                "Missing element <" + REF_ELEMENT.getName() + "> in element <" + aEl.getName()
                                        + "> template=" + alias + ", attribute=" + attrAlias);
                    }
                    Element refType = aEl.element(REF_TYPE_ELEMENT.getName());
                    // It's ok, atleast for references.
                    String refTypeAlias = null;
                    if (refType != null) {
                        /*
                        throw new IllegalAccessError("Missing element <"
                              + REF_TYPE_ELEMENT.getName()
                              + "> in element <" + aEl.getName()
                              + ">  template=" + alias + ", attribute="
                              + attrAlias);
                        */

                        Element refTypeRef = refType.element(REF_ELEMENT.getName());
                        if (refTypeRef == null) {
                            throw new IllegalAccessError("Missing element <" + REF_ELEMENT.getName()
                                    + "> in element <" + refType.getName() + "> template=" + alias
                                    + ", attribute=" + attrAlias);
                        }
                        refTypeAlias = getAttributeValue(refTypeRef, ALIAS_ATTR, null);

                    }
                    String refAlias = getAttributeValue(ref, ALIAS_ATTR, null);
                    aBean.setRefType(refTypeAlias);
                    aBean.setType(refAlias);
                    aBean.setComplexType(true);
                }
                if (aEl.getName().equals(DESCRIPTION_ELEMENT.getName())) {

                    aBean.setDescription(aEl.getTextTrim());
                }
                if (aEl.getName().equals(SET_SIMPLE_VALUE_ELEMENT.getName())) {
                    ValueBean vBean = new ValueBean();
                    String vId = getAttributeValue(aEl, ID_ATTR, null);
                    if (vId != null) {
                        vBean.setId(Long.parseLong(vId));
                    }
                    vBean.setValue(getValue(aEl));
                    vBean.setAlias(attrAlias);
                    vBean.setComplexValue(false);
                    ciBean.addAttributeValue(vBean);
                }
                if (el.getName().equals(SET_COMPLEX_VALUE_ELEMENT.getName())) {
                    ValueBean vBean = new ValueBean();
                    String vId = getAttributeValue(aEl, ID_ATTR, null);
                    if (vId != null) {
                        vBean.setId(Long.parseLong(vId));
                    }
                    Element ref = aEl.element(REF_ELEMENT.getName());
                    if (ref == null) {
                        throw new IllegalAccessError(
                                "Missing element <" + REF_ELEMENT.getName() + "> in element <" + el.getName()
                                        + "> template=" + alias + ", attribute=" + attrAlias);
                    }
                    String aliasValue = getAttributeValue(ref, ALIAS_ATTR, null);
                    vBean.setValue(aliasValue);
                    vBean.setComplexValue(true);

                    vBean.setAlias(attrAlias);
                    ciBean.addAttributeValue(vBean);
                }
            }
            ciBean.addAttribute(aBean);
        } else if (el.getName().equals(SET_SIMPLE_VALUE_ELEMENT.getName())) {
            String attrAlias = getAttributeValue(el, ATT_ALIAS_ATTR, null);
            ValueBean vBean = new ValueBean();

            String vId = getAttributeValue(el, ID_ATTR, null);
            if (vId != null) {
                vBean.setId(Long.parseLong(vId));
            }

            vBean.setValue(getValue(el));
            vBean.setAlias(attrAlias);
            vBean.setComplexValue(false);
            ciBean.addAttributeValue(vBean);
        } else if (el.getName().equals(SET_COMPLEX_VALUE_ELEMENT.getName())) {
            String attrAlias = getAttributeValue(el, ATT_ALIAS_ATTR, null);
            ValueBean vBean = new ValueBean();
            String vId = getAttributeValue(el, ID_ATTR, null);
            if (vId != null) {
                vBean.setId(Long.parseLong(vId));
            }

            Element ref = el.element(REF_ELEMENT.getName());
            if (ref == null) {
                throw new IllegalAccessError("Missing element <" + REF_ELEMENT.getName() + "> in element <"
                        + el.getName() + "> template=" + alias + ", attribute=" + attrAlias);
            }
            String aliasValue = getAttributeValue(ref, ALIAS_ATTR, null);
            vBean.setValue(aliasValue);
            vBean.setComplexValue(true);

            vBean.setAlias(attrAlias);
            ciBean.addAttributeValue(vBean);
        } else if (el.getName().equals(DERIVED_FROM_ELEMENT.getName())) {
            Element ref = el.element(REF_ELEMENT.getName());
            if (ref == null) {
                throw new IllegalAccessError("Missing element <" + REF_ELEMENT.getName() + "> in element <"
                        + el.getName() + "> template=" + alias);
            }
            String aliasValue = getAttributeValue(ref, ALIAS_ATTR, null);
            ciBean.setDerivedFrom(aliasValue);
        } else if (el.getName().equals(DESCRIPTION_ELEMENT.getName())) {
            ciBean.setDescription(el.getTextTrim());
        } else {
            throw new IllegalAccessError("Unkown element <" + el.getName() + "> in element <" + ci.getName()
                    + "> template=" + alias);
        }
    }
    // Validate alias and derivedFrom
    if (ciBean.getAlias() == null) {
        throw new IllegalArgumentException("No alias specified on element '" + ci.getName() + "'");
    }
    if (ciBean.getDerivedFrom() == null) {
        //log.warn("No derivedFrom specified on element '" + ciBean.getAlias() + "'");
        //throw new IllegalArgumentException("No derivedFrom specified on element '" + ciBean.getAlias() + "'");
    }

    return (ciBean);
}

From source file:org.onecmdb.core.utils.xml.XmlParser.java

License:Open Source License

private String getValue(Element el) {
    String trimmedValue = el.getTextTrim();
    if (trimmedValue == null) {
        return (null);
    }/*from   w  ww.j  a va2  s  . c om*/
    if (trimmedValue.equals("")) {
        return (null);
    }
    return (trimmedValue);
}

From source file:org.onecmdb.nagios.Nagios2OneCMDB.java

License:Open Source License

private String getElementValue(Element sel, String elementName, boolean requiered) {

    Element el = sel.element(elementName);
    if (el == null) {
        if (requiered) {
            throw new IllegalArgumentException("Element <" + elementName + "> is missing in <" + sel.getName()
                    + "> [" + sel.getPath() + "]");
        }/*  w w w . j  a v  a 2  s. c  om*/
        return (null);
    }

    String text = el.getTextTrim();

    return (text);
}

From source file:org.onecmdb.ui.gwt.desktop.server.service.content.adapter.GXTModelContentAdapter.java

License:Open Source License

public BaseModel updateModel(Element el, BaseModel parent) throws Exception {

    //System.out.println(el.getName());
    String className = classMap.getProperty(el.getName());
    if (className == null) {
        className = ConfigurationFactory.get("gxtadapter." + el.getName() + ".class");
        if (className == null) {
            className = BaseModel.class.getName();
        }//  w w  w .j  av a 2s. c  om
        //throw new IllegalArgumentException(el.getName() + " has no class definition");
    }
    Class clazz = Class.forName(className);
    Object object = clazz.newInstance();
    if (!(object instanceof BaseModel)) {
        throw new IllegalArgumentException(
                el.getName() + " class " + className + " is not implementing BaseModel");
    }

    BaseModel model = (BaseModel) object;
    if (parent == null) {
        parent = model;
    }
    model.set("tag", el.getName());
    for (Attribute a : (List<Attribute>) el.attributes()) {
        updateModelValue(model, a.getName(), a.getText(), false);
    }
    for (Element e : (List<Element>) el.elements()) {
        boolean asList = false;
        Attribute a = e.attribute("asList");
        if (a != null) {
            asList = true;
        }
        boolean simpleList = false;
        a = e.attribute("asSimpleList");
        if (a != null) {
            asList = true;
            simpleList = true;
        }

        if (isSimpleElement(e) || simpleList) {
            updateModelValue(model, e.getName(), e.getTextTrim(), asList);
        } else {
            updateModelValue(model, e.getName(), updateModel(e, model), asList);
        }
    }
    return (model);
}