Example usage for android.net Uri getPathSegments

List of usage examples for android.net Uri getPathSegments

Introduction

In this page you can find the example usage for android.net Uri getPathSegments.

Prototype

public abstract List<String> getPathSegments();

Source Link

Document

Gets the decoded path segments.

Usage

From source file:org.opendatakit.services.instance.provider.InstanceProvider.java

@Override
public synchronized int update(@NonNull Uri uri, ContentValues cv, String where, String[] whereArgs) {
    possiblyWaitForContentProviderDebugger();

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

    if (segments.size() != 3) {
        throw new SQLException("Unknown URI (does not specify instance!) " + uri);
    }//from   www  . j a va 2 s.  com

    String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);

    String tableId = segments.get(1);
    // _ID in UPLOADS_TABLE_NAME
    String instanceId = segments.get(2);

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

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

        internalUpdate(db, uri, appName, tableId);

        // run the query to get all the ids...
        List<IdStruct> idStructs = new ArrayList<IdStruct>();
        Cursor ref = null;
        try {
            // use this provider's query interface to get the set of ids that
            // match (if any)
            ref = internalQuery(db, uri, appName, tableId, instanceId, null, where, whereArgs, null);
            ref.moveToFirst();
            if (ref.getCount() != 0) {
                do {
                    String iId = CursorUtils.getIndexAsString(ref, ref.getColumnIndex(InstanceColumns._ID));
                    String iIdDataTable = CursorUtils.getIndexAsString(ref,
                            ref.getColumnIndex(InstanceColumns.DATA_INSTANCE_ID));
                    idStructs.add(new IdStruct(iId, iIdDataTable));
                } while (ref.moveToNext());
            }
        } finally {
            if (ref != null) {
                ref.close();
            }
        }

        // update the values string...
        if (cv.containsKey(InstanceColumns.XML_PUBLISH_STATUS)) {
            Date xmlPublishDate = new Date();
            cv.put(InstanceColumns.XML_PUBLISH_TIMESTAMP,
                    TableConstants.nanoSecondsFromMillis(xmlPublishDate.getTime()));
            String xmlPublishStatus = cv.getAsString(InstanceColumns.XML_PUBLISH_STATUS);
            if (!cv.containsKey(InstanceColumns.DISPLAY_SUBTEXT)) {
                String text = getDisplaySubtext(xmlPublishStatus, xmlPublishDate);
                cv.put(InstanceColumns.DISPLAY_SUBTEXT, text);
            }
        }

        Map<String, Object> values = new HashMap<String, Object>();
        for (String key : cv.keySet()) {
            values.put(key, cv.get(key));
        }

        Object[] args = new String[1];
        for (IdStruct idStruct : idStructs) {
            args[0] = idStruct.idUploadsTable;
            count += db.update(DatabaseConstants.UPLOADS_TABLE_NAME, values, InstanceColumns._ID + "=?", args);
        }
        db.setTransactionSuccessful();
    } finally {
        if (db != null) {
            try {
                if (db.inTransaction()) {
                    db.endTransaction();
                }
            } finally {
                try {
                    db.releaseReference();
                } finally {
                    // this closes the connection
                    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().removeConnection(appName,
                            dbHandleName);
                }
            }
        }
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return count;
}

From source file:cn.edu.wyu.documentviewer.RecentsProvider.java

