Search in sources :

Example 51 with ContentProviderOperation

use of android.content.ContentProviderOperation in project iosched by google.

the class HashtagsHandler method makeContentProviderOperations.

@Override
public void makeContentProviderOperations(ArrayList<ContentProviderOperation> list) {
    LOGD(TAG, "makeContentProviderOperations");
    Uri uri = ScheduleContractHelper.setUriAsCalledFromSyncAdapter(ScheduleContract.Hashtags.CONTENT_URI);
    // Remove all the current entries
    list.add(ContentProviderOperation.newDelete(uri).build());
    // Insert hashtags
    for (Hashtag hashtag : mHashtags.values()) {
        ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(uri);
        builder.withValue(ScheduleContract.Hashtags.HASHTAG_NAME, hashtag.name);
        builder.withValue(ScheduleContract.Hashtags.HASHTAG_DESCRIPTION, hashtag.description);
        try {
            builder.withValue(ScheduleContract.Hashtags.HASHTAG_COLOR, Color.parseColor(hashtag.color));
        } catch (IllegalArgumentException e) {
            builder.withValue(ScheduleContract.Hashtags.HASHTAG_COLOR, Color.BLACK);
        }
        builder.withValue(ScheduleContract.Hashtags.HASHTAG_ORDER, hashtag.order);
        list.add(builder.build());
    }
    LOGD(TAG, "Hashtags: " + mHashtags.size());
}
Also used : Hashtag(com.google.samples.apps.iosched.io.model.Hashtag) ContentProviderOperation(android.content.ContentProviderOperation) Uri(android.net.Uri)

Example 52 with ContentProviderOperation

use of android.content.ContentProviderOperation in project iosched by google.

the class ConferenceDataHandler method applyConferenceData.

/**
     * Parses the conference data in the given objects and imports the data into the
     * content provider. The format of the data is documented at https://code.google.com/p/iosched.
     *
     * @param dataBodies The collection of JSON objects to parse and import.
     * @param dataTimestamp The timestamp of the data. This should be in RFC1123 format.
     * @param downloadsAllowed Whether or not we are supposed to download data from the internet if needed.
     * @throws IOException If there is a problem parsing the data.
     */
