Example usage for android.database.sqlite SQLiteDatabase setTransactionSuccessful

List of usage examples for android.database.sqlite SQLiteDatabase setTransactionSuccessful

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteDatabase setTransactionSuccessful.

Prototype

public void setTransactionSuccessful() 

Source Link

Document

Marks the current transaction as successful.

Usage

From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java

/**
 * Call this when the schema on the server has changed w.r.t. the schema on
 * the device. In this case, we do not know whether the rows on the device
 * match those on the server./* www.  j  a v a  2s.  c  o  m*/
 *
 * <ul>
 * <li>Reset all 'in_conflict' rows to their original local state (changed or
 * deleted).</li>
 * <li>Leave all 'deleted' rows in 'deleted' state.</li>
 * <li>Leave all 'changed' rows in 'changed' state.</li>
 * <li>Reset all 'synced' rows to 'new_row' to ensure they are sync'd to the
 * server.</li>
 * <li>Reset all 'synced_pending_files' rows to 'new_row' to ensure they are
 * sync'd to the server.</li>
 * </ul>
 * 
 * @param db
 * @param tableId
 */
public void changeDataRowsToNewRowState(SQLiteDatabase db, String tableId) {

    StringBuilder b = new StringBuilder();

    // remove server conflicting rows
    b.setLength(0);
    b.append("DELETE FROM \"").append(tableId).append("\" WHERE ").append(DataTableColumns.SYNC_STATE)
            .append(" =? AND ").append(DataTableColumns.CONFLICT_TYPE).append(" IN (?, ?)");

    String sqlConflictingServer = b.toString();
    //@formatter:off
    String argsConflictingServer[] = { SyncState.in_conflict.name(),
            Integer.toString(ConflictType.SERVER_DELETED_OLD_VALUES),
            Integer.toString(ConflictType.SERVER_UPDATED_UPDATED_VALUES) };
    //@formatter:on

    // update local delete conflicts to deletes
    b.setLength(0);
    //@formatter:off
    b.append("UPDATE \"").append(tableId).append("\" SET ").append(DataTableColumns.SYNC_STATE).append(" =?, ")
            .append(DataTableColumns.CONFLICT_TYPE).append(" = null WHERE ")
            .append(DataTableColumns.CONFLICT_TYPE).append(" = ?");
    //@formatter:on

    String sqlConflictingLocalDeleting = b.toString();
    //@formatter:off
    String argsConflictingLocalDeleting[] = { SyncState.deleted.name(),
            Integer.toString(ConflictType.LOCAL_DELETED_OLD_VALUES) };
    //@formatter:on

    // update local update conflicts to updates
    String sqlConflictingLocalUpdating = sqlConflictingLocalDeleting;
    //@formatter:off
    String argsConflictingLocalUpdating[] = { SyncState.changed.name(),
            Integer.toString(ConflictType.LOCAL_UPDATED_UPDATED_VALUES) };
    //@formatter:on

    // reset all 'rest' rows to 'insert'
    b.setLength(0);
    //@formatter:off
    b.append("UPDATE \"").append(tableId).append("\" SET ").append(DataTableColumns.SYNC_STATE)
            .append(" =? WHERE ").append(DataTableColumns.SYNC_STATE).append(" =?");
    //@formatter:on

    String sqlRest = b.toString();
    //@formatter:off
    String argsRest[] = { SyncState.new_row.name(), SyncState.synced.name() };
    //@formatter:on

    String sqlRestPendingFiles = sqlRest;
    //@formatter:off
    String argsRestPendingFiles[] = { SyncState.new_row.name(), SyncState.synced_pending_files.name() };
    //@formatter:on

    boolean dbWithinTransaction = db.inTransaction();
    try {
        if (!dbWithinTransaction) {
            db.beginTransaction();
        }

        db.execSQL(sqlConflictingServer, argsConflictingServer);
        db.execSQL(sqlConflictingLocalDeleting, argsConflictingLocalDeleting);
        db.execSQL(sqlConflictingLocalUpdating, argsConflictingLocalUpdating);
        db.execSQL(sqlRest, argsRest);
        db.execSQL(sqlRestPendingFiles, argsRestPendingFiles);

        if (!dbWithinTransaction) {
            db.setTransactionSuccessful();
        }
    } finally {
        if (!dbWithinTransaction) {
            db.endTransaction();
        }
    }
}

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

@Override
public void onCreate(SQLiteDatabase db) {
    db.beginTransaction();//from  w w w . jav a2  s  . co m

    createTable(db, MyInfo.TABLE, null, MyInfo._ID, "INTEGER PRIMARY KEY", MyInfo.PUBLIC_KEY, "TEXT",
            MyInfo.PRIVATE_KEY, "TEXT", MyInfo.NAME, "TEXT", MyInfo.EMAIL, "TEXT", MyInfo.PICTURE, "BLOB",
            MyInfo.ABOUT, "TEXT DEFAULT ''");

    createTable(db, DbObject.TABLE, null, DbObject._ID, "INTEGER PRIMARY KEY", DbObject.TYPE, "TEXT",
            DbObject.SEQUENCE_ID, "INTEGER", DbObject.FEED_NAME, "TEXT", DbObject.APP_ID, "TEXT",
            DbObject.CONTACT_ID, "INTEGER", DbObject.DESTINATION, "TEXT", DbObject.JSON, "TEXT",
            DbObject.TIMESTAMP, "INTEGER", DbObject.LAST_MODIFIED_TIMESTAMP, "INTEGER", DbObject.SENT,
            "INTEGER DEFAULT 0", DbObject.DELETED, "INTEGER DEFAULT 0", DbObject.HASH, "INTEGER",
            DbObject.ENCODED, "BLOB", DbObject.CHILD_FEED_NAME, "TEXT", DbObject.RAW, "BLOB", DbObject.KEY_INT,
            "INTEGER");
    db.execSQL("CREATE INDEX objects_by_sequence_id ON " + DbObject.TABLE + "(" + DbObject.CONTACT_ID + ", "
            + DbObject.FEED_NAME + ", " + DbObject.SEQUENCE_ID + ")");
    createIndex(db, "INDEX", "objects_by_feed_name", DbObject.TABLE, DbObject.FEED_NAME);
    db.execSQL("CREATE INDEX objects_by_creator_id ON " + DbObject.TABLE + "(" + DbObject.CONTACT_ID + ", "
            + DbObject.SENT + ")");
    createIndex(db, "INDEX", "child_feeds", DbObject.TABLE, DbObject.CHILD_FEED_NAME);
    createIndex(db, "INDEX", "objects_by_hash", DbObject.TABLE, DbObject.HASH);
    createIndex(db, "INDEX", "objects_by_int_key", DbObject.TABLE, DbObject.KEY_INT);
    createIndex(db, "INDEX", "objects_last_modified", DbObject.TABLE, DbObject.LAST_MODIFIED_TIMESTAMP);

    createTable(db, Contact.TABLE, null, Contact._ID, "INTEGER PRIMARY KEY", Contact.NAME, "TEXT",
            Contact.PUBLIC_KEY, "TEXT", Contact.PUBLIC_KEY_HASH_64, "INTEGER", Contact.SHARED_SECRET, "BLOB",
            Contact.PERSON_ID, "TEXT", Contact.EMAIL, "TEXT", Contact.PRESENCE,
            "INTEGER DEFAULT " + Presence.AVAILABLE, Contact.LAST_PRESENCE_TIME, "INTEGER DEFAULT 0",
            Contact.LAST_OBJECT_ID, "INTEGER", Contact.LAST_UPDATED, "INTEGER", Contact.NUM_UNREAD,
            "INTEGER DEFAULT 0", Contact.NEARBY, "INTEGER DEFAULT 0", Contact.STATUS, "TEXT", Contact.PICTURE,
            "BLOB", Contact.HIDDEN, "INTEGER DEFAULT 0");
    createIndex(db, "UNIQUE INDEX", "contacts_by_person_id", Contact.TABLE, Contact.PERSON_ID);
    createIndex(db, "INDEX", "contacts_by_pkp", Contact.TABLE, Contact.PUBLIC_KEY_HASH_64);

    createTable(db, Subscriber.TABLE, new String[] { Subscriber.CONTACT_ID, Subscriber.FEED_NAME },
            Subscriber._ID, "INTEGER PRIMARY KEY", Subscriber.CONTACT_ID,
            "INTEGER REFERENCES " + Contact.TABLE + "(" + Contact._ID + ") ON DELETE CASCADE",
            Subscriber.FEED_NAME, "TEXT");
    createIndex(db, "INDEX", "subscribers_by_contact_id", Subscriber.TABLE, Subscriber.CONTACT_ID);

    createGroupBaseTable(db);
    createGroupMemberBaseTable(db);
    createRelationBaseTable(db);
    addRelationIndexes(db);
    createUserAttributesTable(db);
    generateAndStorePersonalInfo(db);

    db.setVersion(VERSION);
    db.setTransactionSuccessful();
    db.endTransaction();
    this.onOpen(db);
    //}
}

