Search in sources :

Example 11 with Task

use of bolts.Task in project phonegap-facebook-plugin by Wizcorp.

the class FacebookAppLinkResolver method getAppLinkFromUrlsInBackground.

/**
     * Asynchronously resolves App Link data for multiple Urls
     *
     * @param uris A list of Uri objects to resolve into App Links
     * @return A Task that, when successful, will return a Map of Uri->AppLink for each Uri that was successfully
     * resolved into an App Link. Uris that could not be resolved into App Links will not be present in the Map.
     * In the case of general server errors, the task will be completed with the corresponding error.
     */
public Task<Map<Uri, AppLink>> getAppLinkFromUrlsInBackground(List<Uri> uris) {
    final Map<Uri, AppLink> appLinkResults = new HashMap<Uri, AppLink>();
    final HashSet<Uri> urisToRequest = new HashSet<Uri>();
    StringBuilder graphRequestFields = new StringBuilder();
    for (Uri uri : uris) {
        AppLink appLink = null;
        synchronized (cachedAppLinks) {
            appLink = cachedAppLinks.get(uri);
        }
        if (appLink != null) {
            appLinkResults.put(uri, appLink);
        } else {
            if (!urisToRequest.isEmpty()) {
                graphRequestFields.append(',');
            }
            graphRequestFields.append(uri.toString());
            urisToRequest.add(uri);
        }
    }
    if (urisToRequest.isEmpty()) {
        return Task.forResult(appLinkResults);
    }
    final Task<Map<Uri, AppLink>>.TaskCompletionSource<Map<Uri, AppLink>> taskCompletionSource = Task.create();
    Bundle appLinkRequestParameters = new Bundle();
    appLinkRequestParameters.putString("ids", graphRequestFields.toString());
    appLinkRequestParameters.putString("fields", String.format("%s.fields(%s,%s)", APP_LINK_KEY, APP_LINK_ANDROID_TARGET_KEY, APP_LINK_WEB_TARGET_KEY));
    Request appLinkRequest = new Request(null, /* Session */
    "", /* Graph path */
    appLinkRequestParameters, /* Query parameters */
    null, /* HttpMethod */
    new Request.Callback() {

        /* Callback */
        @Override
        public void onCompleted(Response response) {
            FacebookRequestError error = response.getError();
            if (error != null) {
                taskCompletionSource.setError(error.getException());
                return;
            }
            GraphObject responseObject = response.getGraphObject();
            JSONObject responseJson = responseObject != null ? responseObject.getInnerJSONObject() : null;
            if (responseJson == null) {
                taskCompletionSource.setResult(appLinkResults);
                return;
            }
            for (Uri uri : urisToRequest) {
                String uriString = uri.toString();
                if (!responseJson.has(uriString)) {
                    continue;
                }
                JSONObject urlData = null;
                try {
                    urlData = responseJson.getJSONObject(uri.toString());
                    JSONObject appLinkData = urlData.getJSONObject(APP_LINK_KEY);
                    JSONArray rawTargets = appLinkData.getJSONArray(APP_LINK_ANDROID_TARGET_KEY);
                    int targetsCount = rawTargets.length();
                    List<AppLink.Target> targets = new ArrayList<AppLink.Target>(targetsCount);
                    for (int i = 0; i < targetsCount; i++) {
                        AppLink.Target target = getAndroidTargetFromJson(rawTargets.getJSONObject(i));
                        if (target != null) {
                            targets.add(target);
                        }
                    }
                    Uri webFallbackUrl = getWebFallbackUriFromJson(uri, appLinkData);
                    AppLink appLink = new AppLink(uri, targets, webFallbackUrl);
                    appLinkResults.put(uri, appLink);
                    synchronized (cachedAppLinks) {
                        cachedAppLinks.put(uri, appLink);
                    }
                } catch (JSONException e) {
                    // The data for this uri was missing or badly formed.
                    continue;
                }
            }
            taskCompletionSource.setResult(appLinkResults);
        }
    });
    appLinkRequest.executeAsync();
    return taskCompletionSource.getTask();
}
Also used : Task(bolts.Task) Bundle(android.os.Bundle) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) GraphObject(com.facebook.model.GraphObject) Uri(android.net.Uri) JSONObject(org.json.JSONObject) AppLink(bolts.AppLink)

Example 12 with Task

use of bolts.Task in project facebook-api-android-maven by avianey.

the class FacebookAppLinkResolver method getAppLinkFromUrlsInBackground.