@Override
public Uri insert(Uri uri, ContentValues values) {
    final SQLiteDatabase db = mHelper.getWritableDatabase();
    final ContentValues key = new ContentValues();
    switch (sMatcher.match(uri)) {
    case URI_RECENT:
        values.put(RecentColumns.TIMESTAMP, System.currentTimeMillis());
        db.insert(TABLE_RECENT, null, values);
        final long cutoff = System.currentTimeMillis() - MAX_HISTORY_IN_MILLIS;
        db.delete(TABLE_RECENT, RecentColumns.TIMESTAMP + "<" + cutoff, null);
        return uri;
    case URI_STATE:
        final String authority = uri.getPathSegments().get(1);
        final String rootId = uri.getPathSegments().get(2);
        final String documentId = uri.getPathSegments().get(3);

        key.put(StateColumns.AUTHORITY, authority);
        key.put(StateColumns.ROOT_ID, rootId);
        key.put(StateColumns.DOCUMENT_ID, documentId);

        // Ensure that row exists, then update with changed values
        db.insertWithOnConflict(TABLE_STATE, null, key, SQLiteDatabase.CONFLICT_IGNORE);
        db.update(TABLE_STATE, values, StateColumns.AUTHORITY + "=? AND " + StateColumns.ROOT_ID + "=? AND "
                + StateColumns.DOCUMENT_ID + "=?", new String[] { authority, rootId, documentId });

        return uri;
    case URI_RESUME:
        values.put(ResumeColumns.TIMESTAMP, System.currentTimeMillis());

        final String packageName = uri.getPathSegments().get(1);
        key.put(ResumeColumns.PACKAGE_NAME, packageName);

        // Ensure that row exists, then update with changed values
        db.insertWithOnConflict(TABLE_RESUME, null, key, SQLiteDatabase.CONFLICT_IGNORE);
        db.update(TABLE_RESUME, values, ResumeColumns.PACKAGE_NAME + "=?", new String[] { packageName });
        return uri;
    default://from w  ww .  jav a  2  s .c  o m
        throw new UnsupportedOperationException("Unsupported Uri " + uri);
    }
}

From source file:org.opendatakit.services.instance.provider.InstanceProvider.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 .  ja  v  a 2  s.c o m
 */