From source file:it.bradipao.berengar.DbTool.java

public static int gson2db(SQLiteDatabase mDB, File jsonFile) {

    // vars//from   w  w w .j a va 2 s  . co  m
    int iTableNum = 0;
    FileReader fr = null;
    BufferedReader br = null;
    JsonReader jr = null;
    String name = null;
    String val = null;

    String mTable = null;
    String mTableSql = null;
    ArrayList<String> aFields = null;
    ArrayList<String> aValues = null;
    ContentValues cv = null;

    // file readers
    try {
        fr = new FileReader(jsonFile);
        br = new BufferedReader(fr);
        jr = new JsonReader(br);
    } catch (FileNotFoundException e) {
        Log.e(LOGTAG, "error in gson2db file readers", e);
    }

    // parsing
    try {
        // start database transaction
        mDB.beginTransaction();
        // open root {
        jr.beginObject();
        // iterate through root objects
        while (jr.hasNext()) {
            name = jr.nextName();
            if (jr.peek() == JsonToken.NULL)
                jr.skipValue();
            // number of tables
            else if (name.equals("tables_num")) {
                val = jr.nextString();
                iTableNum = Integer.parseInt(val);
                if (GOLOG)
                    Log.d(LOGTAG, "TABLE NUM : " + iTableNum);
            }
            // iterate through tables array
            else if (name.equals("tables")) {
                jr.beginArray();
                while (jr.hasNext()) {
                    // start table
                    mTable = null;
                    aFields = null;
                    jr.beginObject();
                    while (jr.hasNext()) {
                        name = jr.nextName();
                        if (jr.peek() == JsonToken.NULL)
                            jr.skipValue();
                        // table name
                        else if (name.equals("table_name")) {
                            mTable = jr.nextString();
                        }
                        // table sql
                        else if (name.equals("table_sql")) {
                            mTableSql = jr.nextString();
                            if ((mTable != null) && (mTableSql != null)) {
                                mDB.execSQL("DROP TABLE IF EXISTS " + mTable);
                                mDB.execSQL(mTableSql);
                                if (GOLOG)
                                    Log.d(LOGTAG, "DROPPED AND CREATED TABLE : " + mTable);
                            }
                        }
                        // iterate through columns name
                        else if (name.equals("cols_name")) {
                            jr.beginArray();
                            while (jr.hasNext()) {
                                val = jr.nextString();
                                if (aFields == null)
                                    aFields = new ArrayList<String>();
                                aFields.add(val);
                            }
                            jr.endArray();
                            if (GOLOG)
                                Log.d(LOGTAG, "COLUMN NAME : " + aFields.toString());
                        }
                        // iterate through rows
                        else if (name.equals("rows")) {
                            jr.beginArray();
                            while (jr.hasNext()) {
                                jr.beginArray();
                                // iterate through values in row
                                aValues = null;
                                cv = null;
                                while (jr.hasNext()) {
                                    val = jr.nextString();
                                    if (aValues == null)
                                        aValues = new ArrayList<String>();
                                    aValues.add(val);
                                }
                                jr.endArray();
                                // add to database
                                cv = new ContentValues();
                                for (int j = 0; j < aFields.size(); j++)
                                    cv.put(aFields.get(j), aValues.get(j));
                                mDB.insert(mTable, null, cv);
                                if (GOLOG)
                                    Log.d(LOGTAG, "INSERT IN " + mTable + " : " + aValues.toString());
                            }
                            jr.endArray();
                        } else
                            jr.skipValue();
                    }
                    // end table
                    jr.endObject();
                }
                jr.endArray();
            } else
                jr.skipValue();
        }
        // close root }
        jr.endObject();
        jr.close();
        // successfull transaction
        mDB.setTransactionSuccessful();
    } catch (IOException e) {
        Log.e(LOGTAG, "error in gson2db gson parsing", e);
    } finally {
        mDB.endTransaction();
    }

    return iTableNum;
}

From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java

/**
 * Clean up the KVS row data types. This simplifies the migration process by
 * enforcing the proper data types regardless of what the values are in the
 * imported CSV files./*ww w .  j  a v a  2  s .  c  o  m*/
 * 
 * @param db
 * @param tableId
 */
public void enforceTypesDBTableMetadata(SQLiteDatabase db, String tableId) {

    boolean dbWithinTransaction = db.inTransaction();
    try {
        if (!dbWithinTransaction) {
            db.beginTransaction();
        }

        StringBuilder b = new StringBuilder();
        b.setLength(0);
        //@formatter:off
        b.append("UPDATE \"").append(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME).append("\" SET ")
                .append(KeyValueStoreColumns.VALUE_TYPE).append("=? WHERE ")
                .append(KeyValueStoreColumns.PARTITION).append("=? AND ").append(KeyValueStoreColumns.KEY)
                .append("=?");
        //@formatter:on

        String sql = b.toString();
        String[] fields = new String[3];

        // for columns

        fields[0] = ElementDataType.array.name();
        fields[1] = KeyValueStoreConstants.PARTITION_COLUMN;
        fields[2] = KeyValueStoreConstants.COLUMN_DISPLAY_CHOICES_LIST;
        db.execSQL(sql, fields);

        fields[0] = ElementDataType.string.name();
        fields[1] = KeyValueStoreConstants.PARTITION_COLUMN;
        fields[2] = KeyValueStoreConstants.COLUMN_DISPLAY_FORMAT;
        db.execSQL(sql, fields);

        fields[0] = ElementDataType.object.name();
        fields[1] = KeyValueStoreConstants.PARTITION_COLUMN;
        fields[2] = KeyValueStoreConstants.COLUMN_DISPLAY_NAME;
        db.execSQL(sql, fields);

        fields[0] = ElementDataType.bool.name();
        fields[1] = KeyValueStoreConstants.PARTITION_COLUMN;
        fields[2] = KeyValueStoreConstants.COLUMN_DISPLAY_VISIBLE;
        db.execSQL(sql, fields);

        fields[0] = ElementDataType.array.name();
        fields[1] = KeyValueStoreConstants.PARTITION_COLUMN;
        fields[2] = KeyValueStoreConstants.COLUMN_JOINS;
        db.execSQL(sql, fields);

        // and for the table...

        fields[0] = ElementDataType.array.name();
        fields[1] = KeyValueStoreConstants.PARTITION_TABLE;
        fields[2] = KeyValueStoreConstants.TABLE_COL_ORDER;
        db.execSQL(sql, fields);

        fields[0] = ElementDataType.object.name();
        fields[1] = KeyValueStoreConstants.PARTITION_TABLE;
        fields[2] = KeyValueStoreConstants.TABLE_DISPLAY_NAME;
        db.execSQL(sql, fields);

        fields[0] = ElementDataType.array.name();
        fields[1] = KeyValueStoreConstants.PARTITION_TABLE;
        fields[2] = KeyValueStoreConstants.TABLE_GROUP_BY_COLS;
        db.execSQL(sql, fields);

        fields[0] = ElementDataType.string.name();
        fields[1] = KeyValueStoreConstants.PARTITION_TABLE;
        fields[2] = KeyValueStoreConstants.TABLE_INDEX_COL;
        db.execSQL(sql, fields);

        fields[0] = ElementDataType.object.name();
        fields[1] = KeyValueStoreConstants.PARTITION_TABLE;
        fields[2] = KeyValueStoreConstants.TABLE_SORT_COL;
        db.execSQL(sql, fields);

        fields[0] = ElementDataType.object.name();
        fields[1] = KeyValueStoreConstants.PARTITION_TABLE;
        fields[2] = KeyValueStoreConstants.TABLE_SORT_ORDER;
        db.execSQL(sql, fields);

        // TODO: color rule groups

        if (!dbWithinTransaction) {
            db.setTransactionSuccessful();
        }
    } finally {
        if (!dbWithinTransaction) {
            db.endTransaction();
        }
    }
}

