Search in sources :

Example 11 with Element

use of org.kxml2.kdom.Element in project javarosa by opendatakit.

the class ChildProcessingTest method discoversNonElementChild.

@Test
public void discoversNonElementChild() {
    Element el = new Element();
    el.addChild(COMMENT, "A string");
    assertFalse(XFormParser.childOptimizationsOk(el));
}
Also used : Element(org.kxml2.kdom.Element) Test(org.junit.Test)

Example 12 with Element

use of org.kxml2.kdom.Element in project javarosa by opendatakit.

the class SubmissionParserTest method parseSubmission.

@Test
public void parseSubmission() throws Exception {
    // Given
    final SubmissionParser submissionParser = new SubmissionParser();
    final Element element = new Element();
    element.setAttribute(null, "mediatype", "application/xml");
    element.setAttribute(null, "custom_attribute", "custom value");
    final String method = "POST";
    final String action = "ACTION";
    final IDataReference ref = new DummyReference();
    // When
    final SubmissionProfile submissionProfile = submissionParser.parseSubmission(method, action, ref, element);
    // Then
    assertEquals(action, submissionProfile.getAction());
    assertEquals(method, submissionProfile.getMethod());
    assertEquals(ref, submissionProfile.getRef());
    assertEquals("application/xml", submissionProfile.getMediaType());
    assertEquals("custom value", submissionProfile.getAttribute("custom_attribute"));
}
Also used : DummyReference(org.javarosa.core.model.test.DummyReference) IDataReference(org.javarosa.core.model.IDataReference) Element(org.kxml2.kdom.Element) SubmissionProfile(org.javarosa.core.model.SubmissionProfile) Test(org.junit.Test)

Example 13 with Element

use of org.kxml2.kdom.Element in project javarosa by opendatakit.

the class XFormParser method parseItem.

private void parseItem(QuestionDef q, Element e) {
    final int MAX_VALUE_LEN = 32;
    // catalogue of used attributes in this method/element
    List<String> usedAtts = new ArrayList<>();
    List<String> labelUA = new ArrayList<>();
    List<String> valueUA = new ArrayList<>();
    labelUA.add(REF_ATTR);
    valueUA.add(FORM_ATTR);
    String labelInnerText = null;
    String textRef = null;
    String value = null;
    for (int i = 0; i < e.getChildCount(); i++) {
        int type = e.getType(i);
        Element child = (type == Node.ELEMENT ? e.getElement(i) : null);
        String childName = (child != null ? child.getName() : null);
        if (LABEL_ELEMENT.equals(childName)) {
            // print attribute warning for child element
            if (XFormUtils.showUnusedAttributeWarning(child, labelUA)) {
                reporter.warning(XFormParserReporter.TYPE_UNKNOWN_MARKUP, XFormUtils.unusedAttWarning(child, labelUA), getVagueLocation(child));
            }
            labelInnerText = getLabel(child);
            String ref = child.getAttributeValue("", REF_ATTR);
            if (ref != null) {
                if (ref.startsWith(ITEXT_OPEN) && ref.endsWith(ITEXT_CLOSE)) {
                    textRef = ref.substring(ITEXT_OPEN.length(), ref.lastIndexOf(ITEXT_CLOSE));
                    verifyTextMappings(textRef, "Item <label>", true);
                } else {
                    throw new XFormParseException("malformed ref [" + ref + "] for <item>", child);
                }
            }
        } else if (VALUE.equals(childName)) {
            value = getXMLText(child, true);
            // print attribute warning for child element
            if (XFormUtils.showUnusedAttributeWarning(child, valueUA)) {
                reporter.warning(XFormParserReporter.TYPE_UNKNOWN_MARKUP, XFormUtils.unusedAttWarning(child, valueUA), getVagueLocation(child));
            }
            if (value != null) {
                if (value.length() > MAX_VALUE_LEN) {
                    reporter.warning(XFormParserReporter.TYPE_ERROR_PRONE, "choice value [" + value + "] is too long; max. suggested length " + MAX_VALUE_LEN + " chars", getVagueLocation(child));
                }
                // validate
                for (int k = 0; k < value.length(); k++) {
                    char c = value.charAt(k);
                    if (" \n\t\f\r\'\"`".indexOf(c) >= 0) {
                        boolean isMultiSelect = (q.getControlType() == Constants.CONTROL_SELECT_MULTI);
                        reporter.warning(XFormParserReporter.TYPE_ERROR_PRONE, (isMultiSelect ? SELECT : SELECTONE) + " question <value>s [" + value + "] " + (isMultiSelect ? "cannot" : "should not") + " contain spaces, and are recommended not to contain apostraphes/quotation marks", getVagueLocation(child));
                        break;
                    }
                }
            }
        }
    }
    if (textRef == null && labelInnerText == null) {
        throw new XFormParseException("<item> without proper <label>", e);
    }
    if (value == null) {
        throw new XFormParseException("<item> without proper <value>", e);
    }
    if (textRef != null) {
        q.addSelectChoice(new SelectChoice(textRef, value));
    } else {
        q.addSelectChoice(new SelectChoice(null, labelInnerText, value, false));
    }
    // print unused attribute warning message for parent element
    if (XFormUtils.showUnusedAttributeWarning(e, usedAtts)) {
        reporter.warning(XFormParserReporter.TYPE_UNKNOWN_MARKUP, XFormUtils.unusedAttWarning(e, usedAtts), getVagueLocation(e));
    }
}
Also used : SelectChoice(org.javarosa.core.model.SelectChoice) TreeElement(org.javarosa.core.model.instance.TreeElement) AbstractTreeElement(org.javarosa.core.model.instance.AbstractTreeElement) Element(org.kxml2.kdom.Element) IFormElement(org.javarosa.core.model.IFormElement) ArrayList(java.util.ArrayList)