@Override
public synchronized int delete(@NonNull Uri uri, String where, String[] whereArgs) {
    possiblyWaitForContentProviderDebugger();

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

    DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
            .generateInternalUseDbHandle();
    OdkConnectionInterface db = null;
    List<IdStruct> idStructs = new ArrayList<IdStruct>();
    try {
        // +1 referenceCount if db is returned (non-null)
        db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(appName,
                dbHandleName);
        db.beginTransactionNonExclusive();

        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) {
            // delete the entries matching the filter criteria
            if (segments.size() == 2) {
                where = "(" + where + ") AND (" + InstanceColumns.DATA_INSTANCE_ID + "=? )";
                if (whereArgs != null) {
                    String[] args = new String[whereArgs.length + 1];
                    System.arraycopy(whereArgs, 0, args, 0, whereArgs.length);
                    args[whereArgs.length] = instanceId;
                    whereArgs = args;
                } else {
                    whereArgs = new String[] { instanceId };
                }
            }

            internalUpdate(db, uri, appName, tableId);

            Cursor del = null;
            try {
                del = internalQuery(db, uri, appName, tableId, instanceId, null, where, whereArgs, null);
                del.moveToPosition(-1);
                while (del.moveToNext()) {
                    String iId = CursorUtils.getIndexAsString(del, del.getColumnIndex(InstanceColumns._ID));
                    String iIdDataTable = CursorUtils.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) {
                WebLogger.getLogger(appName).printStackTrace(e);
                throw new IllegalArgumentException("Unable to delete instance directory: " + e.toString());
            } finally {
                if (del != null) {
                    del.close();
                }
            }
        } else {
            // delete anything we find, since the table doesn't exist
            Cursor del = null;
            try {
                where = InstanceColumns.DATA_TABLE_TABLE_ID + "=?";
                whereArgs = new String[] { tableId };
                del = db.query(DatabaseConstants.UPLOADS_TABLE_NAME, null, where, whereArgs, null, null, null,
                        null);
                del.moveToPosition(-1);
                while (del.moveToNext()) {
                    String iId = CursorUtils.getIndexAsString(del, del.getColumnIndex(InstanceColumns._ID));
                    String iIdDataTable = CursorUtils.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) {
                WebLogger.getLogger(appName).printStackTrace(e);
                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(tableId, DATA_TABLE_ID_COLUMN + "=?", new String[] { idStruct.idDataTable });
        }
        db.setTransactionSuccessful();
    } finally {
        if (db != null) {
            try {
                if (db.inTransaction()) {
                    db.endTransaction();
                }
            } finally {
                try {
                    db.releaseReference();
                } finally {
                    // this closes the connection
                    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().removeConnection(appName,
                            dbHandleName);
                }
            }
        }
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return idStructs.size();
}

From source file:org.opendatakit.services.forms.provider.FormsProvider.java

@Override
public Cursor query(@NonNull Uri uri, String[] projection, String where, String[] whereArgs, String sortOrder) {
    possiblyWaitForContentProviderDebugger();

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

    PatchedFilter pf = extractUriFeatures(uri, segments, where, whereArgs);
    WebLoggerIf log = WebLogger.getLogger(pf.appName);

    // Get the database and run the query
    DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
            .generateInternalUseDbHandle();
    OdkConnectionInterface db = null;// w  w w. j av  a 2 s. c  om
    boolean success = false;
    Cursor c = null;
    try {
        // +1 referenceCount if db is returned (non-null)
        db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(pf.appName,
                dbHandleName);
        c = db.query(DatabaseConstants.FORMS_TABLE_NAME, projection, pf.whereId, pf.whereIdArgs, null, null,
                sortOrder, null);

        if (c == null) {
            log.w(t, "Unable to query database");
            return null;
        }
        // Tell the cursor what uri to watch, so it knows when its source data changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
        c.registerDataSetObserver(new InvalidateMonitor(pf.appName, dbHandleName));
        success = true;
        return c;
    } catch (Exception e) {
        log.w(t, "Exception while querying database");
        log.printStackTrace(e);
        return null;
    } finally {
        if (db != null) {
            try {
                db.releaseReference();
            } finally {
                if (!success) {
                    // this closes the connection
                    // if it was successful, then the InvalidateMonitor will close the connection
                    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
                            .removeConnection(pf.appName, dbHandleName);
                }
            }
        }
    }
}

From source file:org.rapidandroid.activity.FormReviewer.java

private void doCsvDirectBednetsInjection() {
    String rawMessageText = "";

    try {/*ww w. j  a v  a  2s. co m*/
        InputStream is = this.getAssets().open("testdata/rawdata.csv");

        int size = is.available();

        // Read the entire asset into a local byte buffer.
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();

        // Convert the buffer into a Java string.
        String text = new String(buffer);

        rawMessageText = text;

    } catch (IOException e) {
        // Should never happen!
        throw new RuntimeException(e);
    }

    StringReader sr = new StringReader(rawMessageText);
    BufferedReader bufRdr = new BufferedReader(sr);

    String line = null;
    //      int row = 0;
    //      int col = 0;
    Vector<String[]> lines = new Vector<String[]>();
    // read each line of text file
    try {
        while ((line = bufRdr.readLine()) != null) {
            StringTokenizer st = new StringTokenizer(line, ",");
            int tokCount = st.countTokens();

            String[] tokenizedLine = new String[tokCount];
            int toki = 0;
            while (st.hasMoreTokens()) {
                tokenizedLine[toki] = st.nextToken();
                toki++;
            }
            lines.add(tokenizedLine);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {

        try {
            sr.close();
            bufRdr.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    int len = lines.size();

    for (int i = 0; i < len; i++) {
        String[] csvline = lines.get(i);

        String datestr = csvline[0];

        Date dateval = new Date();
        try {
            dateval = Message.SQLDateFormatter.parse(datestr);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }
        String sender = csvline[1];
        String text = csvline[2];

        Monitor monitor = MessageTranslator.GetMonitorAndInsertIfNew(this, sender);

        ContentValues messageValues = new ContentValues();
        messageValues.put(RapidSmsDBConstants.Message.MESSAGE, text);
        messageValues.put(RapidSmsDBConstants.Message.MONITOR, monitor.getID());

        messageValues.put(RapidSmsDBConstants.Message.TIME, Message.SQLDateFormatter.format(dateval));
        messageValues.put(RapidSmsDBConstants.Message.RECEIVE_TIME, Message.SQLDateFormatter.format(dateval));
        messageValues.put(RapidSmsDBConstants.Message.IS_OUTGOING, false);

        Uri msgUri = null;

        msgUri = this.getContentResolver().insert(RapidSmsDBConstants.Message.CONTENT_URI, messageValues);
        Vector<IParseResult> results = ParsingService.ParseMessage(mForm, text);
        ParsedDataTranslator.InsertFormData(this, mForm,
                Integer.valueOf(msgUri.getPathSegments().get(1)).intValue(), results);
    }

}

From source file:org.opendatakit.common.android.provider.impl.FormsProviderImpl.java

@Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() < 1 || segments.size() > 2) {
        throw new IllegalArgumentException("Unknown URI (incorrect number of segments!) " + uri);
    }//from   w  w  w. j  a v  a2 s. c  o m

    String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);
    WebLogger log = WebLogger.getLogger(appName);

    String uriFormId = ((segments.size() == 2) ? segments.get(1) : null);
    boolean isNumericId = StringUtils.isNumeric(uriFormId);

    // Modify the where clause to account for the presence of
    // a form id. Accept either:
    // (1) numeric _ID value
    // (2) string FORM_ID value.
    String whereId;
    String[] whereIdArgs;

    if (uriFormId == null) {
        whereId = where;
        whereIdArgs = whereArgs;
    } else {
        if (TextUtils.isEmpty(where)) {
            whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=?";
            whereIdArgs = new String[1];
            whereIdArgs[0] = uriFormId;
        } else {
            whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=? AND (" + where + ")";
            whereIdArgs = new String[whereArgs.length + 1];
            whereIdArgs[0] = uriFormId;
            for (int i = 0; i < whereArgs.length; ++i) {
                whereIdArgs[i + 1] = whereArgs[i];
            }
        }
    }

    /*
     * First, find out what records match this query, and if they refer to two
     * or more (formId,formVersion) tuples, then be sure to remove all
     * FORM_MEDIA_PATH references. Otherwise, if they are all for the same
     * tuple, and the update specifies a FORM_MEDIA_PATH, move all the
     * non-matching directories elsewhere.
     */
    Integer idValue = null;
    String tableIdValue = null;
    String formIdValue = null;
    HashMap<File, DirType> mediaDirs = new HashMap<File, DirType>();
    boolean multiset = false;
    Cursor c = null;
    try {
        c = this.query(uri, null, whereId, whereIdArgs, null);
        if (c == null) {
            throw new SQLException(
                    "FAILED Update of " + uri + " -- query for existing row did not return a cursor");
        }
        if (c.getCount() >= 1) {
            FormIdVersion ref = null;
            c.moveToPosition(-1);
            while (c.moveToNext()) {
                idValue = ODKDatabaseUtils.get().getIndexAsType(c, Integer.class,
                        c.getColumnIndex(FormsColumns._ID));
                tableIdValue = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.TABLE_ID));
                formIdValue = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.FORM_ID));
                String tableId = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.TABLE_ID));
                String formId = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.FORM_ID));
                String formVersion = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.FORM_VERSION));
                FormIdVersion cur = new FormIdVersion(tableId, formId, formVersion);

                int appRelativeMediaPathIdx = c.getColumnIndex(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH);
                String mediaPath = ODKDatabaseUtils.get().getIndexAsString(c, appRelativeMediaPathIdx);
                if (mediaPath != null) {
                    mediaDirs.put(ODKFileUtils.asAppFile(appName, mediaPath),
                            (tableIdValue == null) ? DirType.FRAMEWORK : DirType.FORMS);
                }

                if (ref != null && !ref.equals(cur)) {
                    multiset = true;
                    break;
                } else {
                    ref = cur;
                }
            }
        }
    } catch (Exception e) {
        log.w(t, "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString());

        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else {
            throw new SQLException(
                    "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString());
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }

    if (multiset) {
        // don't let users manually update media path
        // we are referring to two or more (formId,formVersion) tuples.
        if (values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) {
            values.remove(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH);
        }
    } else if (values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) {
        // we are not a multiset and we are setting the media path
        // try to move all the existing non-matching media paths to
        // somewhere else...
        File mediaPath = ODKFileUtils.asAppFile(appName,
                values.getAsString(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH));
        for (HashMap.Entry<File, DirType> entry : mediaDirs.entrySet()) {
            File altPath = entry.getKey();
            if (!altPath.equals(mediaPath)) {
                try {
                    moveDirectory(appName, entry.getValue(), altPath);
                } catch (IOException e) {
                    e.printStackTrace();
                    log.e(t, "Attempt to move " + altPath.getAbsolutePath() + " failed: " + e.toString());
                }
            }
        }
        // OK. we have moved the existing form definitions elsewhere. We can
        // proceed with update...
    }

    // ensure that all values are correct and ignore some user-supplied
    // values...
    patchUpValues(appName, values);

    // Make sure that the necessary fields are all set
    if (values.containsKey(FormsColumns.DATE) == true) {
        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);
    }

    SQLiteDatabase db = null;
    int count;
    try {
        // OK Finally, now do the update...
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        db.beginTransaction();
        count = db.update(DatabaseConstants.FORMS_TABLE_NAME, values, whereId, whereIdArgs);
        db.setTransactionSuccessful();
    } catch (Exception e) {
        e.printStackTrace();
        log.w(t, "Unable to perform update " + uri);
        return 0;
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }

    if (count == 1) {
        Uri formUri = Uri.withAppendedPath(
                Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName), formIdValue);
        getContext().getContentResolver().notifyChange(formUri, null);
        Uri idUri = Uri.withAppendedPath(
                Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                Long.toString(idValue));
        getContext().getContentResolver().notifyChange(idUri, null);
    } else {
        getContext().getContentResolver().notifyChange(uri, null);
    }
    return count;
}