From source file:com.wheelermarine.android.publicAccesses.Updater.java

@Override
protected Integer doInBackground(URL... urls) {

    try {/*from w  ww  .j a va2  s  .com*/
        final DatabaseHelper db = new DatabaseHelper(context);

        SQLiteDatabase database = db.getWritableDatabase();
        if (database == null)
            throw new IllegalStateException("Unable to open database!");

        database.beginTransaction();
        try {
            // Clear out the old data.
            database.delete(DatabaseHelper.PublicAccessEntry.TABLE_NAME, null, null);

            // Connect to the web server and locate the FTP download link.
            Log.v(TAG, "Finding update: " + urls[0]);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progress.setMessage("Locating update...");
                    progress.setIndeterminate(true);
                }
            });
            Document doc = Jsoup.connect(urls[0].toString()).timeout(timeout * 1000).userAgent(userAgent).get();
            URL dataURL = null;
            for (Element element : doc.select("a")) {
                if (element.hasAttr("href") && element.attr("href").startsWith("ftp://ftp.dnr.state.mn.us")) {
                    dataURL = new URL(element.attr("href"));
                }
            }

            // Make sure the download URL was fund.
            if (dataURL == null)
                throw new FileNotFoundException("Unable to locate data URL.");

            // Connect to the FTP server and download the update.
            Log.v(TAG, "Downloading update: " + dataURL);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progress.setMessage("Downloading update...");
                    progress.setIndeterminate(true);
                }
            });
            FTPClient ftp = new FTPClient();
            try {
                ftp.setConnectTimeout(timeout * 1000);
                ftp.setDefaultTimeout(timeout * 1000);
                ftp.connect(dataURL.getHost());
                ftp.enterLocalPassiveMode();

                // After connection attempt, you should check the reply code
                // to verify success.
                if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                    ftp.disconnect();
                    throw new IOException("FTP server refused connection: " + ftp.getReplyString());
                }

                // Login using the standard anonymous credentials.
                if (!ftp.login("anonymous", "anonymous")) {
                    ftp.disconnect();
                    throw new IOException("FTP Error: " + ftp.getReplyString());
                }

                Map<Integer, Location> locations = null;

                // Download the ZIP archive.
                Log.v(TAG, "Downloading: " + dataURL.getFile());
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
                InputStream in = ftp.retrieveFileStream(dataURL.getFile());
                if (in == null)
                    throw new FileNotFoundException(dataURL.getFile() + " was not found!");
                try {
                    ZipInputStream zin = new ZipInputStream(in);
                    try {
                        // Locate the .dbf entry in the ZIP archive.
                        ZipEntry entry;
                        while ((entry = zin.getNextEntry()) != null) {
                            if (entry.getName().endsWith(entryName)) {
                                readDBaseFile(zin, database);
                            } else if (entry.getName().endsWith(shapeEntryName)) {
                                locations = readShapeFile(zin);
                            }
                        }
                    } finally {
                        try {
                            zin.close();
                        } catch (Exception e) {
                            // Ignore this error.
                        }
                    }
                } finally {
                    in.close();
                }

                if (locations != null) {
                    final int recordCount = locations.size();
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progress.setIndeterminate(false);
                            progress.setMessage("Updating locations...");
                            progress.setMax(recordCount);
                        }
                    });

                    int progress = 0;
                    for (int recordNumber : locations.keySet()) {
                        PublicAccess access = db.getPublicAccessByRecordNumber(recordNumber);
                        Location loc = locations.get(recordNumber);
                        access.setLatitude(loc.getLatitude());
                        access.setLongitude(loc.getLongitude());
                        db.updatePublicAccess(access);
                        publishProgress(++progress);
                    }
                }
            } finally {
                if (ftp.isConnected())
                    ftp.disconnect();
            }
            database.setTransactionSuccessful();
            return db.getPublicAccessesCount();
        } finally {
            database.endTransaction();
        }
    } catch (Exception e) {
        error = e;
        Log.e(TAG, "Error loading data: " + e.getLocalizedMessage(), e);
        return -1;
    }
}

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

/**
 * Inserts a message locally that has been received from some agent,
 * typically from a remote device.// w w  w .j  a  va2 s.  com
 */
