Example usage for javax.xml.transform OutputKeys ENCODING

List of usage examples for javax.xml.transform OutputKeys ENCODING

Introduction

In this page you can find the example usage for javax.xml.transform OutputKeys ENCODING.

Prototype

String ENCODING

To view the source code for javax.xml.transform OutputKeys ENCODING.

Click Source Link

Document

encoding = string.

Usage

From source file:org.mule.module.xml.transformer.AbstractXmlTransformer.java

protected void writeToStream(Object obj, String outputEncoding, OutputStream output) throws Exception {
    // Always use the transformer, even for byte[] (to get the encoding right!)
    Source src = XMLUtils.toXmlSource(xmlInputFactory, useStaxSource, obj);
    if (src == null) {
        return;/*from  ww  w .ja  va  2  s.c o  m*/
    }

    StreamResult result = new StreamResult(output);

    Transformer idTransformer = XMLUtils.getTransformer();
    idTransformer.setOutputProperty(OutputKeys.ENCODING, outputEncoding);
    idTransformer.transform(src, result);
}

From source file:org.mule.module.xml.transformer.XsltTransformer.java

protected void doTransform(MuleMessage message, String outputEncoding, Source sourceDoc, Result result)
        throws Exception {
    DefaultErrorListener errorListener = new DefaultErrorListener(this);
    javax.xml.transform.Transformer transformer = null;

    try {/*from   w  w  w. j  a va 2s  . com*/
        transformer = (javax.xml.transform.Transformer) transformerPool.borrowObject();

        transformer.setErrorListener(errorListener);
        transformer.setOutputProperty(OutputKeys.ENCODING, outputEncoding);

        // set transformation parameters
        if (contextProperties != null) {
            for (Entry<String, Object> parameter : contextProperties.entrySet()) {
                String key = parameter.getKey();
                transformer.setParameter(key, evaluateTransformParameter(key, parameter.getValue(), message));
            }
        }

        transformer.transform(sourceDoc, result);

        if (errorListener.isError()) {
            throw errorListener.getException();
        }
    } finally {
        if (transformer != null) {
            // clear transformation parameters before returning transformer to the
            // pool
            transformer.clearParameters();

            transformerPool.returnObject(transformer);
        }
    }
}

From source file:org.mycore.common.content.MCRVFSContentTest.java

/**
 * Test method for {@link org.mycore.common.content.MCRContent#getSource()}.
 * @throws IOException /*from w  w  w .  j  a  v  a 2 s .c  om*/
 * @throws TransformerException 
 */
@Test
public final void testGetSource() throws IOException, TransformerException {
    CommonVFSResolver resolver = new CommonVFSResolver(fileObject);
    assertFalse("File is open", resolver.isContentOpen());
    //identity transformation
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "no");
    StreamResult result = new StreamResult(System.out);
    transformer.transform(resolver.resolve("test://test", null), result);
    assertFalse("File is open after identity transformation", resolver.isContentOpen());
    //simple transformation
    URL xslURL = MCRVFSContentTest.class.getResource(TEST_BASE + "test.xsl");
    URL xmlURL = MCRVFSContentTest.class.getResource(TEST_BASE + "test.xml");
    Source xsl = new StreamSource(xslURL.toString());
    Source xml = new StreamSource(xmlURL.toString());
    transformer = TransformerFactory.newInstance().newTransformer(xsl);
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setURIResolver(resolver);
    transformer.transform(xml, result);
    assertFalse("File is open after simple transformation", resolver.isContentOpen());
    //cacheable transformation
    Templates templates = TransformerFactory.newInstance().newTemplates(xsl);
    transformer = templates.newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setURIResolver(resolver);
    transformer.transform(xml, result);
    assertFalse("File is open after cacheable transformation", resolver.isContentOpen());
}

From source file:org.niord.core.util.TextUtils.java

/**
 * Prints an XML document to the output stream
 * @param doc the document to print//w  w w.j a va  2  s  .  c  o  m
 * @param out the output stream
 */
public static void printDocument(org.w3c.dom.Document doc, OutputStream out)
        throws IOException, TransformerException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
}

From source file:org.onehippo.cms7.autoexport.Exporter.java

