Search in sources :

Example 6 with ParsingException

use of org.opendatakit.briefcase.model.ParsingException in project briefcase by opendatakit.

the class ServerUploader method subtractServerInstances.

// remove any instances already completed on server
private void subtractServerInstances(FormStatus fs, DatabaseUtils formDatabase, Set<File> instancesToUpload) {
    /*
     * The /view/submissionList interface returns the list of COMPLETED submissions
     * on the server. Fetch this list and filter out the locally-held submissions
     * with the same instanceIds.  We know the server is already content with what
     * it has, so we don't need to send any of these to the server, as that POST
     * request will be treated as a no-op.
     */
    String baseUrl = serverInfo.getUrl() + "/view/submissionList";
    String oldWebsafeCursorString = "not-empty";
    String websafeCursorString = "";
    for (; !oldWebsafeCursorString.equals(websafeCursorString); ) {
        if (isCancelled()) {
            fs.setStatusString("aborting retrieval of instanceIds of submissions on server...", true);
            EventBus.publish(new FormStatusEvent(fs));
            return;
        }
        fs.setStatusString("retrieving next chunk of instanceIds from server...", true);
        EventBus.publish(new FormStatusEvent(fs));
        Map<String, String> params = new HashMap<>();
        params.put("numEntries", Integer.toString(MAX_ENTRIES));
        params.put("formId", fs.getFormDefinition().getFormId());
        params.put("cursor", websafeCursorString);
        String fullUrl = WebUtils.createLinkWithProperties(baseUrl, params);
        // remember what we had...
        oldWebsafeCursorString = websafeCursorString;
        AggregateUtils.DocumentFetchResult result;
        try {
            DocumentDescription submissionChunkDescription = new DocumentDescription("Fetch of instanceIds (submission download chunk) failed.  Detailed error: ", "Fetch of instanceIds (submission download chunk) failed.", "submission download chunk", terminationFuture);
            result = AggregateUtils.getXmlDocument(fullUrl, serverInfo, false, submissionChunkDescription, null);
        } catch (XmlDocumentFetchException e) {
            fs.setStatusString("Not all submissions retrieved: Error fetching list of instanceIds: " + e.getMessage(), false);
            EventBus.publish(new FormStatusEvent(fs));
            return;
        }
        SubmissionChunk chunk;
        try {
            chunk = XmlManipulationUtils.parseSubmissionDownloadListResponse(result.doc);
        } catch (ParsingException e) {
            fs.setStatusString("Not all instanceIds retrieved: Error parsing the submission download chunk: " + e.getMessage(), false);
            EventBus.publish(new FormStatusEvent(fs));
            return;
        }
        websafeCursorString = chunk.websafeCursorString;
        for (String uri : chunk.uriList) {
            File f = formDatabase.hasRecordedInstance(uri);
            if (f != null) {
                instancesToUpload.remove(f);
            }
        }
    }
}
Also used : XmlDocumentFetchException(org.opendatakit.briefcase.model.XmlDocumentFetchException) DocumentDescription(org.opendatakit.briefcase.model.DocumentDescription) HashMap(java.util.HashMap) FormStatusEvent(org.opendatakit.briefcase.model.FormStatusEvent) ParsingException(org.opendatakit.briefcase.model.ParsingException) DocumentFetchResult(org.opendatakit.briefcase.util.AggregateUtils.DocumentFetchResult) SubmissionChunk(org.opendatakit.briefcase.util.ServerFetcher.SubmissionChunk) File(java.io.File)

Example 7 with ParsingException

use of org.opendatakit.briefcase.model.ParsingException in project briefcase by opendatakit.

the class XmlManipulationUtils method parseXml.