From source file:org.opendatakit.services.forms.provider.FormsProvider.java

@Override
public synchronized Uri insert(@NonNull Uri uri, ContentValues initialValues) {
    possiblyWaitForContentProviderDebugger();

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

    if (segments.size() != 1) {
        throw new IllegalArgumentException("Unknown URI (too many segments!) " + uri);
    }// w  ww .  j a  v  a 2 s  . c  o m

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

    HashMap<String, Object> values = new HashMap<String, Object>();
    if (initialValues != null) {
        for (String key : initialValues.keySet()) {
            values.put(key, initialValues.get(key));
        }
    }

    // force a scan from disk
    values.remove(FormsColumns.DATE);
    values.remove(FormsColumns.JSON_MD5_HASH);
    FormSpec formSpec = patchUpValues(appName, values);

    // first try to see if a record with this filename already exists...
    String[] projection = { FormsColumns.TABLE_ID, FormsColumns.FORM_ID };
    String selection = FormsColumns.TABLE_ID + "=? AND " + FormsColumns.FORM_ID + "=?";
    String[] selectionArgs = { formSpec.tableId, formSpec.formId };
    Cursor c = null;

    DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
            .generateInternalUseDbHandle();
    OdkConnectionInterface db = null;
    try {
        // +1 referenceCount if db is returned (non-null)
        db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(appName,
                dbHandleName);
        db.beginTransactionNonExclusive();
        try {
            c = db.query(DatabaseConstants.FORMS_TABLE_NAME, projection, selection, selectionArgs, null, null,
                    null, null);
            if (c == null) {
                throw new SQLException(
                        "FAILED Insert into " + uri + " -- unable to query for existing records. tableId="
                                + formSpec.tableId + " formId=" + formSpec.formId);
            }
            c.moveToFirst();
            if (c.getCount() > 0) {
                // already exists
                throw new SQLException("FAILED Insert into " + uri + " -- row already exists for  tableId="
                        + formSpec.tableId + " formId=" + formSpec.formId);
            }
        } 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.insertOrThrow(DatabaseConstants.FORMS_TABLE_NAME, null, values);
            db.setTransactionSuccessful();
            // and notify listeners of the new row...
            Uri formUri = Uri.withAppendedPath(
                    Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                    (String) values.get(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());
            }
        }
    } catch (SQLException e) {
        throw e;
    } catch (Exception e) {
        throw new SQLException("FAILED Insert into " + uri + " -- insert of row failed: " + e.toString());
    } finally {
        if (db != null) {
            try {
                if (db.inTransaction()) {
                    db.endTransaction();
                }
            } finally {
                try {
                    db.releaseReference();
                } finally {
                    // this closes the connection
                    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().removeConnection(appName,
                            dbHandleName);
                }
            }
        }
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.DungBeetleContentProvider.java

@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    final String appId = getCallingActivityId();
    if (appId == null) {
        Log.d(TAG, "No AppId for calling activity. Ignoring query.");
        return 0;
    }//from   w  w w . j ava 2  s  .  c o m
    if (!appId.equals(SUPER_APP_ID))
        return 0;
    List<String> segs = uri.getPathSegments();

    // TODO: If uri is a feed:
    //String appRestriction = DbObject.APP_ID + "='" + appId + "'";
    //selection = DBHelper.andClauses(selection, appRestriction);

    if (DBG)
        Log.d(TAG, "Updating uri " + uri + " with " + values);
    int count = mHelper.getWritableDatabase().update(segs.get(0), values, selection, selectionArgs);
    if (count > 0) {
        getContext().getContentResolver().notifyChange(uri, null);
    }
    return count;
}