private void doExportContentResource(final InitializeItem item) throws RepositoryException {
    OutputStream out = null;/*  ww w  .ja  va  2  s .c om*/
    try {
        File file = new File(module.getExportDir(), item.getContentResource());
        if (!file.exists()) {
            ExportUtils.createFile(file);
        }
        out = new FileOutputStream(file);
        TransformerHandler handler = ((SAXTransformerFactory) SAXTransformerFactory.newInstance())
                .newTransformerHandler();
        Transformer transformer = handler.getTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(2));
        handler.setResult(new StreamResult(out));

        if (item.isDelta()) {
            exportDeltaXML(item, handler);
        } else {
            exportDereferencedView(item, handler);
        }
    } catch (IOException | TransformerConfigurationException | SAXException e) {
        log.error("Exporting " + item.getContentResource() + " failed.", e);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:org.onehippo.repository.bootstrap.instructions.ContentResourceInstruction.java

InputStream getPartialContentInputStream(InputStream in, final String contextRelPath)
        throws IOException, RepositoryException {
    File file = File.createTempFile("bootstrap-", ".xml");
    OutputStream out = null;/*from w ww.  j  av  a2 s  . com*/
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
        SAXParser parser = factory.newSAXParser();

        out = new FileOutputStream(file);
        TransformerHandler handler = ((SAXTransformerFactory) SAXTransformerFactory.newInstance())
                .newTransformerHandler();
        Transformer transformer = handler.getTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        handler.setResult(new StreamResult(out));

        parser.parse(new InputSource(in),
                new DefaultContentHandler(new PartialSystemViewFilter(handler, contextRelPath)));
        return new TempFileInputStream(file);
    } catch (FactoryConfigurationError e) {
        throw new RepositoryException("SAX parser implementation not available", e);
    } catch (ParserConfigurationException e) {
        throw new RepositoryException("SAX parser configuration error", e);
    } catch (SAXException e) {
        Exception exception = e.getException();
        if (exception instanceof RepositoryException) {
            throw (RepositoryException) exception;
        } else if (exception instanceof IOException) {
            throw (IOException) exception;
        } else {
            throw new InvalidSerializedDataException("Error parsing XML import", e);
        }
    } catch (TransformerConfigurationException e) {
        throw new RepositoryException("SAX transformation error", e);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:org.onehippo.repository.bootstrap.util.PartialSystemViewFilterTest.java

public String getPartialContent(InputStream in, String startPath) throws Exception {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);/*w w  w. j av a2s  .c  o  m*/
    factory.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
    SAXParser parser = factory.newSAXParser();

    StringWriter out = new StringWriter();
    TransformerHandler handler = ((SAXTransformerFactory) SAXTransformerFactory.newInstance())
            .newTransformerHandler();
    Transformer transformer = handler.getTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    handler.setResult(new StreamResult(out));

    parser.parse(new InputSource(in),
            new DefaultContentHandler(new PartialSystemViewFilter(handler, startPath)));
    return out.toString();
}

From source file:org.openbravo.erpCommon.ad_forms.TranslationManager.java

/**
 * Exports a single trl table in a xml file
 * /*  w  w  w .  j av  a2  s  . c om*/
 * @param AD_Language
 *          Language to export
 * @param exportReferenceData
 *          Defines whether exporting reference data
 * @param exportAll
 *          In case it is reference data if it should be exported all data or just imported
 * @param table
 *          Base table
 * @param tableID
 *          Base table id
 * @param rootDirectory
 *          Root directory to the the exportation
 * @param moduleId
 *          Id for the module to export to
 * @param moduleLanguage
 *          Base language for the module
 * @param javaPackage
 *          Java package for the module
 */
private static void exportTable(ConnectionProvider cp, String AD_Language, boolean exportReferenceData,
        boolean exportAll, String table, String tableID, String rootDirectory, String moduleId,
        String moduleLanguage, String javaPackage, boolean trl) {

    Statement st = null;
    StringBuffer sql = null;
    try {
        String trlTable = table;
        if (trl && !table.endsWith("_TRL"))
            trlTable = table + "_TRL";
        final TranslationData[] trlColumns = getTrlColumns(cp, table);
        final String keyColumn = table + "_ID";

        boolean m_IsCentrallyMaintained = false;
        try {
            m_IsCentrallyMaintained = !(TranslationData.centrallyMaintained(cp, table).equals("0"));
            if (m_IsCentrallyMaintained)
                log4j.debug("table:" + table + " IS centrally maintained");
            else
                log4j.debug("table:" + table + " is NOT centrally maintained");
        } catch (final Exception e) {
            log4j.error("getTrlColumns (IsCentrallyMaintained)", e);
        }

        // Prepare query to retrieve translated rows
        sql = new StringBuffer("SELECT ");
        if (trl)
            sql.append("t.IsTranslated,");
        else
            sql.append("'N', ");
        sql.append("t.").append(keyColumn);

        for (int i = 0; i < trlColumns.length; i++) {
            sql.append(", t.").append(trlColumns[i].c).append(",o.").append(trlColumns[i].c).append(" AS ")
                    .append(trlColumns[i].c).append("O");
        }

        sql.append(" FROM ").append(trlTable).append(" t").append(", ").append(table).append(" o");

        if (exportReferenceData && !exportAll) {
            sql.append(", AD_REF_DATA_LOADED DL");
        }

        sql.append(" WHERE ");
        if (trl)
            sql.append("t.AD_Language='" + AD_Language + "'").append(" AND ");
        sql.append("o.").append(keyColumn).append("= t.").append(keyColumn);

        if (m_IsCentrallyMaintained) {
            sql.append(" AND ").append("o.IsCentrallyMaintained='N'");
        }
        // AdClient !=0 not supported
        sql.append(" AND o.AD_Client_ID='0' ");

        if (!exportReferenceData) {
            String tempTrlTableName = trlTable;
            if (!tempTrlTableName.toLowerCase().endsWith("_trl")) {
                tempTrlTableName = tempTrlTableName + "_Trl";
            }
            final TranslationData[] parentTable = TranslationData.parentTable(cp, tempTrlTableName);

            if (parentTable.length == 0) {
                sql.append(" AND ").append(" o.ad_module_id='").append(moduleId).append("'");
            } else {
                /** Search for ad_module_id in the parent table */
                if (StringUtils.isEmpty(parentTable[0].grandparent)) {
                    String strParentTable = parentTable[0].tablename;
                    sql.append(" AND ");
                    sql.append(" exists ( select 1 from ").append(strParentTable).append(" p ");
                    sql.append("   where p.").append(strParentTable + "_ID").append("=")
                            .append("o." + strParentTable + "_ID");
                    sql.append("   and p.ad_module_id='").append(moduleId).append("')");
                } else {
                    String strParentTable = parentTable[0].tablename;
                    String strGandParentTable = parentTable[0].grandparent;

                    sql.append(" AND ");
                    sql.append(" exists ( select 1 from ").append(strGandParentTable).append(" gp, ")
                            .append(strParentTable).append(" p");
                    sql.append("   where p.").append(strParentTable + "_ID").append("=")
                            .append("o." + strParentTable + "_ID");
                    sql.append("   and p." + strGandParentTable + "_ID = gp." + strGandParentTable + "_ID");
                    sql.append("   and gp.ad_module_id='").append(moduleId).append("')");
                }
            }
        }
        if (exportReferenceData && !exportAll) {
            sql.append(" AND DL.GENERIC_ID = o.").append(keyColumn).append(" AND DL.AD_TABLE_ID = '")
                    .append(tableID).append("'").append(" AND DL.AD_MODULE_ID = '").append(moduleId)
                    .append("'");
        }

        sql.append(" ORDER BY t.").append(keyColumn);
        //

        if (log4j.isDebugEnabled())
            log4j.debug("SQL:" + sql.toString());
        st = cp.getStatement();
        if (log4j.isDebugEnabled())
            log4j.debug("st");

        final ResultSet rs = st.executeQuery(sql.toString());
        if (log4j.isDebugEnabled())
            log4j.debug("rs");
        int rows = 0;
        boolean hasRows = false;

        DocumentBuilderFactory factory = null;
        DocumentBuilder builder = null;
        Document document = null;
        Element root = null;
        File out = null;

        // Create xml file

        String directory = "";
        factory = DocumentBuilderFactory.newInstance();
        builder = factory.newDocumentBuilder();
        document = builder.newDocument();
        // Root
        root = document.createElement(XML_TAG);
        root.setAttribute(XML_ATTRIBUTE_LANGUAGE, AD_Language);
        root.setAttribute(XML_ATTRIBUTE_TABLE, table);
        root.setAttribute(XML_ATTRIBUTE_BASE_LANGUAGE, moduleLanguage);
        root.setAttribute(XML_ATTRIBUTE_VERSION, TranslationData.version(cp));
        document.appendChild(root);

        if (moduleId.equals("0"))
            directory = rootDirectory + AD_Language + "/";
        else
            directory = rootDirectory + AD_Language + "/" + javaPackage + "/";
        if (!new File(directory).exists())
            (new File(directory)).mkdir();

        String fileName = directory + trlTable + "_" + AD_Language + ".xml";
        log4j.info("exportTrl - " + fileName);
        out = new File(fileName);

        while (rs.next()) {
            if (!hasRows && !exportReferenceData) { // Create file only in
                // case it has contents
                // or it is not rd
                hasRows = true;

                factory = DocumentBuilderFactory.newInstance();
                builder = factory.newDocumentBuilder();
                document = builder.newDocument();
                // Root
                root = document.createElement(XML_TAG);
                root.setAttribute(XML_ATTRIBUTE_LANGUAGE, AD_Language);
                root.setAttribute(XML_ATTRIBUTE_TABLE, table);
                root.setAttribute(XML_ATTRIBUTE_BASE_LANGUAGE, moduleLanguage);
                root.setAttribute(XML_ATTRIBUTE_VERSION, TranslationData.version(cp));
                document.appendChild(root);

                if (moduleId.equals("0"))
                    directory = rootDirectory + AD_Language + "/";
                else
                    directory = rootDirectory + AD_Language + "/" + javaPackage + "/";
                if (!new File(directory).exists())
                    (new File(directory)).mkdir();

                fileName = directory + trlTable + "_" + AD_Language + ".xml";
                log4j.info("exportTrl - " + fileName);
                out = new File(fileName);
            }

            final Element row = document.createElement(XML_ROW_TAG);
            row.setAttribute(XML_ROW_ATTRIBUTE_ID, String.valueOf(rs.getString(2))); // KeyColumn
            row.setAttribute(XML_ROW_ATTRIBUTE_TRANSLATED, rs.getString(1)); // IsTranslated
            for (int i = 0; i < trlColumns.length; i++) {
                final Element value = document.createElement(XML_VALUE_TAG);
                value.setAttribute(XML_VALUE_ATTRIBUTE_COLUMN, trlColumns[i].c);
                String origString = rs.getString(trlColumns[i].c + "O"); // Original
                String isTrlString = "Y";
                // Value
                if (origString == null) {
                    origString = "";
                    isTrlString = "N";
                }
                String valueString = rs.getString(trlColumns[i].c); // Value
                if (valueString == null) {
                    valueString = "";
                    isTrlString = "N";
                }
                if (origString.equals(valueString))
                    isTrlString = "N";
                value.setAttribute(XML_VALUE_ATTRIBUTE_ISTRL, isTrlString);
                value.setAttribute(XML_VALUE_ATTRIBUTE_ORIGINAL, origString);
                value.appendChild(document.createTextNode(valueString));
                row.appendChild(value);
            }
            root.appendChild(row);
            rows++;
        }
        rs.close();

        log4j.info("exportTrl - Records=" + rows + ", DTD=" + document.getDoctype());

        final DOMSource source = new DOMSource(document);
        final TransformerFactory tFactory = TransformerFactory.newInstance();
        tFactory.setAttribute("indent-number", new Integer(2));
        final Transformer transformer = tFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        // Output
        out.createNewFile();
        // Transform
        final OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(out), "UTF-8");
        transformer.transform(source, new StreamResult(osw));
        osw.close();
    } catch (final Exception e) {
        log4j.error("Error exporting translation for table " + table + "\n" + sql, e);
    } finally {
        try {
            if (st != null)
                cp.releaseStatement(st);
        } catch (final Exception ignored) {
        }
    }

}

