use of bolts.Capture in project facebook-android-sdk by facebook.
the class CallbackManagerImplPowerMockTest method testStaticCallbackExecuted.
@Test
public void testStaticCallbackExecuted() {
final Capture<Boolean> capture = new Capture(false);
final CallbackManagerImpl callbackManagerImpl = new CallbackManagerImpl();
callbackManagerImpl.registerStaticCallback(CallbackManagerImpl.RequestCodeOffset.Login.toRequestCode(), new CallbackManagerImpl.Callback() {
@Override
public boolean onActivityResult(int resultCode, Intent data) {
capture.set(true);
return true;
}
});
callbackManagerImpl.onActivityResult(FacebookSdk.getCallbackRequestCodeOffset(), 1, new Intent());
assertTrue(capture.get());
}
use of bolts.Capture in project Parse-SDK-Android by ParsePlatform.
the class OfflineStore method saveLocallyAsync.
/**
* Stores a single object in the local database. If the object is a pointer, isn't dirty, and has
* an objectId already, it may not be saved, since it would provide no useful data.
*
* @param object
* The object to save.
* @param db
* A database connection to use.
*/
private Task<Void> saveLocallyAsync(final String key, final ParseObject object, final ParseSQLiteDatabase db) {
// If this is just a clean, unfetched pointer known to Parse, then there is nothing to save.
if (object.getObjectId() != null && !object.isDataAvailable() && !object.hasChanges() && !object.hasOutstandingOperations()) {
return Task.forResult(null);
}
final Capture<String> uuidCapture = new Capture<>();
// Make sure we have a UUID for the object to be saved.
return getOrCreateUUIDAsync(object, db).onSuccessTask(new Continuation<String, Task<Void>>() {
@Override
public Task<Void> then(Task<String> task) throws Exception {
String uuid = task.getResult();
uuidCapture.set(uuid);
return updateDataForObjectAsync(uuid, object, db);
}
}).onSuccessTask(new Continuation<Void, Task<Void>>() {
@Override
public Task<Void> then(Task<Void> task) throws Exception {
final ContentValues values = new ContentValues();
values.put(OfflineSQLiteOpenHelper.KEY_KEY, key);
values.put(OfflineSQLiteOpenHelper.KEY_UUID, uuidCapture.get());
return db.insertWithOnConflict(OfflineSQLiteOpenHelper.TABLE_DEPENDENCIES, values, SQLiteDatabase.CONFLICT_IGNORE);
}
});
}
use of bolts.Capture in project Parse-SDK-Android by ParsePlatform.
the class ParseObject method deepSaveAsync.
/**
* This saves all of the objects and files reachable from the given object. It does its work in
* multiple waves, saving as many as possible in each wave. If there's ever an error, it just
* gives up, sets error, and returns NO.
*/
private static Task<Void> deepSaveAsync(final Object object, final String sessionToken) {
Set<ParseObject> objects = new HashSet<>();
Set<ParseFile> files = new HashSet<>();
collectDirtyChildren(object, objects, files);
// This has to happen separately from everything else because ParseUser.save() is
// special-cased to work for lazy users, but new users can't be created by
// ParseMultiCommand's regular save.
Set<ParseUser> users = new HashSet<>();
for (ParseObject o : objects) {
if (o instanceof ParseUser) {
ParseUser user = (ParseUser) o;
if (user.isLazy()) {
users.add((ParseUser) o);
}
}
}
objects.removeAll(users);
// objects will need to wait for files to be complete since they may be nested children.
final AtomicBoolean filesComplete = new AtomicBoolean(false);
List<Task<Void>> tasks = new ArrayList<>();
for (ParseFile file : files) {
tasks.add(file.saveAsync(sessionToken, null, null));
}
Task<Void> filesTask = Task.whenAll(tasks).continueWith(new Continuation<Void, Void>() {
@Override
public Void then(Task<Void> task) throws Exception {
filesComplete.set(true);
return null;
}
});
// objects will need to wait for users to be complete since they may be nested children.
final AtomicBoolean usersComplete = new AtomicBoolean(false);
tasks = new ArrayList<>();
for (final ParseUser user : users) {
tasks.add(user.saveAsync(sessionToken));
}
Task<Void> usersTask = Task.whenAll(tasks).continueWith(new Continuation<Void, Void>() {
@Override
public Void then(Task<Void> task) throws Exception {
usersComplete.set(true);
return null;
}
});
final Capture<Set<ParseObject>> remaining = new Capture<>(objects);
Task<Void> objectsTask = Task.forResult(null).continueWhile(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return remaining.get().size() > 0;
}
}, new Continuation<Void, Task<Void>>() {
@Override
public Task<Void> then(Task<Void> task) throws Exception {
// Partition the objects into two sets: those that can be save immediately,
// and those that rely on other objects to be created first.
final List<ParseObject> current = new ArrayList<>();
final Set<ParseObject> nextBatch = new HashSet<>();
for (ParseObject obj : remaining.get()) {
if (obj.canBeSerialized()) {
current.add(obj);
} else {
nextBatch.add(obj);
}
}
remaining.set(nextBatch);
if (current.size() == 0 && filesComplete.get() && usersComplete.get()) {
// exception instead of an infinite loop.
throw new RuntimeException("Unable to save a ParseObject with a relation to a cycle.");
}
// Package all save commands together
if (current.size() == 0) {
return Task.forResult(null);
}
return enqueueForAll(current, new Continuation<Void, Task<Void>>() {
@Override
public Task<Void> then(Task<Void> toAwait) throws Exception {
return saveAllAsync(current, sessionToken, toAwait);
}
});
}
});
return Task.whenAll(Arrays.asList(filesTask, usersTask, objectsTask));
}
use of bolts.Capture in project Parse-SDK-Android by ParsePlatform.
the class ParseOkHttpClient method addExternalInterceptor.
/**
* For OKHttpClient, since it does not expose any interface for us to check the raw response
* stream, we have to use OKHttp networkInterceptors. Instead of using our own interceptor list,
* we use OKHttp inner interceptor list.
* @param parseNetworkInterceptor
*/
@Override
/* package */
void addExternalInterceptor(final ParseNetworkInterceptor parseNetworkInterceptor) {
OkHttpClient.Builder builder = okHttpClient.newBuilder();
builder.networkInterceptors().add(new Interceptor() {
@Override
public Response intercept(final Chain okHttpChain) throws IOException {
Request okHttpRequest = okHttpChain.request();
// Transfer OkHttpRequest to ParseHttpRequest
final ParseHttpRequest parseRequest = getParseHttpRequest(okHttpRequest);
// Capture OkHttpResponse
final Capture<Response> okHttpResponseCapture = new Capture<>();
final ParseHttpResponse parseResponse = parseNetworkInterceptor.intercept(new ParseNetworkInterceptor.Chain() {
@Override
public ParseHttpRequest getRequest() {
return parseRequest;
}
@Override
public ParseHttpResponse proceed(ParseHttpRequest parseRequest) throws IOException {
// Use OKHttpClient to send request
Request okHttpRequest = ParseOkHttpClient.this.getRequest(parseRequest);
Response okHttpResponse = okHttpChain.proceed(okHttpRequest);
okHttpResponseCapture.set(okHttpResponse);
return getResponse(okHttpResponse);
}
});
final Response okHttpResponse = okHttpResponseCapture.get();
// Ideally we should build newOkHttpResponse only based on parseResponse, however
// ParseHttpResponse does not have all the info we need to build the newOkHttpResponse, so
// we rely on the okHttpResponse to generate the builder and change the necessary info
// inside
Response.Builder newOkHttpResponseBuilder = okHttpResponse.newBuilder();
// Set status
newOkHttpResponseBuilder.code(parseResponse.getStatusCode()).message(parseResponse.getReasonPhrase());
// Set headers
if (parseResponse.getAllHeaders() != null) {
for (Map.Entry<String, String> entry : parseResponse.getAllHeaders().entrySet()) {
newOkHttpResponseBuilder.header(entry.getKey(), entry.getValue());
}
}
// Set body
newOkHttpResponseBuilder.body(new ResponseBody() {
@Override
public MediaType contentType() {
if (parseResponse.getContentType() == null) {
return null;
}
return MediaType.parse(parseResponse.getContentType());
}
@Override
public long contentLength() {
return parseResponse.getTotalSize();
}
@Override
public BufferedSource source() {
// interceptor.
if (parseResponse.getContent() == null) {
return null;
}
return Okio.buffer(Okio.source(parseResponse.getContent()));
}
});
return newOkHttpResponseBuilder.build();
}
});
okHttpClient = builder.build();
}
use of bolts.Capture in project Parse-SDK-Android by ParsePlatform.
the class ParsePushTest method testSendMessageInBackgroundWithCallback.
@Test
public void testSendMessageInBackgroundWithCallback() throws Exception {
// Mock controller
ParsePushController controller = mock(ParsePushController.class);
when(controller.sendInBackground(any(ParsePush.State.class), anyString())).thenReturn(Task.<Void>forResult(null));
ParseCorePlugins.getInstance().registerPushController(controller);
// Make sample ParsePush data and call method
ParseQuery<ParseInstallation> query = ParseInstallation.getQuery();
query.getBuilder().whereEqualTo("foo", "bar");
final Semaphore done = new Semaphore(0);
final Capture<Exception> exceptionCapture = new Capture<>();
ParsePush.sendMessageInBackground("test", query, new SendCallback() {
@Override
public void done(ParseException e) {
exceptionCapture.set(e);
done.release();
}
});
// Make sure controller is executed and state parameter is correct
assertNull(exceptionCapture.get());
assertTrue(done.tryAcquire(1, 10, TimeUnit.SECONDS));
ArgumentCaptor<ParsePush.State> stateCaptor = ArgumentCaptor.forClass(ParsePush.State.class);
verify(controller, times(1)).sendInBackground(stateCaptor.capture(), anyString());
ParsePush.State state = stateCaptor.getValue();
// Verify query state
ParseQuery.State<ParseInstallation> queryState = state.queryState();
JSONObject queryStateJson = queryState.toJSON(PointerEncoder.get());
assertEquals("bar", queryStateJson.getJSONObject("where").getString("foo"));
// Verify message
assertEquals("test", state.data().getString(ParsePush.KEY_DATA_MESSAGE));
}
Aggregations