public static Document parseXml(File submission) throws ParsingException, FileSystemException {
    // parse the xml document...
    Document doc = null;
    try {
        InputStream is = null;
        InputStreamReader isr = null;
        try {
            is = new FileInputStream(submission);
            isr = new InputStreamReader(is, UTF_8);
            Document tempDoc = new Document();
            KXmlParser parser = new KXmlParser();
            parser.setInput(isr);
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
            tempDoc.parse(parser);
            isr.close();
            doc = tempDoc;
        } finally {
            if (isr != null) {
                try {
                    isr.close();
                } catch (Exception e) {
                // no-op
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                // no-op
                }
            }
        }
    } catch (XmlPullParserException e) {
        try {
            return BadXMLFixer.fixBadXML(submission);
        } catch (CannotFixXMLException e1) {
            File debugFileLocation = new File(new StorageLocation().getBriefcaseFolder(), "debug");
            try {
                if (!debugFileLocation.exists()) {
                    FileUtils.forceMkdir(debugFileLocation);
                }
                long checksum = FileUtils.checksumCRC32(submission);
                File debugFile = new File(debugFileLocation, "submission-" + checksum + ".xml");
                FileUtils.copyFile(submission, debugFile);
            } catch (IOException e2) {
                throw new RuntimeException(e2);
            }
            throw new ParsingException("Failed during parsing of submission Xml: " + e.toString());
        }
    } catch (IOException e) {
        throw new FileSystemException("Failed while reading submission xml: " + e.toString());
    }
    return doc;
}
Also used : CannotFixXMLException(org.opendatakit.briefcase.model.CannotFixXMLException) InputStreamReader(java.io.InputStreamReader) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) Document(org.kxml2.kdom.Document) FileInputStream(java.io.FileInputStream) FileSystemException(org.opendatakit.briefcase.model.FileSystemException) CannotFixXMLException(org.opendatakit.briefcase.model.CannotFixXMLException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) MetadataUpdateException(org.opendatakit.briefcase.model.MetadataUpdateException) FileNotFoundException(java.io.FileNotFoundException) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) ParsingException(org.opendatakit.briefcase.model.ParsingException) KXmlParser(org.kxml2.io.KXmlParser) FileSystemException(org.opendatakit.briefcase.model.FileSystemException) ParsingException(org.opendatakit.briefcase.model.ParsingException) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) StorageLocation(org.opendatakit.briefcase.ui.StorageLocation) MediaFile(org.opendatakit.briefcase.util.ServerFetcher.MediaFile) File(java.io.File)

Example 8 with ParsingException

use of org.opendatakit.briefcase.model.ParsingException in project briefcase by opendatakit.

the class XmlManipulationUtils method parseFormManifestResponse.

public static final List<MediaFile> parseFormManifestResponse(boolean isOpenRosaResponse, Document doc) throws ParsingException {
    List<MediaFile> files = new ArrayList<>();
    if (!isOpenRosaResponse) {
        log.error("Manifest reply doesn't report an OpenRosa version -- bad server?");
        throw new ParsingException(BAD_NOT_OPENROSA_MANIFEST);
    }
    // Attempt OpenRosa 1.0 parsing
    Element manifestElement = doc.getRootElement();
    if (!manifestElement.getName().equals("manifest")) {
        log.error("Root element is not <manifest> -- was " + manifestElement.getName());
        throw new ParsingException(BAD_NOT_OPENROSA_MANIFEST);
    }
    String namespace = manifestElement.getNamespace();
    if (!isXformsManifestNamespacedElement(manifestElement)) {
        log.error("Root element Namespace is incorrect: " + namespace);
        throw new ParsingException(BAD_NOT_OPENROSA_MANIFEST);
    }
    int nElements = manifestElement.getChildCount();
    for (int i = 0; i < nElements; ++i) {
        if (manifestElement.getType(i) != Element.ELEMENT) {
            // e.g., whitespace (text)
            continue;
        }
        Element mediaFileElement = (Element) manifestElement.getElement(i);
        if (!isXformsManifestNamespacedElement(mediaFileElement)) {
            // someone else's extension?
            continue;
        }
        String name = mediaFileElement.getName();
        if (name.equalsIgnoreCase("mediaFile")) {
            String filename = null;
            String hash = null;
            String downloadUrl = null;
            // don't process descriptionUrl
            int childCount = mediaFileElement.getChildCount();
            for (int j = 0; j < childCount; ++j) {
                if (mediaFileElement.getType(j) != Element.ELEMENT) {
                    // e.g., whitespace (text)
                    continue;
                }
                Element child = mediaFileElement.getElement(j);
                if (!isXformsManifestNamespacedElement(child)) {
                    // someone else's extension?
                    continue;
                }
                String tag = child.getName();
                if (tag.equals("filename")) {
                    filename = XFormParser.getXMLText(child, true);
                    if (filename != null && filename.length() == 0) {
                        filename = null;
                    }
                } else if (tag.equals("hash")) {
                    hash = XFormParser.getXMLText(child, true);
                    if (hash != null && hash.length() == 0) {
                        hash = null;
                    }
                } else if (tag.equals("downloadUrl")) {
                    downloadUrl = XFormParser.getXMLText(child, true);
                    if (downloadUrl != null && downloadUrl.length() == 0) {
                        downloadUrl = null;
                    }
                }
            }
            if (filename == null || downloadUrl == null || hash == null) {
                log.error("Manifest entry " + Integer.toString(i) + " is missing one or more tags: filename, hash, or downloadUrl");
                throw new ParsingException(BAD_NOT_OPENROSA_MANIFEST);
            }
            files.add(new MediaFile(filename, hash, downloadUrl));
        }
    }
    return files;
}
Also used : MediaFile(org.opendatakit.briefcase.util.ServerFetcher.MediaFile) ParsingException(org.opendatakit.briefcase.model.ParsingException) Element(org.kxml2.kdom.Element) ArrayList(java.util.ArrayList)