From source file:org.opendatakit.services.forms.provider.FormsProvider.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 ww .  j  a  va 2 s.  c om*/
 */
@Override
public synchronized int delete(@NonNull Uri uri, String where, String[] whereArgs) {
    possiblyWaitForContentProviderDebugger();

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

    PatchedFilter pf = extractUriFeatures(uri, segments, where, whereArgs);
    WebLoggerIf logger = WebLogger.getLogger(pf.appName);

    String[] projection = { FormsColumns._ID, FormsColumns.TABLE_ID, FormsColumns.FORM_ID };

    HashMap<String, FormSpec> directories = new HashMap<String, FormSpec>();

    DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
            .generateInternalUseDbHandle();
    OdkConnectionInterface db = null;
    Cursor c = null;

    Integer idValue = null;
    String tableIdValue = null;
    String formIdValue = null;
    try {
        // Get the database and run the query
        // +1 referenceCount if db is returned (non-null)
        db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(pf.appName,
                dbHandleName);
        db.beginTransactionNonExclusive();
        c = db.query(DatabaseConstants.FORMS_TABLE_NAME, projection, pf.whereId, pf.whereIdArgs, null, null,
                null, null);

        if (c == null) {
            throw new SQLException("FAILED Delete into " + uri + " -- unable to query for existing records");
        }

        int idxId = c.getColumnIndex(FormsColumns._ID);
        int idxTableId = c.getColumnIndex(FormsColumns.TABLE_ID);
        int idxFormId = c.getColumnIndex(FormsColumns.FORM_ID);

        if (c.moveToFirst()) {
            do {
                idValue = CursorUtils.getIndexAsType(c, Integer.class, idxId);
                tableIdValue = CursorUtils.getIndexAsString(c, idxTableId);
                formIdValue = CursorUtils.getIndexAsString(c, idxFormId);
                FormSpec formSpec = new FormSpec();
                formSpec.tableId = tableIdValue;
                formSpec.formId = formIdValue;
                formSpec.success = false;
                directories.put(idValue.toString(), formSpec);
            } while (c.moveToNext());
        }
        c.close();
        c = null;

        // and now go through this list moving the directories 
        // into the pending-deletion location and deleting them.
        for (Entry<String, FormSpec> de : directories.entrySet()) {
            String id = de.getKey();
            FormSpec fs = de.getValue();

            File srcDir = new File(ODKFileUtils.getFormFolder(pf.appName, fs.tableId, fs.formId));
            File destDir = new File(ODKFileUtils.getPendingDeletionTablesFolder(pf.appName),
                    fs.tableId + "." + fs.formId + "." + System.currentTimeMillis());

            try {
                FileUtils.moveDirectory(srcDir, destDir);
                if (db.delete(DatabaseConstants.FORMS_TABLE_NAME, FormsColumns._ID + "=?",
                        new String[] { id }) > 0) {
                    fs.success = true;
                }
            } catch (IOException e) {
                logger.e(t, "Unable to move directory prior to deleting it: " + e.toString());
                logger.printStackTrace(e);
            }
        }

        // commit the transaction...
        db.setTransactionSuccessful();

    } catch (Exception e) {
        logger.w(t, "FAILED Delete from " + uri + " -- query for existing row failed: " + e.toString());

        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else {
            throw new SQLException(
                    "FAILED Delete from " + uri + " -- query for existing row failed: " + e.toString());
        }
    } finally {
        if (db != null) {
            try {
                try {
                    if (c != null && !c.isClosed()) {
                        c.close();
                    }
                } finally {
                    if (db.inTransaction()) {
                        db.endTransaction();
                    }
                }
            } finally {
                try {
                    db.releaseReference();
                } finally {
                    // this closes the connection
                    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
                            .removeConnection(pf.appName, dbHandleName);
                }
            }
        }
    }

    // and now, go through all the files in the pending-deletion 
    // directory and try to release them.

    File destFolder = new File(ODKFileUtils.getPendingDeletionTablesFolder(pf.appName));

    File[] delDirs = destFolder.listFiles();
    for (File formIdDir : delDirs) {
        try {
            FileUtils.deleteDirectory(formIdDir);
        } catch (IOException e) {
            logger.e(t, "Unable to remove directory " + e.toString());
            logger.printStackTrace(e);
        }
    }

    int failureCount = 0;
    for (Entry<String, FormSpec> e : directories.entrySet()) {
        String id = e.getKey();
        FormSpec fs = e.getValue();
        if (fs.success) {
            Uri formUri = Uri
                    .withAppendedPath(
                            Uri.withAppendedPath(Uri.withAppendedPath(
                                    Uri.parse("content://" + getFormsAuthority()), pf.appName), fs.tableId),
                            fs.formId);
            getContext().getContentResolver().notifyChange(formUri, null);
            Uri idUri = Uri.withAppendedPath(
                    Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), pf.appName), id);
            getContext().getContentResolver().notifyChange(idUri, null);
        } else {
            ++failureCount;
        }
    }
    getContext().getContentResolver().notifyChange(uri, null);

    int count = directories.size();
    if (failureCount != 0) {
        throw new SQLiteException(
                "Unable to delete all forms (" + (count - failureCount) + " of " + count + " deleted)");
    }
    return count;
}

From source file:com.ichi2.anki.provider.CardContentProvider.java

private long getModelIdFromUri(Uri uri, Collection col) {
    String modelIdSegment = uri.getPathSegments().get(1);
    long id;/*  w w w  .j a  v a2  s .  c o  m*/
    if (modelIdSegment.equals(FlashCardsContract.Model.CURRENT_MODEL_ID)) {
        id = col.getModels().current().optLong("id", -1);
    } else {
        try {
            id = Long.parseLong(uri.getPathSegments().get(1));
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException(
                    "Model ID must be either numeric or the String CURRENT_MODEL_ID");
        }
    }
    return id;
}