Example 14 with Element

use of org.kxml2.kdom.Element in project javarosa by opendatakit.

the class XFormParser method parseIText.

private void parseIText(Element itext) {
    Localizer l = new Localizer(true, true);
    // used for warning message
    ArrayList<String> usedAtts = new ArrayList<>();
    for (int i = 0; i < itext.getChildCount(); i++) {
        Element trans = itext.getElement(i);
        if (trans == null || !trans.getName().equals("translation"))
            continue;
        parseTranslation(l, trans);
    }
    if (l.getAvailableLocales().length == 0)
        throw new XFormParseException("no <translation>s defined", itext);
    if (l.getDefaultLocale() == null)
        l.setDefaultLocale(l.getAvailableLocales()[0]);
    // print unused attribute warning message for parent element
    if (XFormUtils.showUnusedAttributeWarning(itext, usedAtts)) {
        reporter.warning(XFormParserReporter.TYPE_UNKNOWN_MARKUP, XFormUtils.unusedAttWarning(itext, usedAtts), getVagueLocation(itext));
    }
    localizer = l;
}
Also used : TreeElement(org.javarosa.core.model.instance.TreeElement) AbstractTreeElement(org.javarosa.core.model.instance.AbstractTreeElement) Element(org.kxml2.kdom.Element) IFormElement(org.javarosa.core.model.IFormElement) ArrayList(java.util.ArrayList) Localizer(org.javarosa.core.services.locale.Localizer)

Example 15 with Element

use of org.kxml2.kdom.Element in project javarosa by opendatakit.

the class XFormParser method parseDoc.