Example 9 with ParsingException

use of org.opendatakit.briefcase.model.ParsingException in project briefcase by opendatakit.

the class XmlManipulationUtils method parseDownloadSubmissionResponse.

public static final SubmissionManifest parseDownloadSubmissionResponse(Document doc) throws ParsingException {
    // and parse the document...
    List<MediaFile> attachmentList = new ArrayList<>();
    Element rootSubmissionElement = null;
    String instanceID = null;
    // Attempt parsing
    Element submissionElement = doc.getRootElement();
    if (!submissionElement.getName().equals("submission")) {
        String msg = "Parsing downloadSubmission reply -- root element is not <submission> :" + submissionElement.getName();
        log.error(msg);
        throw new ParsingException(msg);
    }
    String namespace = submissionElement.getNamespace();
    if (!namespace.equalsIgnoreCase(NAMESPACE_OPENDATAKIT_ORG_SUBMISSIONS)) {
        String msg = "Parsing downloadSubmission reply -- root element namespace is incorrect:" + namespace;
        log.error(msg);
        throw new ParsingException(msg);
    }
    int nElements = submissionElement.getChildCount();
    for (int i = 0; i < nElements; ++i) {
        if (submissionElement.getType(i) != Element.ELEMENT) {
            // e.g., whitespace (text)
            continue;
        }
        Element subElement = (Element) submissionElement.getElement(i);
        namespace = subElement.getNamespace();
        if (!namespace.equalsIgnoreCase(NAMESPACE_OPENDATAKIT_ORG_SUBMISSIONS)) {
            // someone else's extension?
            continue;
        }
        String name = subElement.getName();
        if (name.equalsIgnoreCase("data")) {
            // find the root submission element and get its instanceID attribute
            int nIdElements = subElement.getChildCount();
            for (int j = 0; j < nIdElements; ++j) {
                if (subElement.getType(j) != Element.ELEMENT) {
                    // e.g., whitespace (text)
                    continue;
                }
                rootSubmissionElement = (Element) subElement.getElement(j);
                break;
            }
            if (rootSubmissionElement == null) {
                throw new ParsingException("no submission body found in submissionDownload response");
            }
            instanceID = rootSubmissionElement.getAttributeValue(null, "instanceID");
            if (instanceID == null) {
                throw new ParsingException("instanceID attribute value is null");
            }
        } else if (name.equalsIgnoreCase("mediaFile")) {
            int nIdElements = subElement.getChildCount();
            String filename = null;
            String hash = null;
            String downloadUrl = null;
            for (int j = 0; j < nIdElements; ++j) {
                if (subElement.getType(j) != Element.ELEMENT) {
                    // e.g., whitespace (text)
                    continue;
                }
                Element mediaSubElement = (Element) subElement.getElement(j);
                name = mediaSubElement.getName();
                if (name.equalsIgnoreCase("filename")) {
                    filename = XFormParser.getXMLText(mediaSubElement, true);
                } else if (name.equalsIgnoreCase("hash")) {
                    hash = XFormParser.getXMLText(mediaSubElement, true);
                } else if (name.equalsIgnoreCase("downloadUrl")) {
                    downloadUrl = XFormParser.getXMLText(mediaSubElement, true);
                }
            }
            attachmentList.add(new MediaFile(filename, hash, downloadUrl));
        } else {
            log.warn("Unrecognized tag inside submission: " + name);
        }
    }
    if (rootSubmissionElement == null) {
        throw new ParsingException("No submission body found");
    }
    if (instanceID == null) {
        throw new ParsingException("instanceID attribute value is null");
    }
    // write submission to a string
    StringWriter fo = new StringWriter();
    KXmlSerializer serializer = new KXmlSerializer();
    serializer.setOutput(fo);
    // setting the response content type emits the xml header.
    // just write the body here...
    // this has the xmlns of the submissions download, indicating that it
    // originated from a briefcase download. Might be useful for discriminating
    // real vs. recovered data?
    rootSubmissionElement.setPrefix(null, NAMESPACE_OPENDATAKIT_ORG_SUBMISSIONS);
    try {
        rootSubmissionElement.write(serializer);
        serializer.flush();
        serializer.endDocument();
        fo.close();
    } catch (IOException e) {
        String msg = "Unexpected IOException";
        log.error(msg, e);
        throw new ParsingException(msg + ": " + e.getMessage());
    }
    return new SubmissionManifest(instanceID, fo.toString(), attachmentList);
}
Also used : MediaFile(org.opendatakit.briefcase.util.ServerFetcher.MediaFile) StringWriter(java.io.StringWriter) Element(org.kxml2.kdom.Element) ParsingException(org.opendatakit.briefcase.model.ParsingException) ArrayList(java.util.ArrayList) SubmissionManifest(org.opendatakit.briefcase.util.ServerFetcher.SubmissionManifest) IOException(java.io.IOException) KXmlSerializer(org.kxml2.io.KXmlSerializer)

