use of android.content.ContentProviderClient in project android_frameworks_base by crdroidandroid.
the class RootsCache method loadRootsForAuthority.
/**
* Bring up requested provider and query for all active roots.
*/
private Collection<RootInfo> loadRootsForAuthority(ContentResolver resolver, String authority, boolean forceRefresh) {
if (DEBUG)
Log.d(TAG, "Loading roots for " + authority);
synchronized (mObservedAuthorities) {
if (mObservedAuthorities.add(authority)) {
// Watch for any future updates
final Uri rootsUri = DocumentsContract.buildRootsUri(authority);
mContext.getContentResolver().registerContentObserver(rootsUri, true, mObserver);
}
}
final Uri rootsUri = DocumentsContract.buildRootsUri(authority);
if (!forceRefresh) {
// Look for roots data that we might have cached for ourselves in the
// long-lived system process.
final Bundle systemCache = resolver.getCache(rootsUri);
if (systemCache != null) {
if (DEBUG)
Log.d(TAG, "System cache hit for " + authority);
return systemCache.getParcelableArrayList(TAG);
}
}
final ArrayList<RootInfo> roots = new ArrayList<>();
ContentProviderClient client = null;
Cursor cursor = null;
try {
client = DocumentsApplication.acquireUnstableProviderOrThrow(resolver, authority);
cursor = client.query(rootsUri, null, null, null, null);
while (cursor.moveToNext()) {
final RootInfo root = RootInfo.fromRootsCursor(authority, cursor);
roots.add(root);
}
} catch (Exception e) {
Log.w(TAG, "Failed to load some roots from " + authority + ": " + e);
} finally {
IoUtils.closeQuietly(cursor);
ContentProviderClient.releaseQuietly(client);
}
// Cache these freshly parsed roots over in the long-lived system
// process, in case our process goes away. The system takes care of
// invalidating the cache if the package or Uri changes.
final Bundle systemCache = new Bundle();
systemCache.putParcelableArrayList(TAG, roots);
resolver.putCache(rootsUri, systemCache);
return roots;
}
use of android.content.ContentProviderClient in project android_frameworks_base by crdroidandroid.
the class OpenExternalDirectoryActivity method getIntentForExistingPermission.
private static Intent getIntentForExistingPermission(OpenExternalDirectoryActivity activity, boolean isRoot, File root, File file) {
final String packageName = activity.getCallingPackage();
final ContentProviderClient storageClient = activity.getExternalStorageClient();
final Uri grantedUri = getGrantedUriPermission(activity, storageClient, file);
final Uri rootUri = root.equals(file) ? grantedUri : getGrantedUriPermission(activity, storageClient, root);
if (DEBUG)
Log.d(TAG, "checking if " + packageName + " already has permission for " + grantedUri + " or its root (" + rootUri + ")");
final ActivityManager am = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
for (UriPermission uriPermission : am.getGrantedUriPermissions(packageName).getList()) {
final Uri uri = uriPermission.getUri();
if (uri == null) {
Log.w(TAG, "null URI for " + uriPermission);
continue;
}
if (uri.equals(grantedUri) || uri.equals(rootUri)) {
if (DEBUG)
Log.d(TAG, packageName + " already has permission: " + uriPermission);
return createGrantedUriPermissionsIntent(grantedUri);
}
}
if (DEBUG)
Log.d(TAG, packageName + " does not have permission for " + grantedUri);
return null;
}
use of android.content.ContentProviderClient in project android_frameworks_base by crdroidandroid.
the class DirectoryLoader method loadInBackground.
@Override
public final DirectoryResult loadInBackground() {
synchronized (this) {
if (isLoadInBackgroundCanceled()) {
throw new OperationCanceledException();
}
mSignal = new CancellationSignal();
}
final ContentResolver resolver = getContext().getContentResolver();
final String authority = mUri.getAuthority();
final DirectoryResult result = new DirectoryResult();
result.doc = mDoc;
// Use default document when searching
if (mSearchMode) {
final Uri docUri = DocumentsContract.buildDocumentUri(mRoot.authority, mRoot.documentId);
try {
mDoc = DocumentInfo.fromUri(resolver, docUri);
} catch (FileNotFoundException e) {
Log.w(TAG, "Failed to query", e);
result.exception = e;
return result;
}
}
if (mUserSortOrder != State.SORT_ORDER_UNKNOWN) {
result.sortOrder = mUserSortOrder;
} else {
if ((mDoc.flags & Document.FLAG_DIR_PREFERS_LAST_MODIFIED) != 0) {
result.sortOrder = State.SORT_ORDER_LAST_MODIFIED;
} else {
result.sortOrder = State.SORT_ORDER_DISPLAY_NAME;
}
}
// Search always uses ranking from provider
if (mSearchMode) {
result.sortOrder = State.SORT_ORDER_UNKNOWN;
}
if (DEBUG)
Log.d(TAG, "userSortOrder=" + mUserSortOrder + ", sortOrder=" + result.sortOrder);
ContentProviderClient client = null;
Cursor cursor = null;
try {
client = DocumentsApplication.acquireUnstableProviderOrThrow(resolver, authority);
cursor = client.query(mUri, null, null, null, getQuerySortOrder(result.sortOrder), mSignal);
if (cursor == null) {
throw new RemoteException("Provider returned null");
}
cursor.registerContentObserver(mObserver);
cursor = new RootCursorWrapper(mUri.getAuthority(), mRoot.rootId, cursor, -1);
if (mSearchMode) {
// Filter directories out of search results, for now
cursor = new FilteringCursorWrapper(cursor, null, SEARCH_REJECT_MIMES);
}
result.client = client;
result.cursor = cursor;
} catch (Exception e) {
Log.w(TAG, "Failed to query", e);
result.exception = e;
ContentProviderClient.releaseQuietly(client);
} finally {
synchronized (this) {
mSignal = null;
}
}
return result;
}
use of android.content.ContentProviderClient in project android_frameworks_base by crdroidandroid.
the class DocumentClipper method getDocumentsFromClipData.
/**
* Returns a list of Documents as decoded in clipData.
* This should be run from inside an AsyncTask.
*/
public List<DocumentInfo> getDocumentsFromClipData(ClipData clipData) {
assert (clipData != null);
final List<DocumentInfo> srcDocs = new ArrayList<>();
int count = clipData.getItemCount();
if (count == 0) {
return srcDocs;
}
ContentResolver resolver = mContext.getContentResolver();
for (int i = 0; i < count; ++i) {
ClipData.Item item = clipData.getItemAt(i);
Uri itemUri = item.getUri();
if (itemUri != null && DocumentsContract.isDocumentUri(mContext, itemUri)) {
ContentProviderClient client = null;
Cursor cursor = null;
try {
client = DocumentsApplication.acquireUnstableProviderOrThrow(resolver, itemUri.getAuthority());
cursor = client.query(itemUri, null, null, null, null);
cursor.moveToPosition(0);
srcDocs.add(DocumentInfo.fromCursor(cursor, itemUri.getAuthority()));
} catch (Exception e) {
Log.e(TAG, e.getMessage());
} finally {
IoUtils.closeQuietly(cursor);
ContentProviderClient.releaseQuietly(client);
}
}
}
return srcDocs;
}
use of android.content.ContentProviderClient in project apps-android-commons by commons-app.
the class ModificationsSyncAdapter method onPerformSync.
@Override
public void onPerformSync(Account account, Bundle bundle, String s, ContentProviderClient contentProviderClient, SyncResult syncResult) {
// This code is fraught with possibilities of race conditions, but lalalalala I can't hear you!
Cursor allModifications;
try {
allModifications = contentProviderClient.query(ModificationsContentProvider.BASE_URI, null, null, null, null);
} catch (RemoteException e) {
throw new RuntimeException(e);
}
// Exit early if nothing to do
if (allModifications == null || allModifications.getCount() == 0) {
Timber.d("No modifications to perform");
return;
}
String authCookie;
try {
authCookie = AccountManager.get(getContext()).blockingGetAuthToken(account, "", false);
} catch (OperationCanceledException | AuthenticatorException e) {
throw new RuntimeException(e);
} catch (IOException e) {
Timber.d("Could not authenticate :(");
return;
}
if (Utils.isNullOrWhiteSpace(authCookie)) {
Timber.d("Could not authenticate :(");
return;
}
MWApi api = CommonsApplication.getInstance().getMWApi();
api.setAuthCookie(authCookie);
String editToken;
ApiResult requestResult, responseResult;
try {
editToken = api.getEditToken();
} catch (IOException e) {
Timber.d("Can not retreive edit token!");
return;
}
allModifications.moveToFirst();
Timber.d("Found %d modifications to execute", allModifications.getCount());
ContentProviderClient contributionsClient = null;
try {
contributionsClient = getContext().getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY);
while (!allModifications.isAfterLast()) {
ModifierSequence sequence = ModifierSequence.fromCursor(allModifications);
sequence.setContentProviderClient(contentProviderClient);
Contribution contrib;
Cursor contributionCursor;
try {
contributionCursor = contributionsClient.query(sequence.getMediaUri(), null, null, null, null);
} catch (RemoteException e) {
throw new RuntimeException(e);
}
contributionCursor.moveToFirst();
contrib = Contribution.fromCursor(contributionCursor);
if (contrib.getState() == Contribution.STATE_COMPLETED) {
try {
requestResult = api.action("query").param("prop", "revisions").param("rvprop", "timestamp|content").param("titles", contrib.getFilename()).get();
} catch (IOException e) {
Timber.d("Network fuckup on modifications sync!");
continue;
}
Timber.d("Page content is %s", Utils.getStringFromDOM(requestResult.getDocument()));
String pageContent = requestResult.getString("/api/query/pages/page/revisions/rev");
String processedPageContent = sequence.executeModifications(contrib.getFilename(), pageContent);
try {
responseResult = api.action("edit").param("title", contrib.getFilename()).param("token", editToken).param("text", processedPageContent).param("summary", sequence.getEditSummary()).post();
} catch (IOException e) {
Timber.d("Network fuckup on modifications sync!");
continue;
}
Timber.d("Response is %s", Utils.getStringFromDOM(responseResult.getDocument()));
String result = responseResult.getString("/api/edit/@result");
if (!result.equals("Success")) {
// FIXME: Log this somewhere else
Timber.d("Non success result! %s", result);
} else {
sequence.delete();
}
}
allModifications.moveToNext();
}
} finally {
if (contributionsClient != null) {
contributionsClient.release();
}
}
}
Aggregations