Search in sources :

Example 6 with KXmlSerializer

use of org.kxml2.io.KXmlSerializer in project robovm by robovm.

the class KxmlSerializerTest method testWriteSpecialCharactersInText.

// http://code.google.com/p/android/issues/detail?id=21250
public void testWriteSpecialCharactersInText() throws Exception {
    StringWriter stringWriter = new StringWriter();
    XmlSerializer serializer = new KXmlSerializer();
    serializer.setOutput(stringWriter);
    serializer.startDocument("UTF-8", null);
    serializer.startTag(NAMESPACE, "foo");
    serializer.text("5'8\", 5 < 6 & 7 > 3!");
    serializer.endTag(NAMESPACE, "foo");
    serializer.endDocument();
    assertXmlEquals("<foo>5'8\", 5 &lt; 6 &amp; 7 &gt; 3!</foo>", stringWriter.toString());
}
Also used : StringWriter(java.io.StringWriter) KXmlSerializer(org.kxml2.io.KXmlSerializer) XmlSerializer(org.xmlpull.v1.XmlSerializer) KXmlSerializer(org.kxml2.io.KXmlSerializer)

Example 7 with KXmlSerializer

use of org.kxml2.io.KXmlSerializer in project robovm by robovm.

the class KxmlSerializerTest method testWhitespaceInAttributeValue.

public void testWhitespaceInAttributeValue() throws Exception {
    StringWriter stringWriter = new StringWriter();
    XmlSerializer serializer = new KXmlSerializer();
    serializer.setOutput(stringWriter);
    serializer.startDocument("UTF-8", null);
    serializer.startTag(NAMESPACE, "a");
    serializer.attribute(NAMESPACE, "cr", "\r");
    serializer.attribute(NAMESPACE, "lf", "\n");
    serializer.attribute(NAMESPACE, "tab", "\t");
    serializer.attribute(NAMESPACE, "space", " ");
    serializer.endTag(NAMESPACE, "a");
    serializer.endDocument();
    assertXmlEquals("<a cr=\"&#13;\" lf=\"&#10;\" tab=\"&#9;\" space=\" \" />", stringWriter.toString());
}
Also used : StringWriter(java.io.StringWriter) KXmlSerializer(org.kxml2.io.KXmlSerializer) XmlSerializer(org.xmlpull.v1.XmlSerializer) KXmlSerializer(org.kxml2.io.KXmlSerializer)

Example 8 with KXmlSerializer

use of org.kxml2.io.KXmlSerializer 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 9 with KXmlSerializer

use of org.kxml2.io.KXmlSerializer in project briefcase by opendatakit.

the class XmlManipulationUtils method updateSubmissionMetadata.