@Override
public Uri insert(Uri uri, ContentValues values) {
    ContentResolver resolver = getContext().getContentResolver();
    if (DBG)
        Log.i(TAG, "Inserting at uri: " + uri + ", " + values);

    final String appId = getCallingActivityId();
    if (appId == null) {
        Log.d(TAG, "No AppId for calling activity. Ignoring query.");
        return null;
    }

    List<String> segs = uri.getPathSegments();
    if (match(uri, "feeds", "me")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }

        long objId = mHelper.addToFeed(appId, "friend", values);
        Uri objUri = DbObject.uriForObj(objId);
        resolver.notifyChange(Feed.uriForName("me"), null);
        resolver.notifyChange(Feed.uriForName("friend"), null);
        resolver.notifyChange(objUri, null);
        return objUri;
    } else if (match(uri, "feeds", ".+")) {
        String feedName = segs.get(1);
        String type = values.getAsString(DbObject.TYPE);
        try {
            JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
            String objHash = null;
            if (feedName.contains(":")) {
                String[] parts = feedName.split(":");
                feedName = parts[0];
                objHash = parts[1];
            }
            if (objHash != null) {
                json.put(DbObjects.TARGET_HASH, Long.parseLong(objHash));
                json.put(DbObjects.TARGET_RELATION, DbRelation.RELATION_PARENT);
                values.put(DbObject.JSON, json.toString());
            }

            String appAuthority = appId;
            if (SUPER_APP_ID.equals(appId)) {
                if (AppObj.TYPE.equals(type)) {
                    if (json.has(AppObj.ANDROID_PACKAGE_NAME)) {
                        appAuthority = json.getString(AppObj.ANDROID_PACKAGE_NAME);
                    }
                }
            }

            long objId = mHelper.addToFeed(appAuthority, feedName, values);
            Uri objUri = DbObject.uriForObj(objId);
            resolver.notifyChange(objUri, null);
            notifyDependencies(mHelper, resolver, segs.get(1));
            if (DBG)
                Log.d(TAG, "just inserted " + values.getAsString(DbObject.JSON));
            return objUri;
        } catch (JSONException e) {
            return null;
        }
    } else if (match(uri, "out")) {
        try {
            JSONObject obj = new JSONObject(values.getAsString("json"));
            long objId = mHelper.addToOutgoing(appId, values.getAsString(DbObject.DESTINATION),
                    values.getAsString(DbObject.TYPE), obj);
            resolver.notifyChange(Uri.parse(CONTENT_URI + "/out"), null);
            return DbObject.uriForObj(objId);
        } catch (JSONException e) {
            return null;
        }
    } else if (match(uri, "contacts")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        long id = mHelper.insertContact(values);
        resolver.notifyChange(Uri.parse(CONTENT_URI + "/contacts"), null);
        return uriWithId(uri, id);
    } else if (match(uri, "subscribers")) {
        // Question: Should this be restricted?
        // if(!appId.equals(SUPER_APP_ID)) return null;
        long id = mHelper.insertSubscriber(values);
        resolver.notifyChange(Uri.parse(CONTENT_URI + "/subscribers"), null);
        return uriWithId(uri, id);
    } else if (match(uri, "groups")) {
        if (!appId.equals(SUPER_APP_ID))
            return null;
        long id = mHelper.insertGroup(values);
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/groups"), null);
        return uriWithId(uri, id);
    } else if (match(uri, "group_members")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        long id = mHelper.insertGroupMember(values);
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_members"), null);
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_contacts"), null);
        return uriWithId(uri, id);
    }

    else if (match(uri, "group_invitations")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        String groupName = values.getAsString(InviteToGroupObj.GROUP_NAME);
        Uri dynUpdateUri = Uri.parse(values.getAsString(InviteToGroupObj.DYN_UPDATE_URI));
        long gid = values.getAsLong("groupId");
        SQLiteDatabase db = mHelper.getWritableDatabase();
        mHelper.addToOutgoing(db, appId, values.getAsString(InviteToGroupObj.PARTICIPANTS),
                InviteToGroupObj.TYPE, InviteToGroupObj.json(groupName, dynUpdateUri));
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/out"), null);
        return uriWithId(uri, gid);
    }

    else if (match(uri, "dynamic_groups")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        Uri gUri = Uri.parse(values.getAsString("uri"));
        GroupProviders.GroupProvider gp = GroupProviders.forUri(gUri);
        String feedName = gp.feedName(gUri);
        Maybe<Group> mg = mHelper.groupByFeedName(feedName);
        long id = -1;
        try {
            Group g = mg.get();
            id = g.id;
        } catch (Maybe.NoValError e) {
            ContentValues cv = new ContentValues();
            cv.put(Group.NAME, gp.groupName(gUri));
            cv.put(Group.FEED_NAME, feedName);
            cv.put(Group.DYN_UPDATE_URI, gUri.toString());

            String table = DbObject.TABLE;
            String[] columns = new String[] { DbObject.FEED_NAME };
            String selection = DbObject.CHILD_FEED_NAME + " = ?";
            String[] selectionArgs = new String[] { feedName };
            Cursor parent = mHelper.getReadableDatabase().query(table, columns, selection, selectionArgs, null,
                    null, null);
            try {
                if (parent.moveToFirst()) {
                    String parentName = parent.getString(0);
                    table = Group.TABLE;
                    columns = new String[] { Group._ID };
                    selection = Group.FEED_NAME + " = ?";
                    selectionArgs = new String[] { parentName };

                    Cursor parent2 = mHelper.getReadableDatabase().query(table, columns, selection,
                            selectionArgs, null, null, null);
                    try {
                        if (parent2.moveToFirst()) {
                            cv.put(Group.PARENT_FEED_ID, parent2.getLong(0));
                        } else {
                            Log.e(TAG, "Parent feed found but no id for " + parentName);
                        }
                    } finally {
                        parent2.close();
                    }
                } else {
                    Log.w(TAG, "No parent feed for " + feedName);
                }
            } finally {
                parent.close();
            }
            id = mHelper.insertGroup(cv);
            getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/dynamic_groups"), null);
            getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/groups"), null);
        }
        return uriWithId(uri, id);
    }

    else if (match(uri, "dynamic_group_member")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        SQLiteDatabase db = mHelper.getWritableDatabase();
        db.beginTransaction();
        try {
            ContentValues cv = new ContentValues();
            String pubKeyStr = values.getAsString(Contact.PUBLIC_KEY);
            RSAPublicKey k = RSACrypto.publicKeyFromString(pubKeyStr);
            String personId = mIdent.personIdForPublicKey(k);
            if (!personId.equals(mIdent.userPersonId())) {
                cv.put(Contact.PUBLIC_KEY, values.getAsString(Contact.PUBLIC_KEY));
                cv.put(Contact.NAME, values.getAsString(Contact.NAME));
                cv.put(Contact.EMAIL, values.getAsString(Contact.EMAIL));
                if (values.getAsString(Contact.PICTURE) != null) {
                    cv.put(Contact.PICTURE, values.getAsByteArray(Contact.PICTURE));
                }

                long cid = -1;
                Contact contact = mHelper.contactForPersonId(personId).otherwise(Contact.NA());
                if (contact.id > -1) {
                    cid = contact.id;
                } else {
                    cid = mHelper.insertContact(db, cv);
                }

                if (cid > -1) {

                    ContentValues gv = new ContentValues();
                    gv.put(GroupMember.GLOBAL_CONTACT_ID, values.getAsString(GroupMember.GLOBAL_CONTACT_ID));
                    gv.put(GroupMember.GROUP_ID, values.getAsLong(GroupMember.GROUP_ID));
                    gv.put(GroupMember.CONTACT_ID, cid);
                    mHelper.insertGroupMember(db, gv);
                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_members"),
                            null);
                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/contacts"), null);
                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_contacts"),
                            null);

                    // Add subscription to this private group feed
                    ContentValues sv = new ContentValues();
                    sv = new ContentValues();
                    sv.put(Subscriber.CONTACT_ID, cid);
                    sv.put(Subscriber.FEED_NAME, values.getAsString(Group.FEED_NAME));
                    mHelper.insertSubscriber(db, sv);

                    ContentValues xv = new ContentValues();
                    xv.put(Subscriber.CONTACT_ID, cid);
                    xv.put(Subscriber.FEED_NAME, "friend");
                    mHelper.insertSubscriber(db, xv);

                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/subscribers"),
                            null);

                    db.setTransactionSuccessful();
                }
                return uriWithId(uri, cid);
            } else {
                Log.i(TAG, "Omitting self.");
                return uriWithId(uri, Contact.MY_ID);
            }
        } finally {
            db.endTransaction();
        }
    } else {
        Log.e(TAG, "Failed to insert into " + uri);
        return null;
    }
}

From source file:org.opendatakit.sync.ProcessRowDataChanges.java

