Example usage for javax.xml.transform OutputKeys OMIT_XML_DECLARATION

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

Introduction

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

Prototype

String OMIT_XML_DECLARATION

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

Click Source Link

Document

omit-xml-declaration = "yes" | "no".

Usage

From source file:org.ojbc.util.camel.processor.audit.FederatedQueryAuditLogger.java

private String getStringFromDocument(Document doc) {
    try {//from   w ww.  j a  v a  2s .c o m
        DOMSource domSource = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(domSource, result);
        return writer.toString();
    } catch (TransformerException ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:org.ojbc.web.WebUtils.java

public static String returnStringFromFilePath(InputStream is) throws Exception {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setNamespaceAware(true);//from   w w w.  ja v  a  2s . c  o  m
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    Document doc = docBuilder.parse(is);

    // set up a transformer
    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans = transfac.newTransformer();
    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    trans.setOutputProperty(OutputKeys.INDENT, "yes");

    // create string from xml tree
    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);
    DOMSource source = new DOMSource(doc);
    trans.transform(source, result);
    String xmlString = sw.toString();

    return xmlString;

}

From source file:org.okbqa.disambiguation.client.DBpediaSpotlightClient.java

public TemplateInterpretations extract(PseudoSPARQLTemplate pst) throws SpotlightException {
    TemplateInterpretations ret = new TemplateInterpretations();
    TemplateInterpretation ti = new TemplateInterpretation();
    ret.getInterpretations().add(ti);//w  ww  .jav a 2s  . co  m
    List<EntityBinding> bindings = ti.getEntityBindings();

    // obtain variables that are rdf:Resource and their verbalizations
    List<String> resourceVariables = new ArrayList<String>();
    for (EntitySlot es : pst.getSlots()) {
        if (es.getPredicate().equals("is") && es.getObject().equals("rdf:Resource"))
            resourceVariables.add(es.getSubject());
    }

    Map<String, String> varToVerbalization = new HashMap<String, String>();

    for (EntitySlot es : pst.getSlots()) {
        if (es.getPredicate().equals("verbalization") && resourceVariables.contains(es.getSubject())) {
            varToVerbalization.put(es.getSubject(), es.getObject());
        }
    }

    // build a query for just the rdf:Resource variables
    String query = null;
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();

    try {
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root element
        Document doc = docBuilder.newDocument();
        Element annotation = doc.createElement("annotation");
        doc.appendChild(annotation);

        annotation.setAttribute("text", pst.getQuestion().replace("\"", "&quot;"));

        // surface forms
        for (String verbalization : varToVerbalization.values()) {
            Element surfaceForm = doc.createElement("surfaceForm");
            annotation.appendChild(surfaceForm);
            surfaceForm.setAttribute("name", verbalization);
            surfaceForm.setAttribute("offset", String.valueOf(pst.getQuestion().indexOf(verbalization)));
        }
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        StreamResult result = new StreamResult(new StringWriter());
        transformer.transform(new DOMSource(doc), result);
        query = result.getWriter().toString();
    } catch (Exception e) {
        e.printStackTrace();
        query = "";
    }

    try {
        String spotlightResponse = getResponse(API_URL + "rest/annotate/?" + "spotter=SpotXmlParser" + "&text="
                + URLEncoder.encode(query, "utf-8"));
        JSONObject resultJSON = null;
        JSONArray entities = null;

        try {
            resultJSON = new JSONObject(spotlightResponse);
            ti.setScore(resultJSON.getDouble("@confidence"));
            entities = resultJSON.getJSONArray("Resources");
        } catch (JSONException e) {
            throw new AnnotationException(e);
        }

        for (int i = 0; i < entities.length(); i++) {
            JSONObject entityJSON = entities.getJSONObject(i);
            Entity entity = Entity.fromJSON(entityJSON);
            bindings.add(new EntityBinding(entityJSON.getString("@surfaceForm"), entity));
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return ret;
}

From source file:org.opencastproject.metadata.dublincore.DublinCoreCatalogList.java

/**
 * Serialize a node to an input stream/*from ww w.  j a  va2  s .  c  om*/
 * 
 * @param node
 *          the node to serialize
 * @return the serialized input stream
 */
private static InputStream nodeToString(Node node) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.transform(new DOMSource(node), new StreamResult(outputStream));
        return new ByteArrayInputStream(outputStream.toByteArray());
    } catch (TransformerException te) {
        System.out.println("nodeToString Transformer Exception");
    }
    return null;
}

From source file:org.opencastproject.metadata.dublincore.DublinCoreTest.java

/**
 * Test method for saving the catalog.//w ww.  j ava2s.co m
 */
@Test
public void testNewInstance() {
    try {

        // Read the sample catalog
        FileInputStream in = new FileInputStream(catalogFile);
        DublinCoreCatalog dcSample = new DublinCoreCatalogImpl(in);
        IOUtils.closeQuietly(in);

        // Create a new catalog and fill it with a few fields
        DublinCoreCatalog dcNew = DublinCoreCatalogImpl.newInstance();
        dcTempFile1 = new File(FileSupport.getTempDirectory(), Long.toString(System.currentTimeMillis()));

        // Add the required fields
        dcNew.add(PROPERTY_IDENTIFIER, dcSample.getFirst(PROPERTY_IDENTIFIER));
        dcNew.add(PROPERTY_TITLE, dcSample.getFirst(PROPERTY_TITLE, DublinCore.LANGUAGE_UNDEFINED),
                DublinCore.LANGUAGE_UNDEFINED);

        // Add an additional field
        dcNew.add(PROPERTY_PUBLISHER, dcSample.getFirst(PROPERTY_PUBLISHER));

        // Add a null-value field
        try {
            dcNew.add(PROPERTY_CONTRIBUTOR, (String) null);
            fail();
        } catch (IllegalArgumentException e) {
        }

        // Add a field with an encoding scheme
        dcNew.add(PROPERTY_LICENSE, new DublinCoreValue("http://www.opencastproject.org/license",
                DublinCore.LANGUAGE_UNDEFINED, ENC_SCHEME_URI));
        // Don't forget to bind the namespace...
        dcNew.bindPrefix("octest", "http://www.opencastproject.org/octest");
        dcNew.add(PROPERTY_PROMOTED, new DublinCoreValue("true", DublinCore.LANGUAGE_UNDEFINED,
                new EName("http://www.opencastproject.org/octest", "Boolean")));
        try {
            dcNew.add(PROPERTY_PROMOTED, new DublinCoreValue("true", DublinCore.LANGUAGE_UNDEFINED,
                    new EName("http://www.opencastproject.org/enc-scheme", "Boolean")));
            fail();
        } catch (NamespaceBindingException e) {
            // Ok. This exception is expected to occur
        }

        // Store the catalog
        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trans.setOutputProperty(OutputKeys.METHOD, "xml");
        FileWriter sw = new FileWriter(dcTempFile1);
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(dcNew.toXml());
        trans.transform(source, result);

        // Re-read the saved catalog and test for its content
        DublinCoreCatalog dcNewFromDisk = new DublinCoreCatalogImpl(dcTempFile1.toURI().toURL().openStream());
        assertEquals(dcSample.getFirst(PROPERTY_IDENTIFIER), dcNewFromDisk.getFirst(PROPERTY_IDENTIFIER));
        assertEquals(dcSample.getFirst(PROPERTY_TITLE, "en"), dcNewFromDisk.getFirst(PROPERTY_TITLE, "en"));
        assertEquals(dcSample.getFirst(PROPERTY_PUBLISHER), dcNewFromDisk.getFirst(PROPERTY_PUBLISHER));

    } catch (IOException e) {
        fail("Error creating the catalog: " + e.getMessage());
    } catch (ParserConfigurationException e) {
        fail("Error creating a parser for the catalog: " + e.getMessage());
    } catch (TransformerException e) {
        fail("Error saving the catalog: " + e.getMessage());
    }
}

From source file:org.opencastproject.metadata.dublincore.DublinCoreTest.java

/**
 * Test method for {@link org.opencastproject.metadata.dublincore.DublinCoreCatalogImpl#save()} .
 *//* ww  w  .j a  v a2 s .c o m*/
@Test(expected = IllegalStateException.class)
public void testRequiredFields() {
    try {

        // Read the sample catalog
        FileInputStream in = new FileInputStream(catalogFile);
        DublinCoreCatalog dcSample = new DublinCoreCatalogImpl(in);
        IOUtils.closeQuietly(in);

        // Create a new catalog and fill it with a few fields
        dcTempFile2 = new File(FileSupport.getTempDirectory(), Long.toString(System.currentTimeMillis()));
        DublinCoreCatalog dcNew = new DublinCoreCatalogImpl();

        // Add the required fields but the title
        dcNew.set(PROPERTY_IDENTIFIER, dcSample.getFirst(PROPERTY_IDENTIFIER));

        // Add an additional field
        dcNew.set(PROPERTY_PUBLISHER, dcSample.getFirst(PROPERTY_PUBLISHER));

        // Store the catalog
        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trans.setOutputProperty(OutputKeys.METHOD, "xml");
        FileWriter sw = new FileWriter(dcTempFile2);
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(dcNew.toXml());
        trans.transform(source, result);

        fail("Required field was missing but not reported!");
    } catch (IOException e) {
        fail("Error creating the catalog: " + e.getMessage());
    } catch (ParserConfigurationException e) {
        fail("Error creating a parser for the catalog: " + e.getMessage());
    } catch (TransformerException e) {
        fail("Error saving the catalog: " + e.getMessage());
    }
}

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

/**
 * The incoming URI is of the form:/*  ww  w  .  ja  va  2  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;
}

From source file:org.opendatakit.services.utilities.EncryptionUtils.java

private static boolean writeSubmissionManifest(EncryptedFormInformation formInfo, File submissionXml,
        File submissionXmlEnc, List<MimeFile> mediaFiles) {

    FileOutputStream out = null;//from  w ww  . j a va 2s  .co  m
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document d = db.newDocument();
        d.setXmlStandalone(true);
        Element e = d.createElementNS(XML_ENCRYPTED_TAG_NAMESPACE, DATA);
        e.setPrefix(null);
        e.setAttribute(ID, formInfo.tableId);
        e.setAttribute(ENCRYPTED, "yes");
        d.appendChild(e);

        Element c;
        c = d.createElementNS(XML_ENCRYPTED_TAG_NAMESPACE, BASE64_ENCRYPTED_KEY);
        Text txtNode;
        txtNode = d.createTextNode(formInfo.base64RsaEncryptedSymmetricKey);
        c.appendChild(txtNode);
        e.appendChild(c);

        c = d.createElementNS(XML_OPENROSA_NAMESPACE, META);
        c.setPrefix("orx");
        {
            Element instanceTag = d.createElementNS(XML_OPENROSA_NAMESPACE, INSTANCE_ID);
            txtNode = d.createTextNode(formInfo.instanceId);
            instanceTag.appendChild(txtNode);
            c.appendChild(instanceTag);
        }
        e.appendChild(c);

        for (MimeFile file : mediaFiles) {
            c = d.createElementNS(XML_ENCRYPTED_TAG_NAMESPACE, MEDIA);
            Element fileTag = d.createElementNS(XML_ENCRYPTED_TAG_NAMESPACE, FILE);
            txtNode = d.createTextNode(file.file.getName());
            fileTag.appendChild(txtNode);
            c.appendChild(fileTag);
            e.appendChild(c);
        }

        c = d.createElementNS(XML_ENCRYPTED_TAG_NAMESPACE, ENCRYPTED_XML_FILE);
        txtNode = d.createTextNode(submissionXmlEnc.getName());
        c.appendChild(txtNode);
        e.appendChild(c);

        c = d.createElementNS(XML_ENCRYPTED_TAG_NAMESPACE, BASE64_ENCRYPTED_ELEMENT_SIGNATURE);
        txtNode = d.createTextNode(formInfo.getBase64EncryptedElementSignature());
        c.appendChild(txtNode);
        e.appendChild(c);

        out = new FileOutputStream(submissionXml);

        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);

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

        out.flush();
        out.close();
    } catch (FileNotFoundException ex) {
        WebLogger.getLogger(formInfo.appName).printStackTrace(ex);
        WebLogger.getLogger(formInfo.appName).e(t, "Error writing submission.xml for encrypted submission: "
                + submissionXml.getParentFile().getName());
        return false;
    } catch (UnsupportedEncodingException ex) {
        WebLogger.getLogger(formInfo.appName).printStackTrace(ex);
        WebLogger.getLogger(formInfo.appName).e(t, "Error writing submission.xml for encrypted submission: "
                + submissionXml.getParentFile().getName());
        return false;
    } catch (IOException ex) {
        WebLogger.getLogger(formInfo.appName).printStackTrace(ex);
        WebLogger.getLogger(formInfo.appName).e(t, "Error writing submission.xml for encrypted submission: "
                + submissionXml.getParentFile().getName());
        return false;
    } catch (TransformerConfigurationException ex) {
        WebLogger.getLogger(formInfo.appName).printStackTrace(ex);
        WebLogger.getLogger(formInfo.appName).e(t, "Error writing submission.xml for encrypted submission: "
                + submissionXml.getParentFile().getName());
        return false;
    } catch (TransformerException ex) {
        WebLogger.getLogger(formInfo.appName).printStackTrace(ex);
        WebLogger.getLogger(formInfo.appName).e(t, "Error writing submission.xml for encrypted submission: "
                + submissionXml.getParentFile().getName());
        return false;
    } catch (ParserConfigurationException ex) {
        WebLogger.getLogger(formInfo.appName).printStackTrace(ex);
        WebLogger.getLogger(formInfo.appName).e(t, "Error writing submission.xml for encrypted submission: "
                + submissionXml.getParentFile().getName());
        return false;
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }

    return true;
}

From source file:org.openestate.io.core.XmlUtils.java

/**
 * Write a {@link Document} to an {@link OutputStream}.
 *
 * @param doc/*from w ww .  jav  a  2  s . c  o  m*/
 * the document to write
 *
 * @param output
 * the output, where the document is written to
 *
 * @param prettyPrint
 * if pretty printing is enabled for the generated XML code
 *
 * @throws TransformerException
 * if XML transformation failed
 */
public static void write(Document doc, OutputStream output, boolean prettyPrint) throws TransformerException {
    XmlUtils.clean(doc);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, (prettyPrint) ? "yes" : "no");
    if (prettyPrint) {
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    }
    transformer.transform(new DOMSource(doc), new StreamResult(output));
}

From source file:org.openestate.io.core.XmlUtils.java

/**
 * Write a {@link Document} to a {@link Writer}.
 *
 * @param doc/* w  w w.j  a va2s .co m*/
 * the document to write
 *
 * @param output
 * the output, where the document is written to
 *
 * @param prettyPrint
 * if pretty printing is enabled for the generated XML code
 *
 * @throws TransformerException
 * if XML transformation failed
 */
public static void write(Document doc, Writer output, boolean prettyPrint) throws TransformerException {
    XmlUtils.clean(doc);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, (prettyPrint) ? "yes" : "no");
    if (prettyPrint) {
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    }
    transformer.transform(new DOMSource(doc), new StreamResult(output));
}