Search in sources :

Example 36 with OperationApplicationException

use of android.content.OperationApplicationException in project PermissionsDispatcher by hotchemi.

the class ContactsFragment method insertDummyContact.

/**
     * Accesses the Contacts content provider directly to insert a new contact.
     * <p>
     * The contact is called "__DUMMY ENTRY" and only contains a name.
     */
private void insertDummyContact() {
    // Two operations are needed to insert a new contact.
    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(2);
    // First, set up a new raw contact.
    ContentProviderOperation.Builder op = ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI).withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null).withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null);
    operations.add(op.build());
    // Next, set the name for the contact.
    op = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, DUMMY_CONTACT_NAME);
    operations.add(op.build());
    // Apply the operations.
    ContentResolver resolver = getActivity().getContentResolver();
    try {
        resolver.applyBatch(ContactsContract.AUTHORITY, operations);
    } catch (RemoteException e) {
        Log.d(TAG, "Could not add a new contact: " + e.getMessage());
    } catch (OperationApplicationException e) {
        Log.d(TAG, "Could not add a new contact: " + e.getMessage());
    }
}
Also used : ContentProviderOperation(android.content.ContentProviderOperation) ArrayList(java.util.ArrayList) RemoteException(android.os.RemoteException) OperationApplicationException(android.content.OperationApplicationException) ContentResolver(android.content.ContentResolver)

Example 37 with OperationApplicationException

use of android.content.OperationApplicationException 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 38 with OperationApplicationException

use of android.content.OperationApplicationException 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)

Example 39 with OperationApplicationException

use of android.content.OperationApplicationException in project SeriesGuide by UweTrottmann.

the class ListsTools method removeListsRemovedOnHexagon.

public static boolean removeListsRemovedOnHexagon(SgApp app) {
    Timber.d("removeListsRemovedOnHexagon");
    HashSet<String> localListIds = getListIds(app);
    if (localListIds == null) {
        // query failed
        return false;
    }
    if (localListIds.size() <= 1) {
        // one or no list, can not remove any list
        return true;
    }
    // get list of ids of lists on hexagon
    List<String> hexagonListIds = new ArrayList<>(localListIds.size());
    String cursor = null;
    do {
        try {
            Lists listsService = app.getHexagonTools().getListsService();
            if (listsService == null) {
                // no longer signed in
                return false;
            }
            Lists.GetIds request = listsService.getIds();
            if (!TextUtils.isEmpty(cursor)) {
                request.setCursor(cursor);
            }
            SgListIds response = request.execute();
            if (response == null) {
                Timber.d("removeListsRemovedOnHexagon: failed, response is null.");
                return false;
            }
            List<String> listIds = response.getListIds();
            if (listIds == null || listIds.size() == 0) {
                // empty response, assume we got all ids
                break;
            }
            hexagonListIds.addAll(listIds);
            cursor = response.getCursor();
        } catch (IOException e) {
            HexagonTools.trackFailedRequest(app, "get list ids", e);
            return false;
        }
    } while (// fetch next batch
    !TextUtils.isEmpty(cursor));
    if (hexagonListIds.size() <= 1) {
        // one or no list on hexagon, can not remove any list
        return true;
    }
    // exclude any lists that are on hexagon
    for (String listId : hexagonListIds) {
        localListIds.remove(listId);
    }
    // remove any list not on hexagon
    if (localListIds.size() > 0) {
        ArrayList<ContentProviderOperation> batch = new ArrayList<>();
        for (String listId : localListIds) {
            batch.add(ContentProviderOperation.newDelete(SeriesGuideContract.Lists.buildListUri(listId)).build());
        }
        try {
            DBUtils.applyInSmallBatches(app, batch);
        } catch (OperationApplicationException e) {
            Timber.e(e, "removeListsRemovedOnHexagon: deleting lists failed.");
            return false;
        }
    }
    return true;
}
Also used : ContentProviderOperation(android.content.ContentProviderOperation) Lists(com.uwetrottmann.seriesguide.backend.lists.Lists) ArrayList(java.util.ArrayList) IOException(java.io.IOException) OperationApplicationException(android.content.OperationApplicationException) SgListIds(com.uwetrottmann.seriesguide.backend.lists.model.SgListIds)

Example 40 with OperationApplicationException

use of android.content.OperationApplicationException in project SeriesGuide by UweTrottmann.

the class TraktTools method processTraktEpisodes.

