use of bolts.Task in project Bolts-Java by BoltsFramework.
the class TaskTest method testContinueWhileAsync.
public void testContinueWhileAsync() {
final AtomicInteger count = new AtomicInteger(0);
runTaskTest(new Callable<Task<?>>() {
public Task<?> call() throws Exception {
return Task.forResult(null).continueWhile(new Callable<Boolean>() {
public Boolean call() throws Exception {
return count.get() < 10;
}
}, new Continuation<Void, Task<Void>>() {
public Task<Void> then(Task<Void> task) throws Exception {
count.incrementAndGet();
return null;
}
}, Executors.newCachedThreadPool()).continueWith(new Continuation<Void, Void>() {
public Void then(Task<Void> task) throws Exception {
assertEquals(10, count.get());
return null;
}
});
}
});
}
use of bolts.Task in project facebook-android-sdk by facebook.
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;
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));
GraphRequest appLinkRequest = new GraphRequest(// token
AccessToken.getCurrentAccessToken(), /* Access Token */
"", /* Graph path */
appLinkRequestParameters, /* Query parameters */
null, /* HttpMethod */
new GraphRequest.Callback() {
/* Callback */
@Override
public void onCompleted(GraphResponse response) {
FacebookRequestError error = response.getError();
if (error != null) {
taskCompletionSource.setError(error.getException());
return;
}
JSONObject responseJson = response.getJSONObject();
if (responseJson == null) {
taskCompletionSource.setResult(appLinkResults);
return;
}
for (Uri uri : urisToRequest) {
String uriString = uri.toString();
if (!responseJson.has(uriString)) {
continue;
}
JSONObject urlData;
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();
}
use of bolts.Task in project facebook-android-sdk by facebook.
the class FacebookAppLinkResolverTests method testSingleUrl.
public void testSingleUrl() {
String testUrlString = "https://fb.me/732873156764191";
Uri testUrl = Uri.parse(testUrlString);
Uri testWebUri = Uri.parse("http://www.facebook.com/");
ArrayList<AppLink.Target> testTargets = new ArrayList<AppLink.Target>();
testTargets.add(new AppLink.Target("com.myapp", null, Uri.parse("myapp://3"), "my app"));
testTargets.add(new AppLink.Target("com.myapp-test", null, Uri.parse("myapp-test://4"), "my test app"));
try {
executeResolverOnBlockerThread(new FacebookAppLinkResolver(), testUrl);
getTestBlocker().waitForSignals(1);
assertNotNull(resolveTask);
Task<AppLink> singleUrlResolveTask = (Task<AppLink>) resolveTask;
assertTrue(singleUrlResolveTask.isCompleted() && !singleUrlResolveTask.isCancelled() && !singleUrlResolveTask.isFaulted());
AppLink appLink = singleUrlResolveTask.getResult();
assertEquals(appLink.getSourceUrl(), testUrl);
assertEquals(appLink.getWebUrl(), testWebUri);
assertTrue(targetListsAreEqual(appLink.getTargets(), testTargets));
} catch (Exception e) {
// Forcing the test to fail with details
assertNull(e);
}
}
use of bolts.Task in project facebook-android-sdk by facebook.
the class FacebookAppLinkResolverTests method executeResolverOnBlockerThread.
public void executeResolverOnBlockerThread(final FacebookAppLinkResolver resolver, final Uri testUrl) {
final TestBlocker blocker = getTestBlocker();
Runnable runnable = new Runnable() {
public void run() {
try {
resolveTask = resolver.getAppLinkFromUrlInBackground(testUrl);
resolveTask.continueWith(new Continuation() {
@Override
public Object then(Task task) throws Exception {
// Once the task is complete, unblock the test thread, so it can inspect for errors/results.
blocker.signal();
return null;
}
});
} catch (Exception e) {
// Get back to the test case if there was an uncaught exception
blocker.signal();
}
}
};
Handler handler = new Handler(blocker.getLooper());
handler.post(runnable);
}
use of bolts.Task in project Parse-SDK-Android by ParsePlatform.
the class ParseCommandCache method maybeRunAllCommandsNow.
/**
* Attempts to run every command in the disk queue in order, synchronously. If there is no network
* connection, returns immediately without doing anything. If there is supposedly a connection,
* but parse can't be reached, waits timeoutRetryWaitSeconds before retrying up to
* retriesRemaining times. Blocks until either there's a connection, or the retries are exhausted.
* If any command fails, just deletes it and moves on to the next one.
*/
private void maybeRunAllCommandsNow(int retriesRemaining) {
synchronized (lock) {
unprocessedCommandsExist = false;
if (!isConnected()) {
// There's no way to do work when there's no network connection.
return;
}
String[] fileNames = cachePath.list();
if (fileNames == null || fileNames.length == 0) {
return;
}
Arrays.sort(fileNames);
for (String fileName : fileNames) {
final File file = new File(cachePath, fileName);
// Read one command from the cache.
JSONObject json;
try {
json = ParseFileUtils.readFileToJSONObject(file);
} catch (FileNotFoundException e) {
// This shouldn't really be possible.
if (Parse.LOG_LEVEL_ERROR >= Parse.getLogLevel()) {
log.log(Level.SEVERE, "File disappeared from cache while being read.", e);
}
continue;
} catch (IOException e) {
if (Parse.LOG_LEVEL_ERROR >= Parse.getLogLevel()) {
log.log(Level.SEVERE, "Unable to read contents of file in cache.", e);
}
removeFile(file);
continue;
} catch (JSONException e) {
if (Parse.LOG_LEVEL_ERROR >= Parse.getLogLevel()) {
log.log(Level.SEVERE, "Error parsing JSON found in cache.", e);
}
removeFile(file);
continue;
}
// Convert the command from a string.
final ParseRESTCommand command;
final TaskCompletionSource<JSONObject> tcs = pendingTasks.containsKey(file) ? pendingTasks.get(file) : null;
try {
command = commandFromJSON(json);
} catch (JSONException e) {
if (Parse.LOG_LEVEL_ERROR >= Parse.getLogLevel()) {
log.log(Level.SEVERE, "Unable to create ParseCommand from JSON.", e);
}
removeFile(file);
continue;
}
try {
Task<JSONObject> commandTask;
if (command == null) {
commandTask = Task.forResult(null);
if (tcs != null) {
tcs.setResult(null);
}
notifyTestHelper(TestHelper.COMMAND_OLD_FORMAT_DISCARDED);
} else {
commandTask = command.executeAsync(httpClient).continueWithTask(new Continuation<JSONObject, Task<JSONObject>>() {
@Override
public Task<JSONObject> then(Task<JSONObject> task) throws Exception {
String localId = command.getLocalId();
Exception error = task.getError();
if (error != null) {
if (error instanceof ParseException && ((ParseException) error).getCode() == ParseException.CONNECTION_FAILED) {
// do nothing
} else {
if (tcs != null) {
tcs.setError(error);
}
}
return task;
}
JSONObject json = task.getResult();
if (tcs != null) {
tcs.setResult(json);
} else if (localId != null) {
// If this command created a new objectId, add it to the map.
String objectId = json.optString("objectId", null);
if (objectId != null) {
ParseCorePlugins.getInstance().getLocalIdManager().setObjectId(localId, objectId);
}
}
return task;
}
});
}
waitForTaskWithoutLock(commandTask);
if (tcs != null) {
waitForTaskWithoutLock(tcs.getTask());
}
// The command succeeded. Remove it from the cache.
removeFile(file);
notifyTestHelper(TestHelper.COMMAND_SUCCESSFUL);
} catch (ParseException e) {
if (e.getCode() == ParseException.CONNECTION_FAILED) {
if (retriesRemaining > 0) {
// Parse. Wait N minutes, or until we get signaled again before doing anything else.
if (Parse.LOG_LEVEL_INFO >= Parse.getLogLevel()) {
log.info("Network timeout in command cache. Waiting for " + timeoutRetryWaitSeconds + " seconds and then retrying " + retriesRemaining + " times.");
}
long currentTime = System.currentTimeMillis();
long waitUntil = currentTime + (long) (timeoutRetryWaitSeconds * 1000);
while (currentTime < waitUntil) {
// or should stop, just quit.
if (!isConnected() || shouldStop) {
if (Parse.LOG_LEVEL_INFO >= Parse.getLogLevel()) {
log.info("Aborting wait because runEventually thread should stop.");
}
return;
}
try {
lock.wait(waitUntil - currentTime);
} catch (InterruptedException ie) {
shouldStop = true;
}
currentTime = System.currentTimeMillis();
if (currentTime < (waitUntil - (long) (timeoutRetryWaitSeconds * 1000))) {
// This situation should be impossible, so it must mean the clock changed.
currentTime = (waitUntil - (long) (timeoutRetryWaitSeconds * 1000));
}
}
maybeRunAllCommandsNow(retriesRemaining - 1);
} else {
setConnected(false);
notifyTestHelper(TestHelper.NETWORK_DOWN);
}
} else {
if (Parse.LOG_LEVEL_ERROR >= Parse.getLogLevel()) {
log.log(Level.SEVERE, "Failed to run command.", e);
}
// Delete the command from the cache, even though it failed.
// Otherwise, we'll just keep trying it forever.
removeFile(file);
notifyTestHelper(TestHelper.COMMAND_FAILED, e);
}
}
}
}
}
Aggregations