Search in sources :

Example 11 with Capture

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());
}
Also used : Intent(android.content.Intent) Capture(bolts.Capture) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 12 with Capture

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);
        }
    });
}
Also used : ContentValues(android.content.ContentValues) Continuation(bolts.Continuation) Task(bolts.Task) Capture(bolts.Capture) JSONException(org.json.JSONException)

Example 13 with Capture

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));
}
Also used : Task(bolts.Task) Set(java.util.Set) HashSet(java.util.HashSet) ArrayList(java.util.ArrayList) Capture(bolts.Capture) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashSet(java.util.HashSet) Continuation(bolts.Continuation) JSONException(org.json.JSONException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 14 with Capture

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();
}
Also used : ParseHttpRequest(com.parse.http.ParseHttpRequest) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) ParseHttpRequest(com.parse.http.ParseHttpRequest) IOException(java.io.IOException) Capture(bolts.Capture) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) ParseHttpResponse(com.parse.http.ParseHttpResponse) Interceptor(okhttp3.Interceptor) ParseNetworkInterceptor(com.parse.http.ParseNetworkInterceptor) ParseHttpResponse(com.parse.http.ParseHttpResponse)

Example 15 with Capture

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));
}
Also used : Semaphore(java.util.concurrent.Semaphore) Capture(bolts.Capture) JSONObject(org.json.JSONObject) Test(org.junit.Test)

Aggregations

Capture (bolts.Capture)18 Test (org.junit.Test)12 Semaphore (java.util.concurrent.Semaphore)8 JSONObject (org.json.JSONObject)5 Intent (android.content.Intent)4 Continuation (bolts.Continuation)4 Task (bolts.Task)4 ArrayList (java.util.ArrayList)4 JSONException (org.json.JSONException)4 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 Cursor (android.database.Cursor)2 TaskCompletionSource (bolts.TaskCompletionSource)2 LinkedList (java.util.LinkedList)2 List (java.util.List)2 Matchers.anyString (org.mockito.Matchers.anyString)2 ContentValues (android.content.ContentValues)1 Location (android.location.Location)1 LocationListener (android.location.LocationListener)1 LocationManager (android.location.LocationManager)1 Bundle (android.os.Bundle)1