private boolean processTraktEpisodes(boolean isInitialSync, String seasonId, BaseSeason traktSeason, List<SyncSeason> syncSeasons, Flag flag) {
    HashSet<Integer> traktEpisodes = buildTraktEpisodesMap(traktSeason.episodes);
    Cursor localEpisodesQuery = context.getContentResolver().query(SeriesGuideContract.Episodes.buildEpisodesOfSeasonUri(seasonId), new String[] { SeriesGuideContract.Episodes._ID, SeriesGuideContract.Episodes.NUMBER, flag.databaseColumn }, null, null, null);
    if (localEpisodesQuery == null) {
        return false;
    }
    ArrayList<ContentProviderOperation> batch = new ArrayList<>();
    List<SyncEpisode> syncEpisodes = new ArrayList<>();
    int episodesAddFlagCount = 0;
    int episodesRemoveFlagCount = 0;
    while (localEpisodesQuery.moveToNext()) {
        int episodeId = localEpisodesQuery.getInt(0);
        int episodeNumber = localEpisodesQuery.getInt(1);
        int flagValue = localEpisodesQuery.getInt(2);
        boolean isFlagged = flag == Flag.WATCHED ? EpisodeTools.isWatched(flagValue) : EpisodeTools.isCollected(flagValue);
        if (traktEpisodes.contains(episodeNumber)) {
            // episode watched/collected on trakt
            if (!isFlagged) {
                // set as watched/collected
                batch.add(ContentProviderOperation.newUpdate(SeriesGuideContract.Episodes.buildEpisodeUri(episodeId)).withValue(flag.databaseColumn, flag.flaggedValue).build());
                episodesAddFlagCount++;
            }
        } else {
            // episode not watched/collected on trakt
            if (isFlagged) {
                if (isInitialSync) {
                    // upload to trakt
                    syncEpisodes.add(new SyncEpisode().number(episodeNumber));
                } else {
                    // set as not watched/collected if it is currently watched/collected
                    boolean isSkipped = flag == Flag.WATCHED && EpisodeTools.isSkipped(flagValue);
                    if (!isSkipped) {
                        batch.add(ContentProviderOperation.newUpdate(SeriesGuideContract.Episodes.buildEpisodeUri(episodeId)).withValue(flag.databaseColumn, flag.notFlaggedValue).build());
                        episodesRemoveFlagCount++;
                    }
                }
            }
        }
    }
    int localEpisodeCount = localEpisodesQuery.getCount();
    boolean addFlagToWholeSeason = episodesAddFlagCount == localEpisodeCount;
    boolean removeFlagFromWholeSeason = episodesRemoveFlagCount == localEpisodeCount;
    localEpisodesQuery.close();
    // if setting the whole season as (not) watched/collected, replace with single db op
    if (addFlagToWholeSeason || removeFlagFromWholeSeason) {
        batch.clear();
        batch.add(ContentProviderOperation.newUpdate(SeriesGuideContract.Episodes.buildEpisodesOfSeasonUri(seasonId)).withValue(flag.databaseColumn, addFlagToWholeSeason ? flag.flaggedValue : flag.notFlaggedValue).build());
    }
    try {
        DBUtils.applyInSmallBatches(context, batch);
    } catch (OperationApplicationException e) {
        Timber.e(e, "Episodes watched/collected values database update failed.");
    }
    if (syncEpisodes.size() > 0) {
        syncSeasons.add(new SyncSeason().number(traktSeason.number).episodes(syncEpisodes));
    }
    return true;
}
Also used : ContentProviderOperation(android.content.ContentProviderOperation) SyncEpisode(com.uwetrottmann.trakt5.entities.SyncEpisode) ArrayList(java.util.ArrayList) Cursor(android.database.Cursor) OperationApplicationException(android.content.OperationApplicationException) SyncSeason(com.uwetrottmann.trakt5.entities.SyncSeason)

Aggregations

OperationApplicationException (android.content.OperationApplicationException)63 ContentProviderOperation (android.content.ContentProviderOperation)57 ArrayList (java.util.ArrayList)52 RemoteException (android.os.RemoteException)42 ContentProviderResult (android.content.ContentProviderResult)21 ContentValues (android.content.ContentValues)15 ContentResolver (android.content.ContentResolver)12 Cursor (android.database.Cursor)11 Uri (android.net.Uri)11 IOException (java.io.IOException)11 Intent (android.content.Intent)9 LinkedList (java.util.LinkedList)6 List (java.util.List)6 JSONArray (org.json.JSONArray)6 JSONException (org.json.JSONException)6 JSONObject (org.json.JSONObject)6 BroadcastReceiver (android.content.BroadcastReceiver)4 Context (android.content.Context)4 IntentFilter (android.content.IntentFilter)4 PackageMonitor (com.android.internal.content.PackageMonitor)4