From source file:org.opencastproject.mediapackage.XMLCatalogImpl.java

/**
 * Serializes the given xml document to the associated file. Please note that this method does <em>not</em> close the
 * output stream. Anyone using this method is responsible for doing it by itself.
 * /* w  ww. j  a va 2  s  .  c  om*/
 * @param document
 *          the document
 * @param docType
 *          the document type definition (dtd)
 * @throws TransformerException
 *           if serialization fails
 */
protected void saveToXml(Node document, String docType, OutputStream out)
        throws TransformerException, IOException {
    StreamResult streamResult = new StreamResult(out);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer serializer = tf.newTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    if (docType != null)
        serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, docType);
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    serializer.transform(new DOMSource(document), streamResult);
    out.flush();
}

From source file:org.opendatakit.services.submissions.provider.SubmissionProvider.java

/**
 * The incoming URI is of the form:/*  ww w  . j  a v  a2  s.  c  o m*/
 * ..../appName/tableId/instanceId?formId=&formVersion=
 *
 * where instanceId is the DataTableColumns._ID
 */
@SuppressWarnings("unchecked")
@Override
public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode) throws FileNotFoundException {

    possiblyWaitForContentProviderDebugger();

    final boolean asXml = uri.getAuthority().equalsIgnoreCase(ProviderConsts.XML_SUBMISSION_AUTHORITY);

    if (mode != null && !mode.equals("r")) {
        throw new IllegalArgumentException("Only read access is supported");
    }

    // URI == ..../appName/tableId/instanceId?formId=&formVersion=

    List<String> segments = uri.getPathSegments();

    if (segments.size() != 4) {
        throw new IllegalArgumentException("Unknown URI (incorrect number of path segments!) " + uri);
    }

    PropertyManager propertyManager = new PropertyManager(getContext());

    final String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);
    WebLoggerIf logger = WebLogger.getLogger(appName);

    final String tableId = segments.get(1);
    final String instanceId = segments.get(2);
    final String submissionInstanceId = segments.get(3);

    PropertiesSingleton props = CommonToolProperties.get(getContext(), appName);
    String userEmail = props.getProperty(CommonToolProperties.KEY_ACCOUNT);
    String username = props.getProperty(CommonToolProperties.KEY_USERNAME);
    String activeUser = props.getActiveUser();
    String rolesList = props.getProperty(CommonToolProperties.KEY_ROLES_LIST);
    String currentLocale = props.getLocale();

    DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
            .generateInternalUseDbHandle();
    OdkConnectionInterface db = null;
    try {
        // +1 referenceCount if db is returned (non-null)
        db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(appName,
                dbHandleName);

        boolean success = false;
        try {
            success = ODKDatabaseImplUtils.get().hasTableId(db, tableId);
        } catch (Exception e) {
            logger.printStackTrace(e);
            throw new SQLException("Unknown URI (exception testing for tableId) " + uri);
        }
        if (!success) {
            throw new SQLException("Unknown URI (missing data table for tableId) " + uri);
        }

        // Get the table properties specific to XML submissions

        String xmlInstanceName = null;
        String xmlRootElementName = null;
        String xmlDeviceIdPropertyName = null;
        String xmlUserIdPropertyName = null;
        String xmlBase64RsaPublicKey = null;

        try {

            Cursor c = null;
            try {
                c = db.query(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME,
                        new String[] { KeyValueStoreColumns.KEY, KeyValueStoreColumns.VALUE },
                        KeyValueStoreColumns.TABLE_ID + "=? AND " + KeyValueStoreColumns.PARTITION + "=? AND "
                                + KeyValueStoreColumns.ASPECT + "=? AND " + KeyValueStoreColumns.KEY
                                + " IN (?,?,?,?,?)",
                        new String[] { tableId, KeyValueStoreConstants.PARTITION_TABLE,
                                KeyValueStoreConstants.ASPECT_DEFAULT, KeyValueStoreConstants.XML_INSTANCE_NAME,
                                KeyValueStoreConstants.XML_ROOT_ELEMENT_NAME,
                                KeyValueStoreConstants.XML_DEVICE_ID_PROPERTY_NAME,
                                KeyValueStoreConstants.XML_USER_ID_PROPERTY_NAME,
                                KeyValueStoreConstants.XML_BASE64_RSA_PUBLIC_KEY },
                        null, null, null, null);
                c.moveToFirst();

                if (c.getCount() > 0) {
                    int idxKey = c.getColumnIndex(KeyValueStoreColumns.KEY);
                    int idxValue = c.getColumnIndex(KeyValueStoreColumns.VALUE);
                    do {
                        String key = c.getString(idxKey);
                        String value = c.getString(idxValue);
                        if (KeyValueStoreConstants.XML_INSTANCE_NAME.equals(key)) {
                            xmlInstanceName = value;
                        } else if (KeyValueStoreConstants.XML_ROOT_ELEMENT_NAME.equals(key)) {
                            xmlRootElementName = value;
                        } else if (KeyValueStoreConstants.XML_DEVICE_ID_PROPERTY_NAME.equals(key)) {
                            xmlDeviceIdPropertyName = value;
                        } else if (KeyValueStoreConstants.XML_USER_ID_PROPERTY_NAME.equals(key)) {
                            xmlUserIdPropertyName = value;
                        } else if (KeyValueStoreConstants.XML_BASE64_RSA_PUBLIC_KEY.equals(key)) {
                            xmlBase64RsaPublicKey = value;
                        }
                    } while (c.moveToNext());
                }
            } finally {
                c.close();
                c = null;
            }

            OrderedColumns orderedDefns = ODKDatabaseImplUtils.get().getUserDefinedColumns(db, tableId);

            // Retrieve the values of the record to be emitted...

            HashMap<String, Object> values = new HashMap<String, Object>();

            // issue query to retrieve the most recent non-checkpoint data record
            // for the instanceId
            StringBuilder b = new StringBuilder();
            b.append("SELECT * FROM ").append(tableId).append(" as T WHERE ").append(DataTableColumns.ID)
                    .append("=?").append(" AND ").append(DataTableColumns.SAVEPOINT_TYPE)
                    .append(" IS NOT NULL AND ").append(DataTableColumns.SAVEPOINT_TIMESTAMP)
                    .append("=(SELECT max(V.").append(DataTableColumns.SAVEPOINT_TIMESTAMP).append(") FROM ")
                    .append(tableId).append(" as V WHERE V.").append(DataTableColumns.ID).append("=T.")
                    .append(DataTableColumns.ID).append(" AND V.").append(DataTableColumns.SAVEPOINT_TYPE)
                    .append(" IS NOT NULL").append(")");

            String[] selectionArgs = new String[] { instanceId };
            FileSet freturn = new FileSet(appName);

            String datestamp = null;

            try {

                ODKDatabaseImplUtils.AccessContext accessContext = ODKDatabaseImplUtils.get()
                        .getAccessContext(db, tableId, activeUser, rolesList);

                c = ODKDatabaseImplUtils.get().rawQuery(db, b.toString(), selectionArgs, null, accessContext);
                b.setLength(0);

                if (c.moveToFirst() && c.getCount() == 1) {
                    String rowETag = null;
                    String filterType = null;
                    String filterValue = null;
                    String formId = null;
                    String locale = null;
                    String savepointType = null;
                    String savepointCreator = null;
                    String savepointTimestamp = null;
                    String instanceName = null;

                    // OK. we have the record -- work through all the terms
                    for (int i = 0; i < c.getColumnCount(); ++i) {
                        ColumnDefinition defn = null;
                        String columnName = c.getColumnName(i);
                        try {
                            defn = orderedDefns.find(columnName);
                        } catch (IllegalArgumentException e) {
                            // ignore...
                        }
                        if (defn != null && !c.isNull(i)) {
                            if (xmlInstanceName != null && defn.getElementName().equals(xmlInstanceName)) {
                                instanceName = CursorUtils.getIndexAsString(c, i);
                            }
                            // user-defined column
                            ElementType type = defn.getType();
                            ElementDataType dataType = type.getDataType();

                            logger.i(t, "element type: " + defn.getElementType());
                            if (dataType == ElementDataType.integer) {
                                Integer value = CursorUtils.getIndexAsType(c, Integer.class, i);
                                putElementValue(values, defn, value);
                            } else if (dataType == ElementDataType.number) {
                                Double value = CursorUtils.getIndexAsType(c, Double.class, i);
                                putElementValue(values, defn, value);
                            } else if (dataType == ElementDataType.bool) {
                                Integer tmp = CursorUtils.getIndexAsType(c, Integer.class, i);
                                Boolean value = tmp == null ? null : (tmp != 0);
                                putElementValue(values, defn, value);
                            } else if (type.getElementType().equals("date")) {
                                String value = CursorUtils.getIndexAsString(c, i);
                                String jrDatestamp = (value == null) ? null
                                        : (new SimpleDateFormat(ISO8601_DATE_ONLY_FORMAT, Locale.US))
                                                .format(new Date(TableConstants.milliSecondsFromNanos(value)));
                                putElementValue(values, defn, jrDatestamp);
                            } else if (type.getElementType().equals("dateTime")) {
                                String value = CursorUtils.getIndexAsString(c, i);
                                String jrDatestamp = (value == null) ? null
                                        : (new SimpleDateFormat(ISO8601_DATE_FORMAT, Locale.US))
                                                .format(new Date(TableConstants.milliSecondsFromNanos(value)));
                                putElementValue(values, defn, jrDatestamp);
                            } else if (type.getElementType().equals("time")) {
                                String value = CursorUtils.getIndexAsString(c, i);
                                putElementValue(values, defn, value);
                            } else if (dataType == ElementDataType.array) {
                                ArrayList<Object> al = CursorUtils.getIndexAsType(c, ArrayList.class, i);
                                putElementValue(values, defn, al);
                            } else if (dataType == ElementDataType.string) {
                                String value = CursorUtils.getIndexAsString(c, i);
                                putElementValue(values, defn, value);
                            } else /* unrecognized */ {
                                throw new IllegalStateException(
                                        "unrecognized data type: " + defn.getElementType());
                            }

                        } else if (columnName.equals(DataTableColumns.SAVEPOINT_TIMESTAMP)) {
                            savepointTimestamp = CursorUtils.getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.ROW_ETAG)) {
                            rowETag = CursorUtils.getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.FILTER_TYPE)) {
                            filterType = CursorUtils.getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.FILTER_VALUE)) {
                            filterValue = CursorUtils.getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.FORM_ID)) {
                            formId = CursorUtils.getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.LOCALE)) {
                            locale = CursorUtils.getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.FORM_ID)) {
                            formId = CursorUtils.getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.SAVEPOINT_TYPE)) {
                            savepointType = CursorUtils.getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.SAVEPOINT_CREATOR)) {
                            savepointCreator = CursorUtils.getIndexAsString(c, i);
                        }
                    }

                    // OK got all the values into the values map -- emit
                    // contents
                    b.setLength(0);
                    File submissionXml = new File(ODKFileUtils.getInstanceFolder(appName, tableId, instanceId),
                            (asXml ? "submission.xml" : "submission.json"));
                    File manifest = new File(ODKFileUtils.getInstanceFolder(appName, tableId, instanceId),
                            "manifest.json");
                    submissionXml.delete();
                    manifest.delete();
                    freturn.instanceFile = submissionXml;

                    if (asXml) {
                        // Pre-processing -- collapse all geopoints into a
                        // string-valued representation
                        for (ColumnDefinition defn : orderedDefns.getColumnDefinitions()) {
                            ElementType type = defn.getType();
                            ElementDataType dataType = type.getDataType();
                            if (dataType == ElementDataType.object && (type.getElementType().equals("geopoint")
                                    || type.getElementType().equals("mimeUri"))) {
                                Map<String, Object> parent = null;
                                List<ColumnDefinition> parents = new ArrayList<ColumnDefinition>();
                                ColumnDefinition d = defn.getParent();
                                while (d != null) {
                                    parents.add(d);
                                    d = d.getParent();
                                }
                                parent = values;
                                for (int i = parents.size() - 1; i >= 0; --i) {
                                    Object o = parent.get(parents.get(i).getElementName());
                                    if (o == null) {
                                        parent = null;
                                        break;
                                    }
                                    parent = (Map<String, Object>) o;
                                }
                                if (parent != null) {
                                    Object o = parent.get(defn.getElementName());
                                    if (o != null) {
                                        if (type.getElementType().equals("geopoint")) {
                                            Map<String, Object> geopoint = (Map<String, Object>) o;
                                            // OK. we have geopoint -- get the
                                            // lat, long, alt, etc.
                                            Double latitude = (Double) geopoint.get("latitude");
                                            Double longitude = (Double) geopoint.get("longitude");
                                            Double altitude = (Double) geopoint.get("altitude");
                                            Double accuracy = (Double) geopoint.get("accuracy");
                                            String gpt = "" + latitude + " " + longitude + " " + altitude + " "
                                                    + accuracy;
                                            parent.put(defn.getElementName(), gpt);
                                        } else if (type.getElementType().equals("mimeUri")) {
                                            Map<String, Object> mimeuri = (Map<String, Object>) o;
                                            String uriFragment = (String) mimeuri.get("uriFragment");
                                            String contentType = (String) mimeuri.get("contentType");

                                            if (uriFragment != null) {
                                                File f = ODKFileUtils.getAsFile(appName, uriFragment);
                                                if (f.equals(manifest)) {
                                                    throw new IllegalStateException(
                                                            "Unexpected collision with manifest.json");
                                                }
                                                freturn.addAttachmentFile(f, contentType);
                                                parent.put(defn.getElementName(), f.getName());
                                            }
                                        } else {
                                            throw new IllegalStateException("Unhandled transform case");
                                        }
                                    }
                                }
                            }
                        }

                        datestamp = (new SimpleDateFormat(ISO8601_DATE_FORMAT, Locale.US))
                                .format(new Date(TableConstants.milliSecondsFromNanos(savepointTimestamp)));

                        // For XML, we traverse the map to serialize it
                        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                        DocumentBuilder docBuilder = dbf.newDocumentBuilder();

                        Document d = docBuilder.newDocument();

                        d.setXmlStandalone(true);

                        Element e = d.createElement((xmlRootElementName == null) ? "data" : xmlRootElementName);
                        d.appendChild(e);
                        e.setAttribute("id", tableId);
                        DynamicPropertiesCallback cb = new DynamicPropertiesCallback(appName, tableId,
                                instanceId, activeUser, currentLocale, username, userEmail);

                        int idx = 0;
                        Element meta = d.createElementNS(XML_OPENROSA_NAMESPACE, "meta");
                        meta.setPrefix("jr");

                        Element v = d.createElementNS(XML_OPENROSA_NAMESPACE, "instanceID");
                        Text txtNode = d.createTextNode(submissionInstanceId);
                        v.appendChild(txtNode);
                        meta.appendChild(v);

                        if (xmlDeviceIdPropertyName != null) {
                            String deviceId = propertyManager.getSingularProperty(xmlDeviceIdPropertyName, cb);
                            if (deviceId != null) {
                                v = d.createElementNS(XML_OPENROSA_NAMESPACE, "deviceID");
                                txtNode = d.createTextNode(deviceId);
                                v.appendChild(txtNode);
                                meta.appendChild(v);
                            }
                        }
                        if (xmlUserIdPropertyName != null) {
                            String userId = propertyManager.getSingularProperty(xmlUserIdPropertyName, cb);
                            if (userId != null) {
                                v = d.createElementNS(XML_OPENROSA_NAMESPACE, "userID");
                                txtNode = d.createTextNode(userId);
                                v.appendChild(txtNode);
                                meta.appendChild(v);
                            }
                        }
                        v = d.createElementNS(XML_OPENROSA_NAMESPACE, "timeEnd");
                        txtNode = d.createTextNode(datestamp);
                        v.appendChild(txtNode);
                        meta.appendChild(v);

                        // these are extra metadata tags...
                        if (instanceName != null) {
                            v = d.createElement("instanceName");
                            txtNode = d.createTextNode(instanceName);
                            v.appendChild(txtNode);
                            meta.appendChild(v);
                        } else {
                            v = d.createElement("instanceName");
                            txtNode = d.createTextNode(savepointTimestamp);
                            v.appendChild(txtNode);
                            meta.appendChild(v);
                        }

                        // these are extra metadata tags...
                        // rowID
                        v = d.createElement("rowID");
                        txtNode = d.createTextNode(instanceId);
                        v.appendChild(txtNode);
                        meta.appendChild(v);

                        // rowETag
                        v = d.createElement("rowETag");
                        if (rowETag != null) {
                            txtNode = d.createTextNode(rowETag);
                            v.appendChild(txtNode);
                        }
                        meta.appendChild(v);

                        // filterType
                        v = d.createElement("filterType");
                        if (filterType != null) {
                            txtNode = d.createTextNode(filterType);
                            v.appendChild(txtNode);
                        }
                        meta.appendChild(v);

                        // filterValue
                        v = d.createElement("filterValue");
                        if (filterValue != null) {
                            txtNode = d.createTextNode(filterValue);
                            v.appendChild(txtNode);
                        }
                        meta.appendChild(v);

                        // formID
                        v = d.createElement("formID");
                        txtNode = d.createTextNode(formId);
                        v.appendChild(txtNode);
                        meta.appendChild(v);

                        // locale
                        v = d.createElement("locale");
                        txtNode = d.createTextNode(locale);
                        v.appendChild(txtNode);
                        meta.appendChild(v);

                        // savepointType
                        v = d.createElement("savepointType");
                        txtNode = d.createTextNode(savepointType);
                        v.appendChild(txtNode);
                        meta.appendChild(v);

                        // savepointCreator
                        v = d.createElement("savepointCreator");
                        if (savepointCreator != null) {
                            txtNode = d.createTextNode(savepointCreator);
                            v.appendChild(txtNode);
                        }
                        meta.appendChild(v);

                        // savepointTimestamp
                        v = d.createElement("savepointTimestamp");
                        txtNode = d.createTextNode(savepointTimestamp);
                        v.appendChild(txtNode);
                        meta.appendChild(v);

                        // and insert the meta block into the XML

                        e.appendChild(meta);

                        idx = 3;
                        ArrayList<String> entryNames = new ArrayList<String>();
                        entryNames.addAll(values.keySet());
                        Collections.sort(entryNames);
                        for (String name : entryNames) {
                            idx = generateXmlHelper(d, e, idx, name, values, logger);
                        }

                        TransformerFactory factory = TransformerFactory.newInstance();
                        Transformer transformer = factory.newTransformer();
                        Properties outFormat = new Properties();
                        outFormat.setProperty(OutputKeys.INDENT, "no");
                        outFormat.setProperty(OutputKeys.METHOD, "xml");
                        outFormat.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                        outFormat.setProperty(OutputKeys.VERSION, "1.0");
                        outFormat.setProperty(OutputKeys.ENCODING, "UTF-8");
                        transformer.setOutputProperties(outFormat);

                        ByteArrayOutputStream out = new ByteArrayOutputStream();

                        DOMSource domSource = new DOMSource(d.getDocumentElement());
                        StreamResult result = new StreamResult(out);
                        transformer.transform(domSource, result);

                        out.flush();
                        out.close();

                        b.append(out.toString(CharEncoding.UTF_8));

                        // OK we have the document in the builder (b).
                        String doc = b.toString();

                        freturn.instanceFile = submissionXml;

                        // see if the form is encrypted and we can
                        // encrypt it...
                        EncryptedFormInformation formInfo = EncryptionUtils.getEncryptedFormInformation(appName,
                                tableId, xmlBase64RsaPublicKey, instanceId);
                        if (formInfo != null) {
                            File submissionXmlEnc = new File(submissionXml.getParentFile(),
                                    submissionXml.getName() + ".enc");
                            submissionXmlEnc.delete();
                            // if we are encrypting, the form cannot be
                            // reopened afterward
                            // and encrypt the submission (this is a
                            // one-way operation)...
                            if (!EncryptionUtils.generateEncryptedSubmission(freturn, doc, submissionXml,
                                    submissionXmlEnc, formInfo)) {
                                return null;
                            }
                            // at this point, the freturn object has
                            // been re-written with the encrypted media
                            // and xml files.
                        } else {
                            exportFile(doc, submissionXml, logger);
                        }

                    } else {
                        // Pre-processing -- collapse all mimeUri into filename
                        for (ColumnDefinition defn : orderedDefns.getColumnDefinitions()) {
                            ElementType type = defn.getType();
                            ElementDataType dataType = type.getDataType();

                            if (dataType == ElementDataType.object && type.getElementType().equals("mimeUri")) {
                                Map<String, Object> parent = null;
                                List<ColumnDefinition> parents = new ArrayList<ColumnDefinition>();
                                ColumnDefinition d = defn.getParent();
                                while (d != null) {
                                    parents.add(d);
                                    d = d.getParent();
                                }
                                parent = values;
                                for (int i = parents.size() - 1; i >= 0; --i) {
                                    Object o = parent.get(parents.get(i).getElementName());
                                    if (o == null) {
                                        parent = null;
                                        break;
                                    }
                                    parent = (Map<String, Object>) o;
                                }
                                if (parent != null) {
                                    Object o = parent.get(defn.getElementName());
                                    if (o != null) {
                                        if (dataType == ElementDataType.object
                                                && type.getElementType().equals("mimeUri")) {
                                            Map<String, Object> mimeuri = (Map<String, Object>) o;
                                            String uriFragment = (String) mimeuri.get("uriFragment");
                                            String contentType = (String) mimeuri.get("contentType");
                                            File f = ODKFileUtils.getAsFile(appName, uriFragment);
                                            if (f.equals(manifest)) {
                                                throw new IllegalStateException(
                                                        "Unexpected collision with manifest.json");
                                            }
                                            freturn.addAttachmentFile(f, contentType);
                                            parent.put(defn.getElementName(), f.getName());
                                        } else {
                                            throw new IllegalStateException("Unhandled transform case");
                                        }
                                    }
                                }
                            }
                        }

                        // For JSON, we construct the model, then emit model +
                        // meta + data
                        HashMap<String, Object> wrapper = new HashMap<String, Object>();
                        wrapper.put("tableId", tableId);
                        wrapper.put("instanceId", instanceId);
                        HashMap<String, Object> formDef = new HashMap<String, Object>();
                        formDef.put("table_id", tableId);
                        formDef.put("model", orderedDefns.getDataModel());
                        wrapper.put("formDef", formDef);
                        wrapper.put("data", values);
                        wrapper.put("metadata", new HashMap<String, Object>());
                        HashMap<String, Object> elem = (HashMap<String, Object>) wrapper.get("metadata");
                        if (instanceName != null) {
                            elem.put("instanceName", instanceName);
                        }
                        elem.put("saved", "COMPLETE");
                        elem.put("timestamp", datestamp);

                        b.append(ODKFileUtils.mapper.writeValueAsString(wrapper));

                        // OK we have the document in the builder (b).
                        String doc = b.toString();
                        exportFile(doc, submissionXml, logger);
                    }
                    exportFile(freturn.serializeUriFragmentList(getContext()), manifest, logger);
                    return ParcelFileDescriptor.open(manifest, ParcelFileDescriptor.MODE_READ_ONLY);

                }
            } finally {
                if (c != null && !c.isClosed()) {
                    c.close();
                    c = null;
                }
            }

        } catch (ParserConfigurationException e) {
            logger.printStackTrace(e);
        } catch (TransformerException e) {
            logger.printStackTrace(e);
        } catch (JsonParseException e) {
            logger.printStackTrace(e);
        } catch (JsonMappingException e) {
            logger.printStackTrace(e);
        } catch (IOException e) {
            logger.printStackTrace(e);
        }

    } finally {
        if (db != null) {
            try {
                // release the reference...
                // this does not necessarily close the db handle
                // or terminate any pending transaction
                db.releaseReference();
            } finally {
                // this will release the final reference and close the database
                OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().removeConnection(appName,
                        dbHandleName);
            }
        }
    }
    return null;
}