/**
     * Asynchronously resolves App Link data for multiple Urls
     *
     * @param uris A list of Uri objects to resolve into App Links
     * @return A Task that, when successful, will return a Map of Uri->AppLink for each Uri that was successfully
     * resolved into an App Link. Uris that could not be resolved into App Links will not be present in the Map.
     * In the case of general server errors, the task will be completed with the corresponding error.
     */
public Task<Map<Uri, AppLink>> getAppLinkFromUrlsInBackground(List<Uri> uris) {
    final Map<Uri, AppLink> appLinkResults = new HashMap<Uri, AppLink>();
    final HashSet<Uri> urisToRequest = new HashSet<Uri>();
    StringBuilder graphRequestFields = new StringBuilder();
    for (Uri uri : uris) {
        AppLink appLink = null;
        synchronized (cachedAppLinks) {
            appLink = cachedAppLinks.get(uri);
        }
        if (appLink != null) {
            appLinkResults.put(uri, appLink);
        } else {
            if (!urisToRequest.isEmpty()) {
                graphRequestFields.append(',');
            }
            graphRequestFields.append(uri.toString());
            urisToRequest.add(uri);
        }
    }
    if (urisToRequest.isEmpty()) {
        return Task.forResult(appLinkResults);
    }
    final Task<Map<Uri, AppLink>>.TaskCompletionSource<Map<Uri, AppLink>> taskCompletionSource = Task.create();
    Bundle appLinkRequestParameters = new Bundle();
    appLinkRequestParameters.putString("ids", graphRequestFields.toString());
    appLinkRequestParameters.putString("fields", String.format("%s.fields(%s,%s)", APP_LINK_KEY, APP_LINK_ANDROID_TARGET_KEY, APP_LINK_WEB_TARGET_KEY));
    Request appLinkRequest = new Request(null, /* Session */
    "", /* Graph path */
    appLinkRequestParameters, /* Query parameters */
    null, /* HttpMethod */
    new Request.Callback() {

        /* Callback */
        @Override
        public void onCompleted(Response response) {
            FacebookRequestError error = response.getError();
            if (error != null) {
                taskCompletionSource.setError(error.getException());
                return;
            }
            GraphObject responseObject = response.getGraphObject();
            JSONObject responseJson = responseObject != null ? responseObject.getInnerJSONObject() : null;
            if (responseJson == null) {
                taskCompletionSource.setResult(appLinkResults);
                return;
            }
            for (Uri uri : urisToRequest) {
                String uriString = uri.toString();
                if (!responseJson.has(uriString)) {
                    continue;
                }
                JSONObject urlData = null;
                try {
                    urlData = responseJson.getJSONObject(uri.toString());
                    JSONObject appLinkData = urlData.getJSONObject(APP_LINK_KEY);
                    JSONArray rawTargets = appLinkData.getJSONArray(APP_LINK_ANDROID_TARGET_KEY);
                    int targetsCount = rawTargets.length();
                    List<AppLink.Target> targets = new ArrayList<AppLink.Target>(targetsCount);
                    for (int i = 0; i < targetsCount; i++) {
                        AppLink.Target target = getAndroidTargetFromJson(rawTargets.getJSONObject(i));
                        if (target != null) {
                            targets.add(target);
                        }
                    }
                    Uri webFallbackUrl = getWebFallbackUriFromJson(uri, appLinkData);
                    AppLink appLink = new AppLink(uri, targets, webFallbackUrl);
                    appLinkResults.put(uri, appLink);
                    synchronized (cachedAppLinks) {
                        cachedAppLinks.put(uri, appLink);
                    }
                } catch (JSONException e) {
                    // The data for this uri was missing or badly formed.
                    continue;
                }
            }
            taskCompletionSource.setResult(appLinkResults);
        }
    });
    appLinkRequest.executeAsync();
    return taskCompletionSource.getTask();
}
Also used : Task(bolts.Task) Bundle(android.os.Bundle) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) GraphObject(com.facebook.model.GraphObject) Uri(android.net.Uri) JSONObject(org.json.JSONObject) AppLink(bolts.AppLink)

Example 13 with Task

use of bolts.Task in project facebook-android-sdk by facebook.

the class FacebookAppLinkResolverTests method testUrlWithNoAppLinkData.