public void applyConferenceData(String[] dataBodies, String dataTimestamp, boolean downloadsAllowed) throws IOException {
    LOGD(TAG, "Applying data from " + dataBodies.length + " files, timestamp " + dataTimestamp);
    // create handlers for each data type
    mHandlerForKey.put(DATA_KEY_ROOMS, mRoomsHandler = new RoomsHandler(mContext));
    mHandlerForKey.put(DATA_KEY_BLOCKS, mBlocksHandler = new BlocksHandler(mContext));
    mHandlerForKey.put(DATA_KEY_TAGS, mTagsHandler = new TagsHandler(mContext));
    mHandlerForKey.put(DATA_KEY_SPEAKERS, mSpeakersHandler = new SpeakersHandler(mContext));
    mHandlerForKey.put(DATA_KEY_SESSIONS, mSessionsHandler = new SessionsHandler(mContext));
    mHandlerForKey.put(DATA_KEY_SEARCH_SUGGESTIONS, mSearchSuggestHandler = new SearchSuggestHandler(mContext));
    mHandlerForKey.put(DATA_KEY_MAP, mMapPropertyHandler = new MapPropertyHandler(mContext));
    mHandlerForKey.put(DATA_KEY_HASHTAGS, mHashtagsHandler = new HashtagsHandler(mContext));
    mHandlerForKey.put(DATA_KEY_VIDEOS, mVideosHandler = new VideosHandler(mContext));
    mHandlerForKey.put(DATA_KEY_CARDS, mCardHandler = new CardHandler(mContext));
    // process the jsons. This will call each of the handlers when appropriate to deal
    // with the objects we see in the data.
    LOGD(TAG, "Processing " + dataBodies.length + " JSON objects.");
    for (int i = 0; i < dataBodies.length; i++) {
        LOGD(TAG, "Processing json object #" + (i + 1) + " of " + dataBodies.length);
        processDataBody(dataBodies[i]);
    }
    // the sessions handler needs to know the tag and speaker maps to process sessions
    mSessionsHandler.setTagMap(mTagsHandler.getTagMap());
    mSessionsHandler.setSpeakerMap(mSpeakersHandler.getSpeakerMap());
    // produce the necessary content provider operations
    ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
    for (String key : DATA_KEYS_IN_ORDER) {
        LOGI(TAG, "Building content provider operations for: " + key);
        mHandlerForKey.get(key).makeContentProviderOperations(batch);
        LOGI(TAG, "Content provider operations so far: " + batch.size());
    }
    LOGD(TAG, "Total content provider operations: " + batch.size());
    // download or process local map tile overlay files (SVG files)
    LOGD(TAG, "Processing map overlay files");
    processMapOverlayFiles(mMapPropertyHandler.getTileOverlays(), downloadsAllowed);
    // finally, push the changes into the Content Provider
    LOGI(TAG, "Applying " + batch.size() + " content provider operations.");
    try {
        int operations = batch.size();
        if (operations > 0) {
            mContext.getContentResolver().applyBatch(ScheduleContract.CONTENT_AUTHORITY, batch);
        }
        LOGD(TAG, "Successfully applied " + operations + " content provider operations.");
        mContentProviderOperationsDone += operations;
    } catch (RemoteException ex) {
        LOGE(TAG, "RemoteException while applying content provider operations.");
        throw new RuntimeException("Error executing content provider batch operation", ex);
    } catch (OperationApplicationException ex) {
        LOGE(TAG, "OperationApplicationException while applying content provider operations.");
        throw new RuntimeException("Error executing content provider batch operation", ex);
    }
    // notify all top-level paths
    LOGD(TAG, "Notifying changes on all top-level paths on Content Resolver.");
    ContentResolver resolver = mContext.getContentResolver();
    for (String path : ScheduleContract.TOP_LEVEL_PATHS) {
        Uri uri = ScheduleContract.BASE_CONTENT_URI.buildUpon().appendPath(path).build();
        resolver.notifyChange(uri, null);
    }
    // update our data timestamp
    setDataTimestamp(dataTimestamp);
    LOGD(TAG, "Done applying conference data.");
}
Also used : ContentProviderOperation(android.content.ContentProviderOperation) ArrayList(java.util.ArrayList) Uri(android.net.Uri) ContentResolver(android.content.ContentResolver) RemoteException(android.os.RemoteException) OperationApplicationException(android.content.OperationApplicationException)

Example 53 with ContentProviderOperation

use of android.content.ContentProviderOperation in project android-ui-design-pattern by MathieuCalba.

the class YANAService method initData.

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
private void initData() {
    Intent i = new Intent(InitDataReceiver.ACTION_INIT_DATA_CHANGE_STATE);
    i.putExtra(InitDataReceiver.EXTRA_STATE, true);
    mLocalBroadcastManager.sendBroadcast(i);
    final SharedPreferences pref = getSharedPreferences(PREF_DATA_NAME, MODE_PRIVATE);
    final boolean isDataInit = pref.getBoolean(PREF_DATA_IS_INIT_KEY, false);
    if (!isDataInit) {
        final ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
        final Set<FeedsData.Article> articles = FeedsData.getArticles(this);
        for (final Iterator<FeedsData.Article> iterator = articles.iterator(); iterator.hasNext(); ) {
            final FeedsData.Article article = iterator.next();
            batch.add(createArticleInsertOpe(article));
        }
        final ContentResolver cr = getContentResolver();
        try {
            cr.applyBatch(YANAContract.CONTENT_AUTHORITY, batch);
            final SharedPreferences.Editor edit = pref.edit();
            edit.putBoolean(PREF_DATA_IS_INIT_KEY, true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
                edit.apply();
            } else {
                edit.commit();
            }
        } catch (final RemoteException e) {
            if (BuildConfig.DEBUG) {
                Log.e(TAG, "Impossible to add batch", e);
            }
        } catch (final OperationApplicationException e) {
            if (BuildConfig.DEBUG) {
                Log.e(TAG, "Impossible to add batch", e);
            }
        }
    }
    i = new Intent(InitDataReceiver.ACTION_INIT_DATA_CHANGE_STATE);
    i.putExtra(InitDataReceiver.EXTRA_STATE, false);
    mLocalBroadcastManager.sendBroadcast(i);
}
Also used : ContentProviderOperation(android.content.ContentProviderOperation) FeedsData(com.mathieucalba.yana.model.FeedsData) SharedPreferences(android.content.SharedPreferences) ArrayList(java.util.ArrayList) Intent(android.content.Intent) ContentResolver(android.content.ContentResolver) RemoteException(android.os.RemoteException) OperationApplicationException(android.content.OperationApplicationException) TargetApi(android.annotation.TargetApi)

