List of usage examples for android.database SQLException SQLException
public SQLException(String error)
From source file:org.thomnichols.android.gmarks.GmarksProvider.java
@Override public Uri insert(Uri uri, ContentValues initialValues) { // Validate the requested uri if (sUriMatcher.match(uri) != BOOKMARKS_URI) { throw new IllegalArgumentException("Unknown URI " + uri); }// w ww. ja v a 2s . c om ContentValues values; if (initialValues != null) { values = new ContentValues(initialValues); } else { values = new ContentValues(); } Long now = Long.valueOf(System.currentTimeMillis()); // Make sure that the fields are all set if (values.containsKey(Bookmark.Columns.CREATED_DATE) == false) { values.put(Bookmark.Columns.CREATED_DATE, now); } if (values.containsKey(Bookmark.Columns.MODIFIED_DATE) == false) { values.put(Bookmark.Columns.MODIFIED_DATE, now); } if (values.containsKey(Bookmark.Columns.TITLE) == false) { Resources r = Resources.getSystem(); values.put(Bookmark.Columns.TITLE, r.getString(android.R.string.untitled)); } if (values.containsKey(Bookmark.Columns.DESCRIPTION) == false) { values.put(Bookmark.Columns.DESCRIPTION, ""); } SQLiteDatabase db = dbHelper.getWritableDatabase(); long rowId = db.insert(BOOKMARKS_TABLE_NAME, "", values); if (rowId > 0) { Uri noteUri = ContentUris.withAppendedId(Bookmark.CONTENT_URI, rowId); getContext().getContentResolver().notifyChange(noteUri, null); return noteUri; } throw new SQLException("Failed to insert row into " + uri); }
From source file:org.opendatakit.survey.android.provider.SubmissionProvider.java
/** * The incoming URI is of the form://from w w w .j a v a2s . c o m * ..../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; }
From source file:org.opendatakit.services.submissions.provider.SubmissionProvider.java
/** * The incoming URI is of the form:/*from w ww .j a v a2s.co 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:pl.selvin.android.syncframework.content.BaseContentProvider.java
@Override public Uri insert(Uri uri, ContentValues values) { final int code = contentHelper.matchUri(uri); if (code != UriMatcher.NO_MATCH) { if (code == ContentHelper.uriSyncCode) { throw new IllegalArgumentException("Can not insert with Sync Uri."); }//w ww.j a va 2 s .c om final TableInfo tab = contentHelper.getTableFromCode(code & ContentHelper.uriCode); if (tab.readonly) { throw new IllegalArgumentException("Table " + tab.name + " is readonly."); } if (isItemCode(code)) { throw new IllegalArgumentException("Can not delete with Item type Uri."); } /*-String tempId = UUID.randomUUID().toString(); if (tab.primaryKey.length == 1 && tab.primaryKey[0].type == ColumnType.guid) { tempId = values.getAsString(tab.primaryKey[0].name); }*/ boolean syncToNetwork = checkSyncToNetwork(uri); values.put("tempId", UUID.randomUUID().toString()); values.put("isDirty", 1); values.put("isDeleted", 0); long rowId = getWritableDatabase().insert(tab.name, null, values); if (rowId > 0) { Uri ret_uri = contentHelper.getItemUri(tab.name, syncToNetwork, rowId); final ContentResolver cr = getContext().getContentResolver(); cr.notifyChange(ret_uri, null, syncToNetwork); for (String n : tab.notifyUris) { cr.notifyChange(Uri.parse(n), null, syncToNetwork); } return ret_uri; } } throw new SQLException("Failed to insert row into " + uri); }
From source file:org.opendatakit.common.android.provider.impl.FormsProviderImpl.java
@Override public synchronized Uri insert(Uri uri, ContentValues initialValues) { List<String> segments = uri.getPathSegments(); if (segments.size() != 1) { throw new IllegalArgumentException("Unknown URI (too many segments!) " + uri); }// ww w.j ava2 s.c om String appName = segments.get(0); ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); WebLogger log = WebLogger.getLogger(appName); ContentValues values; if (initialValues != null) { values = new ContentValues(initialValues); } else { values = new ContentValues(); } // ODK2: require FORM_MEDIA_PATH (different behavior -- ODK1 and // required FORM_FILE_PATH) if (!values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) { throw new IllegalArgumentException(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + " must be specified."); } // Normalize path... File mediaPath = ODKFileUtils.asAppFile(appName, values.getAsString(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)); // require that the form directory actually exists if (!mediaPath.exists()) { throw new IllegalArgumentException(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + " directory does not exist: " + mediaPath.getAbsolutePath()); } patchUpValues(appName, values); if (values.containsKey(FormsColumns.DISPLAY_SUBTEXT) == false) { Date today = new Date(); String ts = new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time), Locale.getDefault()).format(today); values.put(FormsColumns.DISPLAY_SUBTEXT, ts); } if (values.containsKey(FormsColumns.DISPLAY_NAME) == false) { values.put(FormsColumns.DISPLAY_NAME, mediaPath.getName()); } // first try to see if a record with this filename already exists... String[] projection = { FormsColumns.FORM_ID, FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH }; String[] selectionArgs = { ODKFileUtils.asRelativePath(appName, mediaPath) }; String selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "=?"; Cursor c = null; SQLiteDatabase db = null; try { db = DatabaseFactory.get().getDatabase(getContext(), appName); db.beginTransaction(); try { c = db.query(DatabaseConstants.FORMS_TABLE_NAME, projection, selection, selectionArgs, null, null, null); if (c == null) { throw new SQLException("FAILED Insert into " + uri + " -- unable to query for existing records: " + mediaPath.getAbsolutePath()); } if (c.getCount() > 0) { // already exists throw new SQLException("FAILED Insert into " + uri + " -- row already exists for form directory: " + mediaPath.getAbsolutePath()); } } catch (Exception e) { log.w(t, "FAILED Insert into " + uri + " -- query for existing row failed: " + e.toString()); if (e instanceof SQLException) { throw (SQLException) e; } else { throw new SQLException( "FAILED Insert into " + uri + " -- query for existing row failed: " + e.toString()); } } finally { if (c != null) { c.close(); } } try { long rowId = db.insert(DatabaseConstants.FORMS_TABLE_NAME, null, values); db.setTransactionSuccessful(); if (rowId > 0) { Uri formUri = Uri.withAppendedPath( Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName), values.getAsString(FormsColumns.FORM_ID)); getContext().getContentResolver().notifyChange(formUri, null); Uri idUri = Uri.withAppendedPath( Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName), Long.toString(rowId)); getContext().getContentResolver().notifyChange(idUri, null); return formUri; } } catch (Exception e) { log.w(t, "FAILED Insert into " + uri + " -- insert of row failed: " + e.toString()); if (e instanceof SQLException) { throw (SQLException) e; } else { throw new SQLException( "FAILED Insert into " + uri + " -- insert of row failed: " + e.toString()); } } } finally { if (db != null) { db.endTransaction(); db.close(); } } throw new SQLException("Failed to insert row into " + uri); }
From source file:org.opendatakit.services.instance.provider.InstanceProvider.java
Cursor internalQuery(OdkConnectionInterface db, Uri uri, String appName, String tableId, String instanceId, String[] projection, String selection, String[] selectionArgs, String sortOrder) { PropertiesSingleton props = CommonToolProperties.get(getContext(), appName); String activeUser = props.getActiveUser(); String rolesList = props.getProperty(CommonToolProperties.KEY_ROLES_LIST); String fullQuery;//from www . j a v a2 s . c o m String filterArgs[]; Cursor c = null; OrderedColumns orderedDefns; StringBuilder b = new StringBuilder(); boolean success = false; try { success = ODKDatabaseImplUtils.get().hasTableId(db, tableId); } catch (Exception e) { WebLogger.getLogger(appName).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); } // Can't get away with dataTable.* because of collision with _ID column // get map of (elementKey -> ColumnDefinition) try { orderedDefns = ODKDatabaseImplUtils.get().getUserDefinedColumns(db, tableId); } catch (IllegalArgumentException e) { WebLogger.getLogger(appName).printStackTrace(e); throw new SQLException("Unable to retrieve column definitions for tableId " + tableId); } // ////////////////////////////////////////////////////////////// // OK we have the info we need -- now build the query we want... // We can now join through and access the data table rows b.setLength(0); // @formatter:off b.append("SELECT "); b.append(DatabaseConstants.UPLOADS_TABLE_NAME).append(".").append(InstanceColumns._ID).append(" as ") .append(InstanceColumns._ID).append(",").append(DatabaseConstants.UPLOADS_TABLE_NAME).append(".") .append(InstanceColumns.DATA_INSTANCE_ID).append(" as ").append(InstanceColumns.DATA_INSTANCE_ID) .append(",").append(DatabaseConstants.UPLOADS_TABLE_NAME).append(".") .append(InstanceColumns.SUBMISSION_INSTANCE_ID).append(" as ") .append(InstanceColumns.SUBMISSION_INSTANCE_ID).append(","); // add the dataTable metadata except for _ID (which conflicts with InstanceColumns._ID) b.append(tableId).append(".").append(DataTableColumns.ROW_ETAG).append(" as ") .append(DataTableColumns.ROW_ETAG).append(",").append(tableId).append(".") .append(DataTableColumns.SYNC_STATE).append(" as ").append(DataTableColumns.SYNC_STATE).append(",") .append(tableId).append(".").append(DataTableColumns.CONFLICT_TYPE).append(" as ") .append(DataTableColumns.CONFLICT_TYPE).append(",").append(tableId).append(".") .append(DataTableColumns.FILTER_TYPE).append(" as ").append(DataTableColumns.FILTER_TYPE) .append(",").append(tableId).append(".").append(DataTableColumns.FILTER_VALUE).append(" as ") .append(DataTableColumns.FILTER_VALUE).append(",").append(tableId).append(".") .append(DataTableColumns.FORM_ID).append(" as ").append(DataTableColumns.FORM_ID).append(",") .append(tableId).append(".").append(DataTableColumns.LOCALE).append(" as ") .append(DataTableColumns.LOCALE).append(",").append(tableId).append(".") .append(DataTableColumns.SAVEPOINT_TYPE).append(" as ").append(DataTableColumns.SAVEPOINT_TYPE) .append(",").append(tableId).append(".").append(DataTableColumns.SAVEPOINT_TIMESTAMP).append(" as ") .append(DataTableColumns.SAVEPOINT_TIMESTAMP).append(",").append(tableId).append(".") .append(DataTableColumns.SAVEPOINT_CREATOR).append(" as ") .append(DataTableColumns.SAVEPOINT_CREATOR).append(","); // add the user-specified data fields in this dataTable for (ColumnDefinition cd : orderedDefns.getColumnDefinitions()) { if (cd.isUnitOfRetention()) { b.append(tableId).append(".").append(cd.getElementKey()).append(" as ").append(cd.getElementKey()) .append(","); } } b.append("CASE WHEN ").append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(" IS NULL THEN null") .append(" WHEN ").append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" IS NULL THEN null") .append(" WHEN ").append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(" > ") .append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" THEN null").append(" ELSE ") .append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" END as ") .append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(","); b.append("CASE WHEN ").append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(" IS NULL THEN null") .append(" WHEN ").append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" IS NULL THEN null") .append(" WHEN ").append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(" > ") .append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" THEN null").append(" ELSE ") .append(InstanceColumns.XML_PUBLISH_STATUS).append(" END as ") .append(InstanceColumns.XML_PUBLISH_STATUS).append(","); b.append("CASE WHEN ").append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(" IS NULL THEN null") .append(" WHEN ").append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" IS NULL THEN null") .append(" WHEN ").append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(" > ") .append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" THEN null").append(" ELSE ") .append(InstanceColumns.DISPLAY_SUBTEXT).append(" END as ").append(InstanceColumns.DISPLAY_SUBTEXT) .append(","); b.append(InstanceColumns.DATA_INSTANCE_NAME); b.append(" as ").append(InstanceColumns.DISPLAY_NAME); b.append(" FROM "); b.append("( SELECT * FROM ").append(tableId).append(" AS T WHERE T.") .append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append("=(SELECT MAX(V.") .append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(") FROM ").append(tableId) .append(" AS V WHERE V.").append(DATA_TABLE_ID_COLUMN).append("=T.").append(DATA_TABLE_ID_COLUMN) .append(" AND V.").append(DATA_TABLE_SAVEPOINT_TYPE_COLUMN).append(" IS NOT NULL").append(")") .append(") as ").append(tableId); b.append(" JOIN ").append(DatabaseConstants.UPLOADS_TABLE_NAME).append(" ON ").append(tableId).append(".") .append(DATA_TABLE_ID_COLUMN).append("=").append(DatabaseConstants.UPLOADS_TABLE_NAME).append(".") .append(InstanceColumns.DATA_INSTANCE_ID).append(" AND ").append("? =") .append(DatabaseConstants.UPLOADS_TABLE_NAME).append(".") .append(InstanceColumns.DATA_TABLE_TABLE_ID); b.append(" WHERE ").append(DATA_TABLE_SAVEPOINT_TYPE_COLUMN).append("=?"); // @formatter:on if (instanceId != null) { b.append(" AND ").append(DatabaseConstants.UPLOADS_TABLE_NAME).append(".").append(InstanceColumns._ID) .append("=?"); String tempArgs[] = { tableId, InstanceColumns.STATUS_COMPLETE, instanceId }; filterArgs = tempArgs; } else { String tempArgs[] = { tableId, InstanceColumns.STATUS_COMPLETE }; filterArgs = tempArgs; } if (selection != null) { b.append(" AND (").append(selection).append(")"); } if (selectionArgs != null) { String[] tempArgs = new String[filterArgs.length + selectionArgs.length]; System.arraycopy(filterArgs, 0, tempArgs, 0, filterArgs.length); System.arraycopy(selectionArgs, 0, tempArgs, filterArgs.length + 0, selectionArgs.length); filterArgs = tempArgs; } if (sortOrder != null) { b.append(" ORDER BY ").append(sortOrder); } fullQuery = b.toString(); ODKDatabaseImplUtils.AccessContext accessContext = ODKDatabaseImplUtils.get().getAccessContext(db, tableId, activeUser, rolesList); c = ODKDatabaseImplUtils.get().rawQuery(db, fullQuery, filterArgs, null, accessContext); return c; }
From source file:de.nware.app.hsDroid.provider.onlineService2Provider.java
@Override public Uri insert(Uri uri, ContentValues initialValues) { if (mUriMatcher.match(uri) != EXAMS) { throw new IllegalArgumentException("Unbekannte URI " + uri); }//from www.j a va 2 s . c o m ContentValues contentValues; if (initialValues != null) { contentValues = new ContentValues(initialValues); } else { contentValues = new ContentValues(); } if (mOpenHelper == null) { Log.d(TAG, "mOpenHelper NULL"); } SQLiteDatabase db = mOpenHelper.getWritableDatabase(); long rowID = db.insert(mOpenHelper.getTableName(), ExamsCol.EXAMNAME, contentValues); if (rowID > 0) { Uri examsUri = ContentUris.withAppendedId(ExamsCol.CONTENT_URI, rowID); getContext().getContentResolver().notifyChange(examsUri, null); // Observer? return examsUri; } throw new SQLException("Konnte row nicht zu " + uri + " hinzufgen"); }
From source file:com.fututel.db.DBProvider.java
@Override public Uri insert(Uri uri, ContentValues initialValues) { int matched = URI_MATCHER.match(uri); String matchedTable = null;/*from w w w . j a va 2s .co m*/ Uri baseInsertedUri = null; switch (matched) { case ACCOUNTS: case ACCOUNTS_ID: matchedTable = SipProfile.ACCOUNTS_TABLE_NAME; baseInsertedUri = SipProfile.ACCOUNT_ID_URI_BASE; break; case CALLLOGS: case CALLLOGS_ID: matchedTable = SipManager.CALLLOGS_TABLE_NAME; baseInsertedUri = SipManager.CALLLOG_ID_URI_BASE; break; case FILTERS: case FILTERS_ID: matchedTable = SipManager.FILTERS_TABLE_NAME; baseInsertedUri = SipManager.FILTER_ID_URI_BASE; break; case MESSAGES: case MESSAGES_ID: matchedTable = SipMessage.MESSAGES_TABLE_NAME; baseInsertedUri = SipMessage.MESSAGE_ID_URI_BASE; break; case ACCOUNTS_STATUS_ID: long id = ContentUris.parseId(uri); synchronized (profilesStatus) { SipProfileState ps = new SipProfileState(); if (profilesStatus.containsKey(id)) { ContentValues currentValues = profilesStatus.get(id); ps.createFromContentValue(currentValues); } ps.createFromContentValue(initialValues); ContentValues cv = ps.getAsContentValue(); cv.put(SipProfileState.ACCOUNT_ID, id); profilesStatus.put(id, cv); Log.d(THIS_FILE, "Added " + cv); } getContext().getContentResolver().notifyChange(uri, null); return uri; default: break; } if (matchedTable == null) { throw new IllegalArgumentException(UNKNOWN_URI_LOG + uri); } ContentValues values; if (initialValues != null) { values = new ContentValues(initialValues); } else { values = new ContentValues(); } SQLiteDatabase db = mOpenHelper.getWritableDatabase(); long rowId = db.insert(matchedTable, null, values); // If the insert succeeded, the row ID exists. if (rowId >= 0) { // TODO : for inserted account register it here Uri retUri = ContentUris.withAppendedId(baseInsertedUri, rowId); getContext().getContentResolver().notifyChange(retUri, null); if (matched == ACCOUNTS || matched == ACCOUNTS_ID) { broadcastAccountChange(rowId); } if (matched == CALLLOGS || matched == CALLLOGS_ID) { db.delete(SipManager.CALLLOGS_TABLE_NAME, CallLog.Calls._ID + " IN " + "(SELECT " + CallLog.Calls._ID + " FROM " + SipManager.CALLLOGS_TABLE_NAME + " ORDER BY " + CallLog.Calls.DEFAULT_SORT_ORDER + " LIMIT -1 OFFSET 500)", null); } if (matched == ACCOUNTS_STATUS || matched == ACCOUNTS_STATUS_ID) { broadcastRegistrationChange(rowId); } if (matched == FILTERS || matched == FILTERS_ID) { Filter.resetCache(); } return retUri; } throw new SQLException("Failed to insert row into " + uri); }
From source file:org.opendatakit.common.android.provider.impl.InstanceProviderImpl.java
/** * This method removes the entry from the content provider, and also removes * any associated files. files: form.xml, [formmd5].formdef, formname * {directory}//from w w w . j a va 2s.c o m */ @Override public int delete(Uri uri, String where, String[] whereArgs) { List<String> segments = uri.getPathSegments(); if (segments.size() < 2 || segments.size() > 3) { throw new SQLException("Unknown URI (too many segments!) " + uri); } String appName = segments.get(0); ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); String tableId = segments.get(1); // _ID in UPLOADS_TABLE_NAME String instanceId = (segments.size() == 3 ? segments.get(2) : null); SQLiteDatabase db = null; List<IdStruct> idStructs = new ArrayList<IdStruct>(); try { db = DatabaseFactory.get().getDatabase(getContext(), appName); db.beginTransaction(); 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); } String dbTableName = "\"" + tableId + "\""; if (segments.size() == 2) { where = "(" + where + ") AND (" + InstanceColumns.DATA_INSTANCE_ID + "=? )"; if (whereArgs != null) { String[] args = new String[whereArgs.length + 1]; for (int i = 0; i < whereArgs.length; ++i) { args[i] = whereArgs[i]; } args[whereArgs.length] = instanceId; whereArgs = args; } else { whereArgs = new String[] { instanceId }; } } Cursor del = null; try { del = this.query(uri, null, where, whereArgs, null); del.moveToPosition(-1); while (del.moveToNext()) { String iId = ODKDatabaseUtils.get().getIndexAsString(del, del.getColumnIndex(InstanceColumns._ID)); String iIdDataTable = ODKDatabaseUtils.get().getIndexAsString(del, del.getColumnIndex(InstanceColumns.DATA_INSTANCE_ID)); idStructs.add(new IdStruct(iId, iIdDataTable)); String path = ODKFileUtils.getInstanceFolder(appName, tableId, iIdDataTable); File f = new File(path); if (f.exists()) { if (f.isDirectory()) { FileUtils.deleteDirectory(f); } else { f.delete(); } } } } catch (IOException e) { e.printStackTrace(); throw new IllegalArgumentException("Unable to delete instance directory: " + e.toString()); } finally { if (del != null) { del.close(); } } for (IdStruct idStruct : idStructs) { db.delete(DatabaseConstants.UPLOADS_TABLE_NAME, InstanceColumns.DATA_INSTANCE_ID + "=?", new String[] { idStruct.idUploadsTable }); db.delete(dbTableName, DATA_TABLE_ID_COLUMN + "=?", new String[] { idStruct.idDataTable }); } db.setTransactionSuccessful(); } finally { if (db != null) { db.endTransaction(); db.close(); } } getContext().getContentResolver().notifyChange(uri, null); return idStructs.size(); }
From source file:com.sonetel.db.DBProvider.java
@Override public Uri insert(Uri uri, ContentValues initialValues) { int matched = URI_MATCHER.match(uri); String matchedTable = null;//from w w w . j a v a 2 s . com Uri baseInsertedUri = null; switch (matched) { case ACCOUNTS: case ACCOUNTS_ID: matchedTable = SipProfile.ACCOUNTS_TABLE_NAME; baseInsertedUri = SipProfile.ACCOUNT_ID_URI_BASE; break; case CALLLOGS: case CALLLOGS_ID: matchedTable = SipManager.CALLLOGS_TABLE_NAME; baseInsertedUri = SipManager.CALLLOG_ID_URI_BASE; break; case FILTERS: case FILTERS_ID: matchedTable = SipManager.FILTERS_TABLE_NAME; baseInsertedUri = SipManager.FILTER_ID_URI_BASE; break; case MESSAGES: case MESSAGES_ID: matchedTable = SipMessage.MESSAGES_TABLE_NAME; baseInsertedUri = SipMessage.MESSAGE_ID_URI_BASE; break; case ACCESSNO: matchedTable = SipProfile.ACCESS_NUMS_TABLE_NAME; baseInsertedUri = SipProfile.ACCESS_URI_BASE; break; case ACCOUNTS_STATUS_ID: long id = ContentUris.parseId(uri); synchronized (profilesStatus) { SipProfileState ps = new SipProfileState(); if (profilesStatus.containsKey(id)) { ContentValues currentValues = profilesStatus.get(id); ps.createFromContentValue(currentValues); } ps.createFromContentValue(initialValues); ContentValues cv = ps.getAsContentValue(); cv.put(SipProfileState.ACCOUNT_ID, id); profilesStatus.put(id, cv); Log.d(THIS_FILE, "Added " + cv); } getContext().getContentResolver().notifyChange(uri, null); return uri; default: break; } if (matchedTable == null) { throw new IllegalArgumentException(UNKNOWN_URI_LOG + uri); } ContentValues values; if (initialValues != null) { values = new ContentValues(initialValues); } else { values = new ContentValues(); } SQLiteDatabase db = mOpenHelper.getWritableDatabase(); long rowId = db.insert(matchedTable, null, values); // If the insert succeeded, the row ID exists. if (rowId >= 0) { // TODO : for inserted account register it here Uri retUri = ContentUris.withAppendedId(baseInsertedUri, rowId); getContext().getContentResolver().notifyChange(retUri, null); if (matched == ACCOUNTS || matched == ACCOUNTS_ID) { broadcastAccountChange(rowId); } if (matched == CALLLOGS || matched == CALLLOGS_ID) { db.delete(SipManager.CALLLOGS_TABLE_NAME, CallLog.Calls._ID + " IN " + "(SELECT " + CallLog.Calls._ID + " FROM " + SipManager.CALLLOGS_TABLE_NAME + " ORDER BY " + CallLog.Calls.DEFAULT_SORT_ORDER + " LIMIT -1 OFFSET 500)", null); } if (matched == ACCOUNTS_STATUS || matched == ACCOUNTS_STATUS_ID) { broadcastRegistrationChange(rowId); } if (matched == FILTERS || matched == FILTERS_ID) { Filter.resetCache(); } return retUri; } throw new SQLException("Failed to insert row into " + uri); }