Example 10 with ParsingException

use of org.opendatakit.briefcase.model.ParsingException in project briefcase by opendatakit.

the class XmlManipulationUtils method getFormInstanceMetadata.

public static FormInstanceMetadata getFormInstanceMetadata(Element root) throws ParsingException {
    // check for odk id
    String formId = root.getAttributeValue(null, FORM_ID_ATTRIBUTE_NAME);
    // if odk id is not present use namespace
    if (formId == null || formId.equalsIgnoreCase(EMPTY_STRING)) {
        String schema = root.getAttributeValue(null, NAMESPACE_ATTRIBUTE);
        // TODO: move this into FormDefinition?
        if (schema == null) {
            throw new ParsingException("Unable to extract form id");
        }
        formId = schema;
    }
    String modelVersionString = root.getAttributeValue(null, MODEL_VERSION_ATTRIBUTE_NAME);
    String instanceId = getOpenRosaInstanceId(root);
    if (instanceId == null) {
        instanceId = root.getAttributeValue(null, INSTANCE_ID_ATTRIBUTE_NAME);
    }
    String base64EncryptedFieldKey = getBase64EncryptedFieldKey(root);
    return new FormInstanceMetadata(new XFormParameters(formId, modelVersionString), instanceId, base64EncryptedFieldKey);
}
Also used : XFormParameters(org.opendatakit.aggregate.form.XFormParameters) ParsingException(org.opendatakit.briefcase.model.ParsingException)

Aggregations

ParsingException (org.opendatakit.briefcase.model.ParsingException)15 File (java.io.File)9 IOException (java.io.IOException)9 FileSystemException (org.opendatakit.briefcase.model.FileSystemException)8 ArrayList (java.util.ArrayList)7 Element (org.kxml2.kdom.Element)5 FormStatusEvent (org.opendatakit.briefcase.model.FormStatusEvent)4 OutputStreamWriter (java.io.OutputStreamWriter)3 Document (org.kxml2.kdom.Document)3 CannotFixXMLException (org.opendatakit.briefcase.model.CannotFixXMLException)3 DocumentDescription (org.opendatakit.briefcase.model.DocumentDescription)3 MediaFile (org.opendatakit.briefcase.util.ServerFetcher.MediaFile)3 FileNotFoundException (java.io.FileNotFoundException)2 MalformedURLException (java.net.MalformedURLException)2 SQLException (java.sql.SQLException)2 LocalDate (java.time.LocalDate)2 Date (java.util.Date)2 HashMap (java.util.HashMap)2 CryptoException (org.opendatakit.briefcase.model.CryptoException)2 MetadataUpdateException (org.opendatakit.briefcase.model.MetadataUpdateException)2