Example 54 with ContentProviderOperation

use of android.content.ContentProviderOperation in project muzei by romannurik.

the class SourceManager method migrateDataToContentProvider.

/**
     * One time migration of source data from SharedPreferences to the ContentProvider
     */
private static void migrateDataToContentProvider(Context context) {
    SharedPreferences sharedPrefs = context.getSharedPreferences("muzei_art_sources", 0);
    String selectedSourceString = sharedPrefs.getString(PREF_SELECTED_SOURCE, null);
    Set<String> sourceStates = sharedPrefs.getStringSet(PREF_SOURCE_STATES, null);
    if (selectedSourceString == null || sourceStates == null) {
        return;
    }
    ComponentName selectedSource = ComponentName.unflattenFromString(selectedSourceString);
    final ArrayList<ContentProviderOperation> operations = new ArrayList<>();
    for (String sourceStatesPair : sourceStates) {
        String[] pair = sourceStatesPair.split("\\|", 2);
        ComponentName source = ComponentName.unflattenFromString(pair[0]);
        try {
            ContentValues values = new ContentValues();
            try {
                // Ensure the source is a valid Service
                context.getPackageManager().getServiceInfo(source, 0);
            } catch (PackageManager.NameNotFoundException e) {
                // No need to keep no longer valid sources
                continue;
            }
            values.put(MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME, source.flattenToShortString());
            values.put(MuzeiContract.Sources.COLUMN_NAME_IS_SELECTED, source.equals(selectedSource));
            JSONObject jsonObject = (JSONObject) new JSONTokener(pair[1]).nextValue();
            values.put(MuzeiContract.Sources.COLUMN_NAME_DESCRIPTION, jsonObject.optString("description"));
            values.put(MuzeiContract.Sources.COLUMN_NAME_WANTS_NETWORK_AVAILABLE, jsonObject.optBoolean("wantsNetworkAvailable"));
            // Parse out the UserCommands. This ensures it is properly formatted and extracts the
            // Next Artwork built in command from the list
            List<UserCommand> commands = MuzeiContract.Sources.parseCommands(jsonObject.optJSONArray("userCommands").toString());
            JSONArray commandsSerialized = new JSONArray();
            boolean supportsNextArtwork = false;
            for (UserCommand command : commands) {
                if (command.getId() == MuzeiArtSource.BUILTIN_COMMAND_ID_NEXT_ARTWORK) {
                    supportsNextArtwork = true;
                } else {
                    commandsSerialized.put(command.serialize());
                }
            }
            values.put(MuzeiContract.Sources.COLUMN_NAME_SUPPORTS_NEXT_ARTWORK_COMMAND, supportsNextArtwork);
            values.put(MuzeiContract.Sources.COLUMN_NAME_COMMANDS, commandsSerialized.toString());
            operations.add(ContentProviderOperation.newInsert(MuzeiContract.Sources.CONTENT_URI).withValues(values).build());
        } catch (JSONException e) {
            Log.e(TAG, "Error loading source state for " + source, e);
        }
    }
    try {
        context.getContentResolver().applyBatch(MuzeiContract.AUTHORITY, operations);
        sharedPrefs.edit().remove(PREF_SELECTED_SOURCE).remove(PREF_SOURCE_STATES).apply();
        sendSelectedSourceAnalytics(context, selectedSource);
    } catch (RemoteException | OperationApplicationException e) {
        Log.e(TAG, "Error writing sources to ContentProvider", e);
    }
}
Also used : ContentValues(android.content.ContentValues) ContentProviderOperation(android.content.ContentProviderOperation) SharedPreferences(android.content.SharedPreferences) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) JSONTokener(org.json.JSONTokener) UserCommand(com.google.android.apps.muzei.api.UserCommand) PackageManager(android.content.pm.PackageManager) JSONObject(org.json.JSONObject) ComponentName(android.content.ComponentName) RemoteException(android.os.RemoteException) OperationApplicationException(android.content.OperationApplicationException)