private int processRowOutcomes(TableDefinitionEntry te, TableResource resource, TableResult tableResult,
        ArrayList<ColumnDefinition> orderedColumns, ArrayList<ColumnDefinition> fileAttachmentColumns,
        boolean hasAttachments, List<SyncRowPending> rowsToPushFileAttachments, int countSoFar,
        int totalOutcomesSize, List<SyncRow> segmentAlter, ArrayList<RowOutcome> outcomes,
        ArrayList<RowOutcome> specialCases) {

    ArrayList<SyncRowDataChanges> rowsToMoveToInConflictLocally = new ArrayList<SyncRowDataChanges>();

    // For speed, do this all within a transaction. Processing is
    // all in-memory except when we are deleting a client row. In that
    // case, there may be SDCard access to delete the attachments for
    // the client row. But that is local access, and the commit will
    // be accessing the same device.
    ///*from w  w w . j av  a  2 s .c  o m*/
    // i.e., no network access in this code, so we can place it all within
    // a transaction and not lock up the database for very long.
    //

    SQLiteDatabase db = null;

    try {
        db = sc.getDatabase();
        db.beginTransaction();

        for (int i = 0; i < segmentAlter.size(); ++i) {
            RowOutcome r = outcomes.get(i);
            SyncRow syncRow = segmentAlter.get(i);
            if (!r.getRowId().equals(syncRow.getRowId())) {
                throw new IllegalStateException("Unexpected reordering of return");
            }
            if (r.getOutcome() == OutcomeType.SUCCESS) {

                if (r.isDeleted()) {
                    // DELETE
                    // move the local record into the 'new_row' sync state
                    // so it can be physically deleted.
                    ODKDatabaseUtils.get().updateRowETagAndSyncState(db, resource.getTableId(), r.getRowId(),
                            null, SyncState.new_row);
                    // !!Important!! update the rowETag in our copy of this row.
                    syncRow.setRowETag(r.getRowETag());
                    // and physically delete row and attachments from database.
                    ODKDatabaseUtils.get().deleteDataInExistingDBTableWithId(db, sc.getAppName(),
                            resource.getTableId(), r.getRowId());
                    tableResult.incServerDeletes();
                } else {
                    ODKDatabaseUtils.get().updateRowETagAndSyncState(db, resource.getTableId(), r.getRowId(),
                            r.getRowETag(),
                            (hasAttachments && !syncRow.getUriFragments().isEmpty())
                                    ? SyncState.synced_pending_files
                                    : SyncState.synced);
                    // !!Important!! update the rowETag in our copy of this row.
                    syncRow.setRowETag(r.getRowETag());
                    if (hasAttachments && !syncRow.getUriFragments().isEmpty()) {
                        rowsToPushFileAttachments.add(new SyncRowPending(syncRow, false, true, true));
                    }
                    // UPDATE or INSERT
                    tableResult.incServerUpserts();
                }
            } else if (r.getOutcome() == OutcomeType.FAILED) {
                if (r.getRowId() == null || !r.isDeleted()) {
                    // should never occur!!!
                    throw new IllegalStateException(
                            "Unexpected null rowId or OutcomeType.FAILED when not deleting row");
                } else {
                    // special case of a delete where server has no record of the row.
                    // server should add row and mark it as deleted.
                }
            } else if (r.getOutcome() == OutcomeType.IN_CONFLICT) {
                // another device updated this record between the time we fetched
                // changes
                // and the time we tried to update this record. Transition the record
                // locally into the conflicting state.
                // SyncState.deleted and server is not deleting
                // SyncState.new_row and record exists on server
                // SyncState.changed and new change on server
                // SyncState.in_conflict and new change on server

                // no need to worry about server in_conflict records.
                // any server in_conflict rows will be cleaned up during the
                // update of the in_conflict state.
                Integer localRowConflictType = syncRow.isDeleted() ? ConflictType.LOCAL_DELETED_OLD_VALUES
                        : ConflictType.LOCAL_UPDATED_UPDATED_VALUES;

                Integer serverRowConflictType = r.isDeleted() ? ConflictType.SERVER_DELETED_OLD_VALUES
                        : ConflictType.SERVER_UPDATED_UPDATED_VALUES;

                // figure out what the localRow conflict type sh
                SyncRow serverRow = new SyncRow(r.getRowId(), r.getRowETag(), r.isDeleted(), r.getFormId(),
                        r.getLocale(), r.getSavepointType(), r.getSavepointTimestamp(), r.getSavepointCreator(),
                        r.getFilterScope(), r.getValues(), fileAttachmentColumns);
                SyncRowDataChanges conflictRow = new SyncRowDataChanges(serverRow, syncRow, false,
                        localRowConflictType);

                rowsToMoveToInConflictLocally.add(conflictRow);
                // we transition all of these later, outside this processing loop...
            } else if (r.getOutcome() == OutcomeType.DENIED) {
                // user does not have privileges...
                specialCases.add(r);
            } else {
                // a new OutcomeType state was added!
                throw new IllegalStateException("Unexpected OutcomeType! " + r.getOutcome().name());
            }

            ++countSoFar;
            ++rowsProcessed;
            if (rowsProcessed % ROWS_BETWEEN_PROGRESS_UPDATES == 0) {
                sc.updateNotification(SyncProgressState.ROWS, R.string.altering_server_row,
                        new Object[] { resource.getTableId(), countSoFar, totalOutcomesSize },
                        10.0 + rowsProcessed * perRowIncrement, false);
            }
        }

        // process the conflict rows, if any
        conflictRowsInDb(db, resource, orderedColumns, rowsToMoveToInConflictLocally, rowsToPushFileAttachments,
                hasAttachments, tableResult);

        // and allow this to happen
        db.setTransactionSuccessful();
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
            db = null;
        }
    }

    return countSoFar;
}

From source file:pl.selvin.android.syncframework.content.BaseContentProvider.java