private void parseDoc(Map<String, String> namespacePrefixesByUri) {
    final CodeTimer codeTimer = new CodeTimer("Creating FormDef from parsed XML");
    _f = new FormDef();
    initState();
    final String defaultNamespace = _xmldoc.getRootElement().getNamespaceUri(null);
    parseElement(_xmldoc.getRootElement(), _f, topLevelHandlers);
    collapseRepeatGroups(_f);
    final FormInstanceParser instanceParser = new FormInstanceParser(_f, defaultNamespace, reporter, bindings, repeats, itemsets, selectOnes, selectMultis, actionTargets);
    // if this assumption is wrong, well, then we're screwed.
    if (instanceNodes.size() > 1) {
        for (int instanceIndex = 1; instanceIndex < instanceNodes.size(); instanceIndex++) {
            final Element instance = instanceNodes.get(instanceIndex);
            final String instanceId = instanceNodeIdStrs.get(instanceIndex);
            final String ediPath = getPathIfExternalDataInstance(instance.getAttributeValue(null, "src"));
            if (ediPath != null) {
                try {
                    /* todo implement better error handling */
                    _f.addNonMainInstance(ExternalDataInstance.buildFromPath(ediPath, instanceId));
                } catch (IOException | UnfullfilledRequirementsException | InvalidStructureException | XmlPullParserException e) {
                    e.printStackTrace();
                }
            } else {
                FormInstance fi = instanceParser.parseInstance(instance, false, instanceNodeIdStrs.get(instanceNodes.indexOf(instance)), namespacePrefixesByUri);
                // same situation as below
                loadNamespaces(_xmldoc.getRootElement(), fi);
                loadInstanceData(instance, fi.getRoot(), _f);
                _f.addNonMainInstance(fi);
            }
        }
    }
    // now parse the main instance
    if (mainInstanceNode != null) {
        FormInstance fi = instanceParser.parseInstance(mainInstanceNode, true, instanceNodeIdStrs.get(instanceNodes.indexOf(mainInstanceNode)), namespacePrefixesByUri);
        /*
             Load namespaces definition (map of prefixes -> URIs) into a form instance so later it can be used
             during the form instance serialization (XFormSerializingVisitor#visit). If the map is not present, then
             serializer will provide own prefixes for the namespaces present in the nodes.
             This will lead to inconsistency between prefixes used in the form definition (bindings)
             and prefixes in the form instance after the instance is restored and inserted into the form definition.
             */
        loadNamespaces(_xmldoc.getRootElement(), fi);
        addMainInstanceToFormDef(mainInstanceNode, fi);
    }
    // Clear the caches, as these may not have been initialized
    // entirely correctly during the validation steps.
    Enumeration<DataInstance> e = _f.getNonMainInstances();
    while (e.hasMoreElements()) {
        DataInstance instance = e.nextElement();
        final AbstractTreeElement treeElement = instance.getRoot();
        if (treeElement instanceof TreeElement) {
            ((TreeElement) treeElement).clearChildrenCaches();
        }
        treeElement.clearCaches();
    }
    _f.getMainInstance().getRoot().clearChildrenCaches();
    _f.getMainInstance().getRoot().clearCaches();
    codeTimer.logDone();
}
Also used : AbstractTreeElement(org.javarosa.core.model.instance.AbstractTreeElement) ExternalDataInstance.getPathIfExternalDataInstance(org.javarosa.core.model.instance.ExternalDataInstance.getPathIfExternalDataInstance) DataInstance(org.javarosa.core.model.instance.DataInstance) ExternalDataInstance(org.javarosa.core.model.instance.ExternalDataInstance) UnfullfilledRequirementsException(org.javarosa.xml.util.UnfullfilledRequirementsException) TreeElement(org.javarosa.core.model.instance.TreeElement) AbstractTreeElement(org.javarosa.core.model.instance.AbstractTreeElement) Element(org.kxml2.kdom.Element) IFormElement(org.javarosa.core.model.IFormElement) InvalidStructureException(org.javarosa.xml.util.InvalidStructureException) IOException(java.io.IOException) TreeElement(org.javarosa.core.model.instance.TreeElement) AbstractTreeElement(org.javarosa.core.model.instance.AbstractTreeElement) FormDef(org.javarosa.core.model.FormDef) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) FormInstance(org.javarosa.core.model.instance.FormInstance) CodeTimer(org.javarosa.core.util.CodeTimer)

Aggregations

Element (org.kxml2.kdom.Element)50 TreeElement (org.javarosa.core.model.instance.TreeElement)25 AbstractTreeElement (org.javarosa.core.model.instance.AbstractTreeElement)23 ArrayList (java.util.ArrayList)21 IOException (java.io.IOException)17 IFormElement (org.javarosa.core.model.IFormElement)17 KXmlParser (org.kxml2.io.KXmlParser)12 XmlPullParserException (org.xmlpull.v1.XmlPullParserException)12 File (java.io.File)8 Test (org.junit.Test)7 ParsingException (org.opendatakit.briefcase.model.ParsingException)7 XmlPullParser (org.xmlpull.v1.XmlPullParser)7 Document (org.kxml2.kdom.Document)6 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 FileInputStream (java.io.FileInputStream)3 FileNotFoundException (java.io.FileNotFoundException)3 OutputStreamWriter (java.io.OutputStreamWriter)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 HashMap (java.util.HashMap)3 KXmlSerializer (org.kxml2.io.KXmlSerializer)3