public static final String updateSubmissionMetadata(File submissionFile, Document doc) throws MetadataUpdateException {
    Element root = doc.getRootElement();
    Element metadata = root.getElement(NAMESPACE_ODK, "submissionMetadata");
    // and get the instanceID and submissionDate from the metadata.
    // we need to put that back into the instance file if not already present
    String instanceID = metadata.getAttributeValue("", INSTANCE_ID_ATTRIBUTE_NAME);
    String submissionDate = metadata.getAttributeValue("", SUBMISSION_DATE_ATTRIBUTE_NAME);
    // read the original document...
    Document originalDoc = null;
    try {
        FileInputStream fs = new FileInputStream(submissionFile);
        InputStreamReader fr = new InputStreamReader(fs, "UTF-8");
        originalDoc = new Document();
        KXmlParser parser = new KXmlParser();
        parser.setInput(fr);
        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
        originalDoc.parse(parser);
        fr.close();
        fs.close();
    } catch (IOException e) {
        String msg = "Original submission file could not be opened";
        log.error(msg, e);
        throw new MetadataUpdateException(msg);
    } catch (XmlPullParserException e) {
        String msg = "Original submission file could not be parsed as XML file";
        log.error(msg, e);
        throw new MetadataUpdateException(msg);
    }
    // determine whether it has the attributes already added.
    // if they are already there, they better match the values returned by
    // Aggregate 1.0
    boolean hasInstanceID = false;
    boolean hasSubmissionDate = false;
    root = originalDoc.getRootElement();
    for (int i = 0; i < root.getAttributeCount(); ++i) {
        String name = root.getAttributeName(i);
        if (name.equals(INSTANCE_ID_ATTRIBUTE_NAME)) {
            if (!root.getAttributeValue(i).equals(instanceID)) {
                String msg = "Original submission file's instanceID does not match that on server!";
                log.error(msg);
                throw new MetadataUpdateException(msg);
            } else {
                hasInstanceID = true;
            }
        }
        if (name.equals(SUBMISSION_DATE_ATTRIBUTE_NAME)) {
            Date oldDate = WebUtils.parseDate(submissionDate);
            String returnDate = root.getAttributeValue(i);
            Date newDate = WebUtils.parseDate(returnDate);
            // cross-platform datetime resolution is 1 second.
            if (Math.abs(newDate.getTime() - oldDate.getTime()) > 1000L) {
                String msg = "Original submission file's submissionDate does not match that on server!";
                log.error(msg);
                throw new MetadataUpdateException(msg);
            } else {
                hasSubmissionDate = true;
            }
        }
    }
    if (hasInstanceID && hasSubmissionDate) {
        log.info("submission already has instanceID and submissionDate attributes: " + submissionFile.getAbsolutePath());
        return instanceID;
    }
    if (!hasInstanceID) {
        root.setAttribute("", INSTANCE_ID_ATTRIBUTE_NAME, instanceID);
    }
    if (!hasSubmissionDate) {
        root.setAttribute("", SUBMISSION_DATE_ATTRIBUTE_NAME, submissionDate);
    }
    // and write out the changes...
    // write the file out...
    File revisedFile = new File(submissionFile.getParentFile(), "." + submissionFile.getName());
    try {
        FileOutputStream fos = new FileOutputStream(revisedFile, false);
        KXmlSerializer serializer = new KXmlSerializer();
        serializer.setOutput(fos, "UTF-8");
        originalDoc.write(serializer);
        serializer.flush();
        fos.close();
        // and swap files...
        boolean restoreTemp = false;
        File temp = new File(submissionFile.getParentFile(), ".back." + submissionFile.getName());
        try {
            if (temp.exists()) {
                if (!temp.delete()) {
                    String msg = "Unable to remove temporary submission backup file";
                    log.error(msg);
                    throw new MetadataUpdateException(msg);
                }
            }
            if (!submissionFile.renameTo(temp)) {
                String msg = "Unable to rename submission to temporary submission backup file";
                log.error(msg);
                throw new MetadataUpdateException(msg);
            }
            // recovery is possible...
            restoreTemp = true;
            if (!revisedFile.renameTo(submissionFile)) {
                String msg = "Original submission file could not be updated";
                log.error(msg);
                throw new MetadataUpdateException(msg);
            }
            // we're successful...
            restoreTemp = false;
        } finally {
            if (restoreTemp) {
                if (!temp.renameTo(submissionFile)) {
                    String msg = "Unable to restore submission from temporary submission backup file";
                    log.error(msg);
                    throw new MetadataUpdateException(msg);
                }
            }
        }
    } catch (FileNotFoundException e) {
        String msg = "Temporary submission file could not be opened";
        log.error(msg, e);
        throw new MetadataUpdateException(msg);
    } catch (IOException e) {
        String msg = "Temporary submission file could not be written";
        log.error(msg, e);
        throw new MetadataUpdateException(msg);
    }
    return instanceID;
}
Also used : InputStreamReader(java.io.InputStreamReader) Element(org.kxml2.kdom.Element) FileNotFoundException(java.io.FileNotFoundException) MetadataUpdateException(org.opendatakit.briefcase.model.MetadataUpdateException) IOException(java.io.IOException) Document(org.kxml2.kdom.Document) FileInputStream(java.io.FileInputStream) Date(java.util.Date) KXmlSerializer(org.kxml2.io.KXmlSerializer) KXmlParser(org.kxml2.io.KXmlParser) FileOutputStream(java.io.FileOutputStream) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) MediaFile(org.opendatakit.briefcase.util.ServerFetcher.MediaFile) File(java.io.File)

Example 10 with KXmlSerializer

use of org.kxml2.io.KXmlSerializer in project javarosa by opendatakit.

the class XFormSerializer method getStream.

public static ByteArrayOutputStream getStream(Document doc) {
    KXmlSerializer serializer = new KXmlSerializer();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    try {
        serializer.setOutput(dos, null);
        doc.write(serializer);
        serializer.flush();
        return bos;
    } catch (Exception e) {
        Std.printStack(e);
        return null;
    }
}
Also used : DataOutputStream(java.io.DataOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) KXmlSerializer(org.kxml2.io.KXmlSerializer) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Aggregations

KXmlSerializer (org.kxml2.io.KXmlSerializer)11 StringWriter (java.io.StringWriter)5 XmlSerializer (org.xmlpull.v1.XmlSerializer)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 IOException (java.io.IOException)3 Element (org.kxml2.kdom.Element)3 DataOutputStream (java.io.DataOutputStream)2 File (java.io.File)2 FileOutputStream (java.io.FileOutputStream)2 OutputStreamWriter (java.io.OutputStreamWriter)2 Document (org.kxml2.kdom.Document)2 MediaFile (org.opendatakit.briefcase.util.ServerFetcher.MediaFile)2 FileInputStream (java.io.FileInputStream)1 FileNotFoundException (java.io.FileNotFoundException)1 InputStreamReader (java.io.InputStreamReader)1 RandomAccessFile (java.io.RandomAccessFile)1 Writer (java.io.Writer)1 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)1 InvalidKeyException (java.security.InvalidKeyException)1