protected boolean Sync(String service, String scope, String params) {
    final Date start = new Date();
    boolean hasError = false;
    if (params == null)
        params = "";
    final SQLiteDatabase db = mDB.getWritableDatabase();
    final ArrayList<TableInfo> notifyTableInfo = new ArrayList<TableInfo>();

    final String download = String.format(contentHelper.DOWNLOAD_SERVICE_URI, service, scope, params);
    final String upload = String.format(contentHelper.UPLOAD_SERVICE_URI, service, scope, params);
    final String scopeServerBlob = String.format("%s.%s.%s", service, scope, _.serverBlob);
    String serverBlob = null;/*from   w  w w  .  ja  v a2 s  .  c  o  m*/
    Cursor cur = db.query(BlobsTable.NAME, new String[] { BlobsTable.C_VALUE }, BlobsTable.C_NAME + "=?",
            new String[] { scopeServerBlob }, null, null, null);
    final String originalBlob;
    if (cur.moveToFirst()) {
        originalBlob = serverBlob = cur.getString(0);
    } else {
        originalBlob = null;
    }
    cur.close();
    db.beginTransaction();
    try {
        boolean nochanges = false;
        if (serverBlob != null) {
            nochanges = !contentHelper.hasDirtTable(db, scope);
        }
        boolean resolve = false;
        final Metadata meta = new Metadata();
        final HashMap<String, Object> vals = new HashMap<String, Object>();
        final ContentValues cv = new ContentValues(2);
        JsonFactory jsonFactory = new JsonFactory();
        JsonToken current = null;
        String name = null;
        boolean moreChanges = false;
        boolean forceMoreChanges = false;
        do {
            final int requestMethod;
            final String serviceRequestUrl;
            final ContentProducer contentProducer;

            if (serverBlob != null) {
                requestMethod = HTTP_POST;
                if (nochanges) {
                    serviceRequestUrl = download;
                } else {
                    serviceRequestUrl = upload;
                    forceMoreChanges = true;
                }
                contentProducer = new SyncContentProducer(jsonFactory, db, scope, serverBlob, !nochanges,
                        notifyTableInfo, contentHelper);
                nochanges = true;
            } else {
                requestMethod = HTTP_GET;
                serviceRequestUrl = download;
                contentProducer = null;

            }
            if (moreChanges) {
                db.beginTransaction();
            }

            Result result = executeRequest(requestMethod, serviceRequestUrl, contentProducer);
            if (result.getStatus() == HttpStatus.SC_OK) {
                final JsonParser jp = jsonFactory.createParser(result.getInputStream());

                jp.nextToken(); // skip ("START_OBJECT(d) expected");
                jp.nextToken(); // skip ("FIELD_NAME(d) expected");
                if (jp.nextToken() != JsonToken.START_OBJECT)
                    throw new Exception("START_OBJECT(d - object) expected");
                while (jp.nextToken() != JsonToken.END_OBJECT) {
                    name = jp.getCurrentName();
                    if (_.__sync.equals(name)) {
                        current = jp.nextToken();
                        while (jp.nextToken() != JsonToken.END_OBJECT) {
                            name = jp.getCurrentName();
                            current = jp.nextToken();
                            if (_.serverBlob.equals(name)) {
                                serverBlob = jp.getText();
                            } else if (_.moreChangesAvailable.equals(name)) {
                                moreChanges = jp.getBooleanValue() || forceMoreChanges;
                                forceMoreChanges = false;
                            } else if (_.resolveConflicts.equals(name)) {
                                resolve = jp.getBooleanValue();
                            }
                        }
                    } else if (_.results.equals(name)) {
                        if (jp.nextToken() != JsonToken.START_ARRAY)
                            throw new Exception("START_ARRAY(results) expected");
                        while (jp.nextToken() != JsonToken.END_ARRAY) {
                            meta.isDeleted = false;
                            meta.tempId = null;
                            vals.clear();
                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                name = jp.getCurrentName();
                                current = jp.nextToken();
                                if (current == JsonToken.VALUE_STRING) {
                                    vals.put(name, jp.getText());
                                } else if (current == JsonToken.VALUE_NUMBER_INT) {
                                    vals.put(name, jp.getLongValue());
                                } else if (current == JsonToken.VALUE_NUMBER_FLOAT) {
                                    vals.put(name, jp.getDoubleValue());
                                } else if (current == JsonToken.VALUE_FALSE) {
                                    vals.put(name, 0L);
                                } else if (current == JsonToken.VALUE_TRUE) {
                                    vals.put(name, 1L);
                                } else if (current == JsonToken.VALUE_NULL) {
                                    vals.put(name, null);
                                } else {
                                    if (current == JsonToken.START_OBJECT) {
                                        if (_.__metadata.equals(name)) {
                                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                name = jp.getCurrentName();
                                                jp.nextToken();
                                                if (_.uri.equals(name)) {
                                                    meta.uri = jp.getText();
                                                } else if (_.type.equals(name)) {
                                                    meta.type = jp.getText();
                                                } else if (_.isDeleted.equals(name)) {
                                                    meta.isDeleted = jp.getBooleanValue();
                                                } else if (_.tempId.equals(name)) {
                                                    meta.tempId = jp.getText();
                                                }
                                            }
                                        } else if (_.__syncConflict.equals(name)) {
                                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                name = jp.getCurrentName();
                                                jp.nextToken();
                                                if (_.isResolved.equals(name)) {
                                                } else if (_.conflictResolution.equals(name)) {
                                                } else if (_.conflictingChange.equals(name)) {
                                                    while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                        name = jp.getCurrentName();
                                                        current = jp.nextToken();
                                                        if (current == JsonToken.START_OBJECT) {
                                                            if (_.__metadata.equals(name)) {
                                                                while (jp.nextToken() != JsonToken.END_OBJECT) {

                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            // resolve conf

                                        } else if (_.__syncError.equals(name)) {
                                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                name = jp.getCurrentName();
                                                jp.nextToken();
                                            }
                                        }
                                    }
                                }
                            }
                            TableInfo tab = contentHelper.getTableFromType(meta.type);
                            if (meta.isDeleted) {
                                tab.DeleteWithUri(meta.uri, db);
                            } else {
                                tab.SyncJSON(vals, meta, db);
                            }
                            if (!notifyTableInfo.contains(tab))
                                notifyTableInfo.add(tab);
                        }
                    }
                }
                jp.close();
                if (!hasError) {
                    cv.clear();
                    cv.put(BlobsTable.C_NAME, scopeServerBlob);
                    cv.put(BlobsTable.C_VALUE, serverBlob);
                    cv.put(BlobsTable.C_DATE, Calendar.getInstance().getTimeInMillis());
                    cv.put(BlobsTable.C_STATE, 0);
                    db.replace(BlobsTable.NAME, null, cv);
                    db.setTransactionSuccessful();
                    db.endTransaction();
                    if (DEBUG) {
                        Log.d(TAG, "CP-Sync: commit changes");
                    }
                    final ContentResolver cr = getContext().getContentResolver();
                    for (TableInfo t : notifyTableInfo) {
                        final Uri nu = contentHelper.getDirUri(t.name, false);
                        cr.notifyChange(nu, null, false);
                        // false - do not force sync cause we are in sync
                        if (DEBUG) {
                            Log.d(TAG, "CP-Sync: notifyChange table: " + t.name + ", uri: " + nu);
                        }

                        for (String n : t.notifyUris) {
                            cr.notifyChange(Uri.parse(n), null, false);
                            if (DEBUG) {
                                Log.d(TAG, "+uri: " + n);
                            }
                        }
                    }
                    notifyTableInfo.clear();
                }
            } else {
                if (DEBUG) {
                    Log.e(TAG, "Server error in fetching remote contacts: " + result.getStatus());
                }
                hasError = true;
                break;
            }
        } while (moreChanges);
    } catch (final ConnectTimeoutException e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, "ConnectTimeoutException", e);
        }
    } catch (final IOException e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
    } catch (final ParseException e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, "ParseException", e);
        }
    } catch (final Exception e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, "ParseException", e);
        }
    }
    if (hasError) {
        db.endTransaction();
        ContentValues cv = new ContentValues();
        cv.put(BlobsTable.C_NAME, scopeServerBlob);
        cv.put(BlobsTable.C_VALUE, originalBlob);
        cv.put(BlobsTable.C_DATE, Calendar.getInstance().getTimeInMillis());
        cv.put(BlobsTable.C_STATE, -1);
        db.replace(BlobsTable.NAME, null, cv);
    }
    /*-if (!hasError) {
    final ContentValues cv = new ContentValues(2);
     cv.put(BlobsTable.C_NAME, scopeServerBlob);
     cv.put(BlobsTable.C_VALUE, serverBlob);
     db.replace(BlobsTable.NAME, null, cv);
     db.setTransactionSuccessful();
    }
    db.endTransaction();
    if (!hasError) {
     for (String t : notifyTableInfo) {
    getContext().getContentResolver().notifyChange(getDirUri(t),
          null);
     }
    }*/
    if (DEBUG) {
        Helpers.LogInfo(start);
    }
    return !hasError;
}

From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java

