List of usage examples for android.database.sqlite SQLiteDatabase query
public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy,
String having, String orderBy)
From source file:com.openatk.planting.MainActivity.java
private Job FindJobById(Integer id) { if (id != null) { SQLiteDatabase database = dbHelper.getReadableDatabase(); // Find job Job theJob = null;/*from w w w.j av a 2 s. co m*/ String where = TableJobs.COL_ID + " = " + Integer.toString(id) + " AND " + TableJobs.COL_DELETED + " = 0"; Cursor cursor = database.query(TableJobs.TABLE_NAME, TableJobs.COLUMNS, where, null, null, null, null); if (cursor.moveToFirst()) { theJob = Job.cursorToJob(cursor); } cursor.close(); dbHelper.close(); return theJob; } else { return null; } }
From source file:org.ttrssreader.controllers.DBHelper.java
/** * get the map of article IDs to its update date from DB * * @param selection A filter declaring which articles should be considered, formatted as an SQL WHERE clause * (excluding// www . j a v a 2 s. c om * the WHERE * itself). Passing null will return all rows. * @param selectionArgs You may include ?s in selection, which will be replaced by the values from selectionArgs, * in * order * that they appear in the selection. The values will be bound as Strings. * @return map of unread article IDs to its update date (may be {@code null}) */ @SuppressLint("UseSparseArrays") public Map<Integer, Long> getArticleIdUpdatedMap(String selection, String[] selectionArgs) { Map<Integer, Long> ret = null; if (!isDBAvailable()) return null; Cursor c = null; SQLiteDatabase db = getOpenHelper().getReadableDatabase(); readLock(true); try { c = db.query(TABLE_ARTICLES, new String[] { "_id", "updateDate" }, selection, selectionArgs, null, null, null); ret = new HashMap<>(c.getCount()); while (c.moveToNext()) { ret.put(c.getInt(0), c.getLong(1)); } } finally { if (c != null && !c.isClosed()) c.close(); readLock(false); } return ret; }
From source file:com.openatk.planting.MainActivity.java
private Job FindJobByFieldName(String name) { SQLiteDatabase database = dbHelper.getReadableDatabase(); // Find job//w w w .j av a 2s .co m Job theJob = null; String where = TableJobs.COL_FIELD_NAME + " = '" + name + "'" + " AND " + TableJobs.COL_OPERATION_ID + " = " + Integer.toString(currentOperationId) + " AND " + TableJobs.COL_DELETED + " = 0"; Cursor cursor = database.query(TableJobs.TABLE_NAME, TableJobs.COLUMNS, where, null, null, null, null); if (cursor.moveToFirst()) { theJob = Job.cursorToJob(cursor); } cursor.close(); dbHelper.close(); return theJob; }
From source file:com.openatk.planting.MainActivity.java
private void drawFields() { SQLiteDatabase database = dbHelper.getReadableDatabase(); String[] columns = { TableFields.COL_ID, TableFields.COL_BOUNDARY, TableFields.COL_NAME, TableFields.COL_DELETED };//from w ww .j a va2 s . co m String where = TableFields.COL_DELETED + " = 0"; Cursor cursor = database.query(TableFields.TABLE_NAME, columns, where, null, null, null, null); FieldsOnMap = new ArrayList<Field>(); Log.d("MainActivity- DrawFields", "Op Id:" + Integer.toString(currentOperationId)); while (cursor.moveToNext()) { String boundary = cursor.getString(cursor.getColumnIndex(TableFields.COL_BOUNDARY)); List<LatLng> points = Field.StringToBoundary(boundary); if (points.size() == 0) points = null; // Add to list so we can catch click events Field newField = new Field(); newField.setId(cursor.getInt(cursor.getColumnIndex(TableFields.COL_ID))); newField.setMap(map); newField.setBoundary(points); newField.setName(cursor.getString(cursor.getColumnIndex(TableFields.COL_NAME))); // Find status of this field // Find job Job theJob = null; String where2 = TableJobs.COL_FIELD_NAME + " = '" + newField.getName() + "'" + " AND " + TableJobs.COL_OPERATION_ID + " = " + Integer.toString(currentOperationId) + " AND " + TableJobs.COL_DELETED + " = 0"; Cursor cursor2 = database.query(TableJobs.TABLE_NAME, TableJobs.COLUMNS, where2, null, null, null, null); if (cursor2.moveToFirst()) { theJob = Job.cursorToJob(cursor2); } cursor2.close(); // Now draw this field // Create polygon if (points != null && points.isEmpty() == false) { PolygonOptions polygonOptions = new PolygonOptions(); if (theJob == null || theJob.getStatus() == Job.STATUS_NOT_PLANNED) { polygonOptions.fillColor(Field.FILL_COLOR_NOT_PLANNED); } else if (theJob.getStatus() == Job.STATUS_PLANNED) { polygonOptions.fillColor(Field.FILL_COLOR_PLANNED); } else if (theJob.getStatus() == Job.STATUS_STARTED) { polygonOptions.fillColor(Field.FILL_COLOR_STARTED); } else if (theJob.getStatus() == Job.STATUS_DONE) { polygonOptions.fillColor(Field.FILL_COLOR_DONE); } polygonOptions.strokeWidth(Field.STROKE_WIDTH); polygonOptions.strokeColor(Field.STROKE_COLOR); for (int i = 0; i < points.size(); i++) { polygonOptions.add(points.get(i)); } newField.setPolygon(new MyPolygon(map, map.addPolygon(polygonOptions), this)); if (currentField != null && newField.getId() == currentField.getId()) { this.currentPolygon = newField.getPolygon(); this.currentPolygon.setLabel(newField.getName(), true); } else { newField.getPolygon().setLabel(newField.getName()); } } FieldsOnMap.add(newField); } cursor.close(); dbHelper.close(); if (addIsShowing == 1) { if (this.currentPolygon != null && currentField != null) { this.currentPolygon.edit(); } if (this.addingBoundary.length() > 0) { List<LatLng> points = Field.StringToBoundary(this.addingBoundary); this.currentPolygon = new MyPolygon(map, this); Log.d("Hi", "hello" + points.size()); for (int i = 0; i < (points.size() - 1); i++) { this.currentPolygon.addPoint(points.get(i)); } } } }
From source file:org.ttrssreader.controllers.DBHelper.java
public Set<Category> getAllCategories() { if (!isDBAvailable()) return new LinkedHashSet<>(); SQLiteDatabase db = getOpenHelper().getReadableDatabase(); readLock(true);//from w w w . j a v a2s. c o m Cursor c = null; try { c = db.query(TABLE_CATEGORIES, null, "_id>=0", null, null, null, "title ASC"); Set<Category> ret = new LinkedHashSet<>(c.getCount()); while (c.moveToNext()) { ret.add(handleCategoryCursor(c)); } return ret; } finally { if (c != null && !c.isClosed()) c.close(); readLock(false); } }
From source file:org.ttrssreader.controllers.DBHelper.java
/** * get summary length of remote files, which are cached * * @return summary length of remote files *//*from w ww. j a va 2 s . c om*/ public long getCachedFilesSize() { if (!isDBAvailable()) return 0; long ret = 0; SQLiteDatabase db = getOpenHelper().getReadableDatabase(); readLock(true); Cursor c = null; try { c = db.query(TABLE_REMOTEFILES, new String[] { "SUM(length)" }, "cached=1", null, null, null, null); if (c.moveToFirst()) ret = c.getLong(0); } finally { if (c != null && !c.isClosed()) c.close(); readLock(false); } return ret; }
From source file:org.ttrssreader.controllers.DBHelper.java
/** * get remote files which should be deleted to free given amount of space * * @param spaceToBeFreed amount of space (summary file size) to be freed * @return collection of remote files, which can be deleted * to free given amount of space/*from www . j a v a2 s.co m*/ */ public Collection<RemoteFile> getUncacheFiles(long spaceToBeFreed) { if (!isDBAvailable()) return null; ArrayList<RemoteFile> rfs = new ArrayList<>(); SQLiteDatabase db = getOpenHelper().getReadableDatabase(); readLock(true); Cursor c = null; try { c = db.query("remotefile_sequence", null, "cached = 1", null, null, null, "ord"); long spaceToFree = spaceToBeFreed; while (spaceToFree > 0 && c.moveToNext()) { RemoteFile rf = handleRemoteFileCursor(c); spaceToFree -= rf.length; rfs.add(rf); } } finally { if (c != null && !c.isClosed()) c.close(); readLock(false); } return rfs; }
From source file:org.ttrssreader.controllers.DBHelper.java
/** * 0 - Uncategorized/*from ww w . j av a 2 s .c o m*/ * -1 - Special (e.g. Starred, Published, Archived, etc.) <- these are categories here o.O * -2 - Labels * -3 - All feeds, excluding virtual feeds (e.g. Labels and such) * -4 - All feeds, including virtual feeds */ public Set<Feed> getFeeds(int categoryId) { if (!isDBAvailable()) return new LinkedHashSet<>(); String where = null; // categoryId = 0 if (categoryId >= 0) where = "categoryId=" + categoryId; switch (categoryId) { case -1: where = "_id IN (0, -2, -3)"; break; case -2: where = "_id < -10"; break; case -3: where = "categoryId >= 0"; break; case -4: where = null; break; } SQLiteDatabase db = getOpenHelper().getReadableDatabase(); readLock(true); Cursor c = null; try { c = db.query(TABLE_FEEDS, null, where, null, null, null, "UPPER(title) ASC"); Set<Feed> ret = new LinkedHashSet<>(c.getCount()); while (c.moveToNext()) { ret.add(handleFeedCursor(c)); } return ret; } finally { if (c != null && !c.isClosed()) c.close(); readLock(false); } }
From source file:org.ttrssreader.controllers.DBHelper.java
/** * set read status in DB for given category/feed * * @param id category/feed ID//from www. j a va2 s . co m * @param isCategory if set to {@code true}, then given id is category * ID, otherwise - feed ID * @return collection of article IDs, which was marked as read or {@code null} if nothing was changed */ Collection<Integer> markRead(int id, boolean isCategory) { Set<Integer> ret = null; if (!isDBAvailable()) return null; StringBuilder where = new StringBuilder(); StringBuilder feedIds = new StringBuilder(); switch (id) { case Data.VCAT_ALL: where.append(" 1 "); // Select everything... break; case Data.VCAT_FRESH: long time = System.currentTimeMillis() - Controller.getInstance().getFreshArticleMaxAge(); where.append(" updateDate > ").append(time); break; case Data.VCAT_PUB: where.append(" isPublished > 0 "); break; case Data.VCAT_STAR: where.append(" isStarred > 0 "); break; default: if (isCategory) { feedIds.append("SELECT _id FROM ").append(TABLE_FEEDS).append(" WHERE categoryId=").append(id); } else { feedIds.append(id); } where.append(" feedId IN (").append(feedIds).append(") "); break; } where.append(" and isUnread>0 "); Cursor c = null; SQLiteDatabase db = getOpenHelper().getReadableDatabase(); readLock(true); try { // select id from articles where categoryId in (...) c = db.query(TABLE_ARTICLES, new String[] { "_id" }, where.toString(), null, null, null, null); int count = c.getCount(); if (count > 0) { ret = new HashSet<>(count); while (c.moveToNext()) { ret.add(c.getInt(0)); } } } finally { if (c != null && !c.isClosed()) c.close(); readLock(false); } if (ret != null && !ret.isEmpty()) { // TODO Check access markArticles(ret, "isUnread", 0); } return ret; }
From source file:org.opendatakit.survey.android.provider.SubmissionProvider.java
/** * The incoming URI is of the form://from www .j av a 2 s . c om * ..../appName/tableId/instanceId?formId=&formVersion= * * where instanceId is the DataTableColumns._ID */ @SuppressWarnings("unchecked") @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { final boolean asXml = uri.getAuthority().equalsIgnoreCase(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); } final String appName = segments.get(0); ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); WebLogger log = WebLogger.getLogger(appName); final String tableId = segments.get(1); final String instanceId = segments.get(2); final String submissionInstanceId = segments.get(3); SQLiteDatabase db = null; try { db = DatabaseFactory.get().getDatabase(getContext(), appName); boolean success = false; try { success = ODKDatabaseUtils.get().hasTableId(db, tableId); } catch (Exception e) { e.printStackTrace(); throw new SQLException("Unknown URI (exception testing for tableId) " + uri); } if (!success) { throw new SQLException("Unknown URI (missing data table for tableId) " + uri); } final String dbTableName = "\"" + tableId + "\""; // 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); if (c.getCount() > 0) { c.moveToFirst(); 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; } ArrayList<ColumnDefinition> orderedDefns = TableUtil.get().getColumnDefinitions(db, appName, 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(dbTableName).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(dbTableName).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 { c = db.rawQuery(b.toString(), selectionArgs); 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 = ColumnDefinition.find(orderedDefns, columnName); } catch (IllegalArgumentException e) { // ignore... } if (defn != null && !c.isNull(i)) { if (xmlInstanceName != null && defn.getElementName().equals(xmlInstanceName)) { instanceName = ODKDatabaseUtils.get().getIndexAsString(c, i); } // user-defined column ElementType type = defn.getType(); ElementDataType dataType = type.getDataType(); log.i(t, "element type: " + defn.getElementType()); if (dataType == ElementDataType.integer) { Integer value = ODKDatabaseUtils.get().getIndexAsType(c, Integer.class, i); putElementValue(values, defn, value); } else if (dataType == ElementDataType.number) { Double value = ODKDatabaseUtils.get().getIndexAsType(c, Double.class, i); putElementValue(values, defn, value); } else if (dataType == ElementDataType.bool) { Integer tmp = ODKDatabaseUtils.get().getIndexAsType(c, Integer.class, i); Boolean value = tmp == null ? null : (tmp != 0); putElementValue(values, defn, value); } else if (type.getElementType().equals("date")) { String value = ODKDatabaseUtils.get().getIndexAsString(c, i); String jrDatestamp = (value == null) ? null : (new SimpleDateFormat(ISO8601_DATE_ONLY_FORMAT, Locale.ENGLISH)) .format(new Date(TableConstants.milliSecondsFromNanos(value))); putElementValue(values, defn, jrDatestamp); } else if (type.getElementType().equals("dateTime")) { String value = ODKDatabaseUtils.get().getIndexAsString(c, i); String jrDatestamp = (value == null) ? null : (new SimpleDateFormat(ISO8601_DATE_FORMAT, Locale.ENGLISH)) .format(new Date(TableConstants.milliSecondsFromNanos(value))); putElementValue(values, defn, jrDatestamp); } else if (type.getElementType().equals("time")) { String value = ODKDatabaseUtils.get().getIndexAsString(c, i); putElementValue(values, defn, value); } else if (dataType == ElementDataType.array) { ArrayList<Object> al = ODKDatabaseUtils.get().getIndexAsType(c, ArrayList.class, i); putElementValue(values, defn, al); } else if (dataType == ElementDataType.string) { String value = ODKDatabaseUtils.get().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 = ODKDatabaseUtils.get().getIndexAsString(c, i); } else if (columnName.equals(DataTableColumns.ROW_ETAG)) { rowETag = ODKDatabaseUtils.get().getIndexAsString(c, i); } else if (columnName.equals(DataTableColumns.FILTER_TYPE)) { filterType = ODKDatabaseUtils.get().getIndexAsString(c, i); } else if (columnName.equals(DataTableColumns.FILTER_VALUE)) { filterValue = ODKDatabaseUtils.get().getIndexAsString(c, i); } else if (columnName.equals(DataTableColumns.FORM_ID)) { formId = ODKDatabaseUtils.get().getIndexAsString(c, i); } else if (columnName.equals(DataTableColumns.LOCALE)) { locale = ODKDatabaseUtils.get().getIndexAsString(c, i); } else if (columnName.equals(DataTableColumns.FORM_ID)) { formId = ODKDatabaseUtils.get().getIndexAsString(c, i); } else if (columnName.equals(DataTableColumns.SAVEPOINT_TYPE)) { savepointType = ODKDatabaseUtils.get().getIndexAsString(c, i); } else if (columnName.equals(DataTableColumns.SAVEPOINT_CREATOR)) { savepointCreator = ODKDatabaseUtils.get().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) { 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.ENGLISH)) .format(new Date(TableConstants.milliSecondsFromNanos(savepointTimestamp))); // For XML, we traverse the map to serialize it Document d = new Document(); d.setStandalone(true); d.setEncoding(CharEncoding.UTF_8); Element e = d.createElement(XML_DEFAULT_NAMESPACE, (xmlRootElementName == null) ? "data" : xmlRootElementName); e.setPrefix("jr", XML_OPENROSA_NAMESPACE); e.setPrefix("", XML_DEFAULT_NAMESPACE); d.addChild(0, Node.ELEMENT, e); e.setAttribute("", "id", tableId); DynamicPropertiesCallback cb = new DynamicPropertiesCallback(getContext(), appName, tableId, instanceId); int idx = 0; Element meta = d.createElement(XML_OPENROSA_NAMESPACE, "meta"); Element v = d.createElement(XML_OPENROSA_NAMESPACE, "instanceID"); v.addChild(0, Node.TEXT, submissionInstanceId); meta.addChild(idx++, Node.ELEMENT, v); meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE); if (xmlDeviceIdPropertyName != null) { String deviceId = propertyManager.getSingularProperty(xmlDeviceIdPropertyName, cb); if (deviceId != null) { v = d.createElement(XML_OPENROSA_NAMESPACE, "deviceID"); v.addChild(0, Node.TEXT, deviceId); meta.addChild(idx++, Node.ELEMENT, v); meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE); } } if (xmlUserIdPropertyName != null) { String userId = propertyManager.getSingularProperty(xmlUserIdPropertyName, cb); if (userId != null) { v = d.createElement(XML_OPENROSA_NAMESPACE, "userID"); v.addChild(0, Node.TEXT, userId); meta.addChild(idx++, Node.ELEMENT, v); meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE); } } v = d.createElement(XML_OPENROSA_NAMESPACE, "timeEnd"); v.addChild(0, Node.TEXT, datestamp); meta.addChild(idx++, Node.ELEMENT, v); meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE); // these are extra metadata tags... if (instanceName != null) { v = d.createElement(XML_DEFAULT_NAMESPACE, "instanceName"); v.addChild(0, Node.TEXT, instanceName); meta.addChild(idx++, Node.ELEMENT, v); meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE); } else { v = d.createElement(XML_DEFAULT_NAMESPACE, "instanceName"); v.addChild(0, Node.TEXT, savepointTimestamp); meta.addChild(idx++, Node.ELEMENT, v); meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE); } // these are extra metadata tags... // rowID v = d.createElement(XML_DEFAULT_NAMESPACE, "rowID"); v.addChild(0, Node.TEXT, instanceId); meta.addChild(idx++, Node.ELEMENT, v); meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE); // rowETag v = d.createElement(XML_DEFAULT_NAMESPACE, "rowETag"); if (rowETag != null) { v.addChild(0, Node.TEXT, rowETag); } meta.addChild(idx++, Node.ELEMENT, v); meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE); // filterType v = d.createElement(XML_DEFAULT_NAMESPACE, "filterType"); if (filterType != null) { v.addChild(0, Node.TEXT, filterType); } meta.addChild(idx++, Node.ELEMENT, v); meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE); // filterValue v = d.createElement(XML_DEFAULT_NAMESPACE, "filterValue"); if (filterValue != null) { v.addChild(0, Node.TEXT, filterValue); } meta.addChild(idx++, Node.ELEMENT, v); meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE); // formID v = d.createElement(XML_DEFAULT_NAMESPACE, "formID"); v.addChild(0, Node.TEXT, formId); meta.addChild(idx++, Node.ELEMENT, v); meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE); // locale v = d.createElement(XML_DEFAULT_NAMESPACE, "locale"); v.addChild(0, Node.TEXT, locale); meta.addChild(idx++, Node.ELEMENT, v); meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE); // savepointType v = d.createElement(XML_DEFAULT_NAMESPACE, "savepointType"); v.addChild(0, Node.TEXT, savepointType); meta.addChild(idx++, Node.ELEMENT, v); meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE); // savepointCreator v = d.createElement(XML_DEFAULT_NAMESPACE, "savepointCreator"); if (savepointCreator != null) { v.addChild(0, Node.TEXT, savepointCreator); } meta.addChild(idx++, Node.ELEMENT, v); meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE); // savepointTimestamp v = d.createElement(XML_DEFAULT_NAMESPACE, "savepointTimestamp"); v.addChild(0, Node.TEXT, savepointTimestamp); meta.addChild(idx++, Node.ELEMENT, v); meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE); // and insert the meta block into the XML e.addChild(0, Node.IGNORABLE_WHITESPACE, NEW_LINE); e.addChild(1, Node.ELEMENT, meta); e.addChild(2, Node.IGNORABLE_WHITESPACE, NEW_LINE); 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, log); } KXmlSerializer serializer = new KXmlSerializer(); ByteArrayOutputStream bo = new ByteArrayOutputStream(); serializer.setOutput(bo, CharEncoding.UTF_8); // setting the response content type emits the // xml header. // just write the body here... d.writeChildren(serializer); serializer.flush(); bo.close(); b.append(bo.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, log); } } else { // Pre-processing -- collapse all mimeUri into filename for (ColumnDefinition defn : orderedDefns) { 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", ColumnDefinition.getDataModel(orderedDefns)); 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, log); } exportFile(freturn.serializeUriFragmentList(getContext()), manifest, log); return ParcelFileDescriptor.open(manifest, ParcelFileDescriptor.MODE_READ_ONLY); } } finally { if (c != null && !c.isClosed()) { c.close(); } } } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } finally { if (db != null) { db.close(); } } return null; }