Example 55 with ContentProviderOperation

use of android.content.ContentProviderOperation in project android by owncloud.

the class FileDataStorageManager method saveFolder.

/**
     * Inserts or updates the list of files contained in a given folder.
     * <p/>
     * CALLER IS THE RESPONSIBLE FOR GRANTING RIGHT UPDATE OF INFORMATION, NOT THIS METHOD.
     * HERE ONLY DATA CONSISTENCY SHOULD BE GRANTED
     *
     * @param folder
     * @param updatedFiles
     * @param filesToRemove
     */
public void saveFolder(OCFile folder, Collection<OCFile> updatedFiles, Collection<OCFile> filesToRemove) {
    Log_OC.d(TAG, "Saving folder " + folder.getRemotePath() + " with " + updatedFiles.size() + " children and " + filesToRemove.size() + " files to remove");
    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(updatedFiles.size());
    // prepare operations to insert or update files to save in the given folder
    for (OCFile file : updatedFiles) {
        ContentValues cv = new ContentValues();
        cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
        cv.put(ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA, file.getModificationTimestampAtLastSyncForData());
        cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
        cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
        cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
        cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
        cv.put(ProviderTableMeta.FILE_PARENT, folder.getFileId());
        cv.put(ProviderTableMeta.FILE_PATH, file.getRemotePath());
        if (!file.isFolder()) {
            cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
        }
        cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
        cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.getLastSyncDateForProperties());
        cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, file.getLastSyncDateForData());
        cv.put(ProviderTableMeta.FILE_ETAG, file.getEtag());
        cv.put(ProviderTableMeta.FILE_TREE_ETAG, file.getTreeEtag());
        cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, file.isSharedViaLink() ? 1 : 0);
        cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, file.isSharedWithSharee() ? 1 : 0);
        cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, file.getPublicLink());
        cv.put(ProviderTableMeta.FILE_PERMISSIONS, file.getPermissions());
        cv.put(ProviderTableMeta.FILE_REMOTE_ID, file.getRemoteId());
        cv.put(ProviderTableMeta.FILE_UPDATE_THUMBNAIL, file.needsUpdateThumbnail());
        cv.put(ProviderTableMeta.FILE_IS_DOWNLOADING, file.isDownloading());
        cv.put(ProviderTableMeta.FILE_ETAG_IN_CONFLICT, file.getEtagInConflict());
        boolean existsByPath = fileExists(file.getRemotePath());
        if (existsByPath || fileExists(file.getFileId())) {
            // updating an existing file
            operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).withValues(cv).withSelection(ProviderTableMeta._ID + "=?", new String[] { String.valueOf(file.getFileId()) }).build());
        } else {
            // adding a new file
            setInitialAvailableOfflineStatus(file, cv);
            operations.add(ContentProviderOperation.newInsert(ProviderTableMeta.CONTENT_URI).withValues(cv).build());
        }
    }
    // prepare operations to remove files in the given folder
    String where = ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?" + " AND " + ProviderTableMeta.FILE_PATH + "=?";
    String[] whereArgs = null;
    for (OCFile file : filesToRemove) {
        if (file.getParentId() == folder.getFileId()) {
            whereArgs = new String[] { mAccount.name, file.getRemotePath() };
            if (file.isFolder()) {
                operations.add(ContentProviderOperation.newDelete(ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_DIR, file.getFileId())).withSelection(where, whereArgs).build());
                File localFolder = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
                if (localFolder.exists()) {
                    removeLocalFolder(localFolder);
                }
            } else {
                operations.add(ContentProviderOperation.newDelete(ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, file.getFileId())).withSelection(where, whereArgs).build());
                if (file.isDown()) {
                    String path = file.getStoragePath();
                    new File(path).delete();
                    // notify MediaScanner about removed file
                    triggerMediaScan(path);
                }
            }
        }
    }
    // update metadata of folder
    ContentValues cv = new ContentValues();
    cv.put(ProviderTableMeta.FILE_MODIFIED, folder.getModificationTimestamp());
    cv.put(ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA, folder.getModificationTimestampAtLastSyncForData());
    cv.put(ProviderTableMeta.FILE_CREATION, folder.getCreationTimestamp());
    cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, folder.getFileLength());
    cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, folder.getMimetype());
    cv.put(ProviderTableMeta.FILE_NAME, folder.getFileName());
    cv.put(ProviderTableMeta.FILE_PARENT, folder.getParentId());
    cv.put(ProviderTableMeta.FILE_PATH, folder.getRemotePath());
    cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
    cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, folder.getLastSyncDateForProperties());
    cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, folder.getLastSyncDateForData());
    cv.put(ProviderTableMeta.FILE_ETAG, folder.getEtag());
    cv.put(ProviderTableMeta.FILE_TREE_ETAG, folder.getTreeEtag());
    cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, folder.isSharedViaLink() ? 1 : 0);
    cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, folder.isSharedWithSharee() ? 1 : 0);
    cv.put(ProviderTableMeta.FILE_PUBLIC_LINK, folder.getPublicLink());
    cv.put(ProviderTableMeta.FILE_PERMISSIONS, folder.getPermissions());
    cv.put(ProviderTableMeta.FILE_REMOTE_ID, folder.getRemoteId());
    operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI).withValues(cv).withSelection(ProviderTableMeta._ID + "=?", new String[] { String.valueOf(folder.getFileId()) }).build());
    // apply operations in batch
    ContentProviderResult[] results = null;
    Log_OC.d(TAG, "Sending " + operations.size() + " operations to FileContentProvider");
    try {
        if (getContentResolver() != null) {
            results = getContentResolver().applyBatch(MainApp.getAuthority(), operations);
        } else {
            results = getContentProviderClient().applyBatch(operations);
        }
    } catch (OperationApplicationException e) {
        Log_OC.e(TAG, "Exception in batch of operations " + e.getMessage());
    } catch (RemoteException e) {
        Log_OC.e(TAG, "Exception in batch of operations  " + e.getMessage());
    }
    // update new id in file objects for insertions
    if (results != null) {
        long newId;
        Iterator<OCFile> filesIt = updatedFiles.iterator();
        OCFile file = null;
        for (int i = 0; i < results.length; i++) {
            if (filesIt.hasNext()) {
                file = filesIt.next();
            } else {
                file = null;
            }
            if (results[i].uri != null) {
                newId = Long.parseLong(results[i].uri.getPathSegments().get(1));
                //updatedFiles.get(i).setFileId(newId);
                if (file != null) {
                    file.setFileId(newId);
                }
            }
        }
    }
}
Also used : ContentValues(android.content.ContentValues) ContentProviderResult(android.content.ContentProviderResult) ContentProviderOperation(android.content.ContentProviderOperation) ArrayList(java.util.ArrayList) RemoteException(android.os.RemoteException) File(java.io.File) OperationApplicationException(android.content.OperationApplicationException)

Aggregations

ContentProviderOperation (android.content.ContentProviderOperation)75 ArrayList (java.util.ArrayList)53 OperationApplicationException (android.content.OperationApplicationException)34 Uri (android.net.Uri)27 ContentValues (android.content.ContentValues)25 RemoteException (android.os.RemoteException)22 Cursor (android.database.Cursor)14 ContentProviderResult (android.content.ContentProviderResult)13 ContentResolver (android.content.ContentResolver)9 LinkedList (java.util.LinkedList)8 IOException (java.io.IOException)7 JSONArray (org.json.JSONArray)6 JSONException (org.json.JSONException)6 JSONObject (org.json.JSONObject)6 Intent (android.content.Intent)5 List (java.util.List)5 SuppressLint (android.annotation.SuppressLint)4 BroadcastReceiver (android.content.BroadcastReceiver)4 Context (android.content.Context)4 IntentFilter (android.content.IntentFilter)4