private void upsertDataIntoExistingDBTable(SQLiteDatabase db, String tableId,
        ArrayList<ColumnDefinition> orderedColumns, ContentValues cvValues, boolean shouldUpdate) {
    String rowId = null;/*www. ja  v a 2  s  .  c  om*/
    String whereClause = null;
    boolean specifiesConflictType = cvValues.containsKey(DataTableColumns.CONFLICT_TYPE);
    boolean nullConflictType = specifiesConflictType && (cvValues.get(DataTableColumns.CONFLICT_TYPE) == null);
    String[] whereArgs = new String[specifiesConflictType ? (1 + (nullConflictType ? 0 : 1)) : 1];
    boolean update = false;

    if (cvValues.size() <= 0) {
        throw new IllegalArgumentException(t + ": No values to add into table " + tableId);
    }

    ContentValues cvDataTableVal = new ContentValues();
    cvDataTableVal.putAll(cvValues);

    if (cvDataTableVal.containsKey(DataTableColumns.ID)) {
        // The user specified a row id; we need to determine whether to
        // insert or update the record, or to reject the action because
        // there are either checkpoint records for this row id, or, if
        // a server conflict is associated with this row, that the
        // _conflict_type to update was not specified.
        //
        // i.e., the tuple (_id, _conflict_type) should be unique. If
        // we find that there are more than 0 or 1 records matching this
        // tuple, then we should reject the update request.
        //
        // TODO: perhaps we want to allow updates to the local conflict
        // row if there are no checkpoints on it? I.e., change the
        // tri-state conflict type to a pair of states (local / remote).
        // and all local changes are flagged local. Remote only exists
        // if the server is in conflict.

        rowId = cvDataTableVal.getAsString(DataTableColumns.ID);
        if (rowId == null) {
            throw new IllegalArgumentException(DataTableColumns.ID + ", if specified, cannot be null");
        }

        if (specifiesConflictType) {
            if (nullConflictType) {
                whereClause = DataTableColumns.ID + " = ?" + " AND " + DataTableColumns.CONFLICT_TYPE
                        + " IS NULL";
                whereArgs[0] = rowId;
            } else {
                whereClause = DataTableColumns.ID + " = ?" + " AND " + DataTableColumns.CONFLICT_TYPE + " = ?";
                whereArgs[0] = rowId;
                whereArgs[1] = cvValues.getAsString(DataTableColumns.CONFLICT_TYPE);
            }
        } else {
            whereClause = DataTableColumns.ID + " = ?";
            whereArgs[0] = rowId;
        }

        String sel = "SELECT * FROM " + tableId + " WHERE " + whereClause;
        String[] selArgs = whereArgs;
        Cursor cursor = rawQuery(db, sel, selArgs);

        // There must be only one row in the db for the update to work
        if (shouldUpdate) {
            if (cursor.getCount() == 1) {
                update = true;
            } else if (cursor.getCount() > 1) {
                throw new IllegalArgumentException(
                        t + ": row id " + rowId + " has more than 1 row in table " + tableId);
            }
        } else {
            if (cursor.getCount() > 0) {
                throw new IllegalArgumentException(
                        t + ": id " + rowId + " is already present in table " + tableId);
            }
        }

    } else {
        rowId = "uuid:" + UUID.randomUUID().toString();
    }

    // TODO: This is broken w.r.t. updates of partial fields
    // TODO: This is broken w.r.t. updates of partial fields
    // TODO: This is broken w.r.t. updates of partial fields
    // TODO: This is broken w.r.t. updates of partial fields

    if (!cvDataTableVal.containsKey(DataTableColumns.ID)) {
        cvDataTableVal.put(DataTableColumns.ID, rowId);
    }

    if (update) {
        if (!cvDataTableVal.containsKey(DataTableColumns.SYNC_STATE)
                || (cvDataTableVal.get(DataTableColumns.SYNC_STATE) == null)) {
            cvDataTableVal.put(DataTableColumns.SYNC_STATE, SyncState.changed.name());
        }

        if (cvDataTableVal.containsKey(DataTableColumns.LOCALE)
                && (cvDataTableVal.get(DataTableColumns.LOCALE) == null)) {
            cvDataTableVal.put(DataTableColumns.LOCALE, DataTableColumns.DEFAULT_LOCALE);
        }

        if (cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TYPE)
                && (cvDataTableVal.get(DataTableColumns.SAVEPOINT_TYPE) == null)) {
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_TYPE, SavepointTypeManipulator.complete());
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TIMESTAMP)
                || cvDataTableVal.get(DataTableColumns.SAVEPOINT_TIMESTAMP) == null) {
            String timeStamp = TableConstants.nanoSecondsFromMillis(System.currentTimeMillis());
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_TIMESTAMP, timeStamp);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_CREATOR)
                || (cvDataTableVal.get(DataTableColumns.SAVEPOINT_CREATOR) == null)) {
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_CREATOR, DataTableColumns.DEFAULT_SAVEPOINT_CREATOR);
        }
    } else {

        if (!cvDataTableVal.containsKey(DataTableColumns.ROW_ETAG)
                || cvDataTableVal.get(DataTableColumns.ROW_ETAG) == null) {
            cvDataTableVal.put(DataTableColumns.ROW_ETAG, DataTableColumns.DEFAULT_ROW_ETAG);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SYNC_STATE)
                || (cvDataTableVal.get(DataTableColumns.SYNC_STATE) == null)) {
            cvDataTableVal.put(DataTableColumns.SYNC_STATE, SyncState.new_row.name());
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.CONFLICT_TYPE)) {
            cvDataTableVal.putNull(DataTableColumns.CONFLICT_TYPE);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.FILTER_TYPE)
                || (cvDataTableVal.get(DataTableColumns.FILTER_TYPE) == null)) {
            cvDataTableVal.put(DataTableColumns.FILTER_TYPE, DataTableColumns.DEFAULT_FILTER_TYPE);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.FILTER_VALUE)
                || (cvDataTableVal.get(DataTableColumns.FILTER_VALUE) == null)) {
            cvDataTableVal.put(DataTableColumns.FILTER_VALUE, DataTableColumns.DEFAULT_FILTER_VALUE);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.FORM_ID)) {
            cvDataTableVal.putNull(DataTableColumns.FORM_ID);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.LOCALE)
                || (cvDataTableVal.get(DataTableColumns.LOCALE) == null)) {
            cvDataTableVal.put(DataTableColumns.LOCALE, DataTableColumns.DEFAULT_LOCALE);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TYPE)
                || (cvDataTableVal.get(DataTableColumns.SAVEPOINT_TYPE) == null)) {
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_TYPE, SavepointTypeManipulator.complete());
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TIMESTAMP)
                || cvDataTableVal.get(DataTableColumns.SAVEPOINT_TIMESTAMP) == null) {
            String timeStamp = TableConstants.nanoSecondsFromMillis(System.currentTimeMillis());
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_TIMESTAMP, timeStamp);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_CREATOR)
                || (cvDataTableVal.get(DataTableColumns.SAVEPOINT_CREATOR) == null)) {
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_CREATOR, DataTableColumns.DEFAULT_SAVEPOINT_CREATOR);
        }
    }

    cleanUpValuesMap(orderedColumns, cvDataTableVal);

    boolean dbWithinTransaction = db.inTransaction();
    try {
        if (!dbWithinTransaction) {
            db.beginTransaction();
        }

        if (update) {
            db.update(tableId, cvDataTableVal, whereClause, whereArgs);
        } else {
            db.insertOrThrow(tableId, null, cvDataTableVal);
        }

        if (!dbWithinTransaction) {
            db.setTransactionSuccessful();
        }
    } finally {
        if (!dbWithinTransaction) {
            db.endTransaction();
        }
    }

}

From source file:mobile.tiis.appv2.base.BackboneApplication.java