public void testUrlWithNoAppLinkData() {
    String testNoAppLinkUrlString = "https://fb.me/732873156764191_no_app_link";
    Uri testNoAppLinkUrl = Uri.parse(testNoAppLinkUrlString);
    try {
        executeResolverOnBlockerThread(new FacebookAppLinkResolver(), testNoAppLinkUrl);
        getTestBlocker().waitForSignals(1);
        assertNotNull(resolveTask);
        Task<AppLink> singleUrlResolveTask = (Task<AppLink>) resolveTask;
        assertTrue(singleUrlResolveTask.isCompleted() && !singleUrlResolveTask.isCancelled() && !singleUrlResolveTask.isFaulted());
        AppLink appLink = singleUrlResolveTask.getResult();
        assertNull(appLink);
    } catch (Exception e) {
        // Forcing the test to fail with details
        assertNull(e);
    }
}
Also used : Task(bolts.Task) FacebookAppLinkResolver(com.facebook.applinks.FacebookAppLinkResolver) AppLink(bolts.AppLink) Uri(android.net.Uri)

Example 14 with Task

use of bolts.Task in project fresco by facebook.

the class ImagePipeline method isInDiskCache.

/**
   * Returns whether the image is stored in the disk cache.
   *
   * @param imageRequest the imageRequest for the image to be looked up.
   * @return true if the image was found in the disk cache, false otherwise.
   */
public DataSource<Boolean> isInDiskCache(final ImageRequest imageRequest) {
    final CacheKey cacheKey = mCacheKeyFactory.getEncodedCacheKey(imageRequest, null);
    final SimpleDataSource<Boolean> dataSource = SimpleDataSource.create();
    mMainBufferedDiskCache.contains(cacheKey).continueWithTask(new Continuation<Boolean, Task<Boolean>>() {

        @Override
        public Task<Boolean> then(Task<Boolean> task) throws Exception {
            if (!task.isCancelled() && !task.isFaulted() && task.getResult()) {
                return Task.forResult(true);
            }
            return mSmallImageBufferedDiskCache.contains(cacheKey);
        }
    }).continueWith(new Continuation<Boolean, Void>() {

        @Override
        public Void then(Task<Boolean> task) throws Exception {
            dataSource.setResult(!task.isCancelled() && !task.isFaulted() && task.getResult());
            return null;
        }
    });
    return dataSource;
}
Also used : Continuation(bolts.Continuation) Task(bolts.Task) CacheKey(com.facebook.cache.common.CacheKey) CancellationException(java.util.concurrent.CancellationException)

Example 15 with Task

use of bolts.Task in project fresco by facebook.

the class SplitCachesByImageSizeDiskCachePolicy method createAndStartCacheReadTask.

@Override
public Task<EncodedImage> createAndStartCacheReadTask(ImageRequest imageRequest, Object callerContext, final AtomicBoolean isCancelled) {
    final CacheKey cacheKey = mCacheKeyFactory.getEncodedCacheKey(imageRequest, callerContext);
    final boolean alreadyInSmall = mSmallImageBufferedDiskCache.containsSync(cacheKey);
    final boolean alreadyInMain = mDefaultBufferedDiskCache.containsSync(cacheKey);
    final BufferedDiskCache firstCache;
    final BufferedDiskCache secondCache;
    if (alreadyInSmall || !alreadyInMain) {
        firstCache = mSmallImageBufferedDiskCache;
        secondCache = mDefaultBufferedDiskCache;
    } else {
        firstCache = mDefaultBufferedDiskCache;
        secondCache = mSmallImageBufferedDiskCache;
    }
    return firstCache.get(cacheKey, isCancelled).continueWithTask(new Continuation<EncodedImage, Task<EncodedImage>>() {

        @Override
        public Task<EncodedImage> then(Task<EncodedImage> task) throws Exception {
            if (isTaskCancelled(task) || (!task.isFaulted() && task.getResult() != null)) {
                return task;
            }
            return secondCache.get(cacheKey, isCancelled);
        }
    });
}
Also used : Task(bolts.Task) EncodedImage(com.facebook.imagepipeline.image.EncodedImage) CacheKey(com.facebook.cache.common.CacheKey) CancellationException(java.util.concurrent.CancellationException)

Aggregations

Task (bolts.Task)46 JSONObject (org.json.JSONObject)27 Continuation (bolts.Continuation)23 JSONException (org.json.JSONException)20 ArrayList (java.util.ArrayList)15 JSONArray (org.json.JSONArray)14 RCLog (chat.rocket.android.log.RCLog)11 TaskCompletionSource (bolts.TaskCompletionSource)10 List (java.util.List)8 Context (android.content.Context)7 Uri (android.net.Uri)7 RealmHelper (chat.rocket.persistence.realm.RealmHelper)7 CancellationException (java.util.concurrent.CancellationException)7 TextUtils (android.text.TextUtils)6 SyncState (chat.rocket.core.SyncState)6 IOException (java.io.IOException)6 NonNull (android.support.annotation.NonNull)5 Nullable (android.support.annotation.Nullable)5 AggregateException (bolts.AggregateException)5 AppLink (bolts.AppLink)5