public void updateChildVaccinationEventVaccinationAppointment(ChildCollector childCollector) {
    Child child = childCollector.getChildEntity();
    List<VaccinationEvent> vaccinationEvents = childCollector.getVeList();
    List<VaccinationAppointment> vaccinationAppointments = childCollector.getVaList();
    ContentValues childCV = new ContentValues();
    DatabaseHandler db = getDatabaseInstance();

    SQLiteDatabase db1 = db.getWritableDatabase();
    db1.beginTransactionNonExclusive();//w ww.ja  v  a 2 s  .  co  m
    try {
        String sql0 = "INSERT OR REPLACE INTO " + SQLHandler.Tables.CHILD + " ( "
                + SQLHandler.SyncColumns.UPDATED + ", " + SQLHandler.ChildColumns.ID + ","
                + SQLHandler.ChildColumns.BARCODE_ID + "," + SQLHandler.ChildColumns.FIRSTNAME1 + ","
                + SQLHandler.ChildColumns.FIRSTNAME2 + "," + SQLHandler.ChildColumns.LASTNAME1 + ","
                + SQLHandler.ChildColumns.BIRTHDATE + "," + SQLHandler.ChildColumns.GENDER + ","
                + SQLHandler.ChildColumns.TEMP_ID + "," + SQLHandler.ChildColumns.HEALTH_FACILITY + ","
                + SQLHandler.ChildColumns.DOMICILE + "," + SQLHandler.ChildColumns.DOMICILE_ID + ","
                + SQLHandler.ChildColumns.HEALTH_FACILITY_ID + "," + SQLHandler.ChildColumns.STATUS_ID + ","
                + SQLHandler.ChildColumns.BIRTHPLACE_ID + "," + SQLHandler.ChildColumns.NOTES + ","
                + SQLHandler.ChildColumns.STATUS + "," + SQLHandler.ChildColumns.MOTHER_FIRSTNAME + ","
                + SQLHandler.ChildColumns.MOTHER_LASTNAME + ","
                + SQLHandler.ChildColumns.CUMULATIVE_SERIAL_NUMBER + ","
                + SQLHandler.ChildColumns.CHILD_REGISTRY_YEAR + "," + SQLHandler.ChildColumns.MOTHER_TT2_STS
                + "," + SQLHandler.ChildColumns.MOTHER_VVU_STS + "," + SQLHandler.ChildColumns.PHONE
                + " ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        SQLiteStatement stmt0 = db1.compileStatement(sql0);
        stmt0.bindString(1, "1");
        stmt0.bindString(2, child.getId() == null ? "" : child.getId());
        stmt0.bindString(3, child.getBarcodeID() == null ? "" : child.getBarcodeID());
        stmt0.bindString(4, child.getFirstname1() == null ? "" : child.getFirstname1());
        stmt0.bindString(5, child.getFirstname2() == null ? "" : child.getFirstname2());
        stmt0.bindString(6, child.getLastname1() == null ? "" : child.getLastname1());
        stmt0.bindString(7, child.getBirthdate() == null ? "" : child.getBirthdate());
        stmt0.bindString(8, child.getGender() == null ? "" : child.getGender());
        stmt0.bindString(9, child.getTempId() == null ? "" : child.getTempId());
        stmt0.bindString(10, child.getHealthcenter() == null ? "" : child.getHealthcenter());
        stmt0.bindString(11, child.getDomicile() == null ? "" : child.getDomicile());
        stmt0.bindString(12, child.getDomicileId() == null ? "" : child.getDomicileId());
        stmt0.bindString(13, child.getHealthcenterId() == null ? "" : child.getHealthcenterId());
        stmt0.bindString(14, child.getStatusId() == null ? "" : child.getStatusId());
        stmt0.bindString(15, child.getBirthplaceId() == null ? "" : child.getBirthplaceId());
        stmt0.bindString(16, child.getNotes() == null ? "" : child.getNotes());
        stmt0.bindString(17, child.getStatus() == null ? "" : child.getStatus());
        stmt0.bindString(18, child.getMotherFirstname() == null ? "" : child.getMotherFirstname());
        stmt0.bindString(19, child.getMotherLastname() == null ? "" : child.getMotherLastname());
        stmt0.bindString(20, child.getChildCumulativeSn() == null ? "" : child.getChildCumulativeSn());
        stmt0.bindString(21, child.getChildRegistryYear() == null ? "" : child.getChildRegistryYear());
        stmt0.bindString(22, child.getMotherTT2Status() == null ? "" : child.getMotherTT2Status());
        stmt0.bindString(23, child.getMotherHivStatus() == null ? "" : child.getMotherHivStatus());
        stmt0.bindString(24, child.getPhone() == null ? "" : child.getPhone());
        stmt0.execute();
        stmt0.clearBindings();

        String sql = "INSERT OR REPLACE INTO " + SQLHandler.Tables.VACCINATION_EVENT + " ( "
                + SQLHandler.SyncColumns.UPDATED + ", " + SQLHandler.VaccinationEventColumns.APPOINTMENT_ID
                + "," + SQLHandler.VaccinationEventColumns.CHILD_ID + ","
                + SQLHandler.VaccinationEventColumns.DOSE_ID + ","
                + SQLHandler.VaccinationEventColumns.HEALTH_FACILITY_ID + ","
                + SQLHandler.VaccinationEventColumns.ID + "," + SQLHandler.VaccinationEventColumns.IS_ACTIVE
                + "," + SQLHandler.VaccinationEventColumns.MODIFIED_BY + ","
                + SQLHandler.VaccinationEventColumns.MODIFIED_ON + ","
                + SQLHandler.VaccinationEventColumns.NONVACCINATION_REASON_ID + ","
                + SQLHandler.VaccinationEventColumns.SCHEDULED_DATE + ","
                + SQLHandler.VaccinationEventColumns.VACCINATION_DATE + ","
                + SQLHandler.VaccinationEventColumns.VACCINATION_STATUS + ","
                + SQLHandler.VaccinationEventColumns.VACCINE_LOT_ID
                + " ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        SQLiteStatement stmt = db1.compileStatement(sql);

        for (VaccinationEvent vaccinationEvent : vaccinationEvents) {
            stmt.bindString(1, "1");
            stmt.bindString(2, vaccinationEvent.getAppointmentId());
            stmt.bindString(3, vaccinationEvent.getChildId());
            stmt.bindString(4, vaccinationEvent.getDoseId());
            stmt.bindString(5, vaccinationEvent.getHealthFacilityId());
            stmt.bindString(6, vaccinationEvent.getId());
            stmt.bindString(7, vaccinationEvent.getIsActive());
            stmt.bindString(8, vaccinationEvent.getModifiedBy());
            stmt.bindString(9, vaccinationEvent.getModifiedOn());
            stmt.bindString(10, vaccinationEvent.getNonvaccinationReasonId());
            stmt.bindString(11, vaccinationEvent.getScheduledDate());
            stmt.bindString(12, vaccinationEvent.getVaccinationDate());
            stmt.bindString(13, vaccinationEvent.getVaccinationStatus());
            stmt.bindString(14, vaccinationEvent.getVaccineLotId());
            stmt.execute();
            stmt.clearBindings();
        }

        String sql1 = "INSERT OR REPLACE INTO " + SQLHandler.Tables.VACCINATION_APPOINTMENT + " ( "
                + SQLHandler.SyncColumns.UPDATED + ", " + SQLHandler.VaccinationAppointmentColumns.CHILD_ID
                + "," + SQLHandler.VaccinationAppointmentColumns.ID + ","
                + SQLHandler.VaccinationAppointmentColumns.IS_ACTIVE + ","
                + SQLHandler.VaccinationAppointmentColumns.MODIFIED_BY + ","
                + SQLHandler.VaccinationAppointmentColumns.MODIFIED_ON + ","
                + SQLHandler.VaccinationAppointmentColumns.NOTES + ","
                + SQLHandler.VaccinationAppointmentColumns.OUTREACH + ","
                + SQLHandler.VaccinationAppointmentColumns.SCHEDULED_DATE + ","
                + SQLHandler.VaccinationAppointmentColumns.SCHEDULED_FACILITY_ID
                + " ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?,?)";

        SQLiteStatement stmt1 = db1.compileStatement(sql1);

        for (VaccinationAppointment vaccinationAppointment : vaccinationAppointments) {
            stmt1.bindString(1, "1");
            stmt1.bindString(2, vaccinationAppointment.getChildId());
            stmt1.bindString(3, vaccinationAppointment.getId());
            stmt1.bindString(4, vaccinationAppointment.getIsActive());
            stmt1.bindString(5, vaccinationAppointment.getModifiedBy());
            stmt1.bindString(6, vaccinationAppointment.getModifiedOn());
            stmt1.bindString(7, vaccinationAppointment.getNotes());
            stmt1.bindString(8, vaccinationAppointment.getOutreach());
            stmt1.bindString(9, vaccinationAppointment.getScheduledDate());
            stmt1.bindString(10, vaccinationAppointment.getScheduledFacilityId());

            stmt1.execute();
            stmt1.clearBindings();

        }

        db1.setTransactionSuccessful();
        db1.endTransaction();
    } catch (Exception e) {
        db1.endTransaction();
        e.printStackTrace();
    }
}