Java Code Examples for com.google.android.gms.tasks.TaskCompletionSource#setResult()

The following examples show how to use com.google.android.gms.tasks.TaskCompletionSource#setResult() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AsyncQueue.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Initiate the shutdown process. Once called, the only possible way to run `Runnable`s are by
 * holding the `internalExecutor` reference.
 */
private synchronized Task<Void> executeAndInitiateShutdown(Runnable task) {
  if (isShuttingDown()) {
    TaskCompletionSource<Void> source = new TaskCompletionSource<>();
    source.setResult(null);
    return source.getTask();
  }

  // Not shutting down yet, execute and return a Task.
  Task<Void> t =
      executeAndReportResult(
          () -> {
            task.run();
            return null;
          });

  // Mark the initiation of shut down.
  isShuttingDown = true;

  return t;
}
 
Example 2
Source File: SyncEngine.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Takes a snapshot of current mutation queue, and register a user task which will resolve when
 * all those mutations are either accepted or rejected by the server.
 */
public void registerPendingWritesTask(TaskCompletionSource<Void> userTask) {
  if (!remoteStore.canUseNetwork()) {
    Logger.debug(
        TAG,
        "The network is disabled. The task returned by 'awaitPendingWrites()' will not "
            + "complete until the network is enabled.");
  }

  int largestPendingBatchId = localStore.getHighestUnacknowledgedBatchId();

  if (largestPendingBatchId == MutationBatch.UNKNOWN) {
    // Complete the task right away if there is no pending writes at the moment.
    userTask.setResult(null);
    return;
  }

  if (!pendingWritesCallbacks.containsKey(largestPendingBatchId)) {
    pendingWritesCallbacks.put(largestPendingBatchId, new ArrayList());
  }

  pendingWritesCallbacks.get(largestPendingBatchId).add(userTask);
}
 
Example 3
Source File: SyncEngine.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/** Resolves the task corresponding to this write result. */
private void notifyUser(int batchId, @Nullable Status status) {
  Map<Integer, TaskCompletionSource<Void>> userTasks = mutationUserCallbacks.get(currentUser);

  // NOTE: Mutations restored from persistence won't have task completion sources, so it's okay
  // for this (or the task below) to be null.
  if (userTasks != null) {
    Integer boxedBatchId = batchId;
    TaskCompletionSource<Void> userTask = userTasks.get(boxedBatchId);
    if (userTask != null) {
      if (status != null) {
        userTask.setException(Util.exceptionFromStatus(status));
      } else {
        userTask.setResult(null);
      }
      userTasks.remove(boxedBatchId);
    }
  }
}
 
Example 4
Source File: Utilities.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
public static Pair<Task<Void>, DatabaseReference.CompletionListener> wrapOnComplete(
    DatabaseReference.CompletionListener optListener) {
  if (optListener == null) {
    final TaskCompletionSource<Void> source = new TaskCompletionSource<>();
    DatabaseReference.CompletionListener listener =
        new DatabaseReference.CompletionListener() {
          @Override
          public void onComplete(DatabaseError error, DatabaseReference ref) {
            if (error != null) {
              source.setException(error.toException());
            } else {
              source.setResult(null);
            }
          }
        };
    return new Pair<>(source.getTask(), listener);
  } else {
    // If a listener is supplied we do not want to create a Task
    return new Pair<>(null, optListener);
  }
}
 
Example 5
Source File: StorageReference.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * List all items (files) and prefixes (folders) under this StorageReference.
 *
 * <p>This is a helper method for calling {@code list()} repeatedly until there are no more
 * results. Consistency of the result is not guaranteed if objects are inserted or removed while
 * this operation is executing.
 *
 * <p>{@code listAll()} is only available for projects using <a
 * href="https://firebase.google.com/docs/rules/rules-behavior#security_rules_version_2">Firebase
 * Rules Version 2</a>.
 *
 * @throws OutOfMemoryError If there are too many items at this location.
 * @return A {@link Task} that returns all items and prefixes under the current StorageReference.
 */
@NonNull
public Task<ListResult> listAll() {
  TaskCompletionSource<ListResult> pendingResult = new TaskCompletionSource<>();

  List<StorageReference> prefixes = new ArrayList<>();
  List<StorageReference> items = new ArrayList<>();

  Executor executor = StorageTaskScheduler.getInstance().getCommandPoolExecutor();
  Task<ListResult> list = listHelper(/* maxResults= */ null, /* pageToken= */ null);

  Continuation<ListResult, Task<Void>> continuation =
      new Continuation<ListResult, Task<Void>>() {
        @Override
        public Task<Void> then(@NonNull Task<ListResult> currentPage) {
          if (currentPage.isSuccessful()) {
            ListResult result = currentPage.getResult();
            prefixes.addAll(result.getPrefixes());
            items.addAll(result.getItems());

            if (result.getPageToken() != null) {
              Task<ListResult> nextPage =
                  listHelper(/* maxResults= */ null, result.getPageToken());
              nextPage.continueWithTask(executor, this);
            } else {
              pendingResult.setResult(new ListResult(prefixes, items, /* pageToken= */ null));
            }
          } else {
            pendingResult.setException(currentPage.getException());
          }

          return Tasks.forResult(null);
        }
      };

  list.continueWithTask(executor, continuation);

  return pendingResult.getTask();
}
 
Example 6
Source File: TestCommandHelper.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
private static Task<StringBuilder> updateMetadata(
    StorageReference ref, StorageMetadata metadata) {
  TaskCompletionSource<StringBuilder> source = new TaskCompletionSource<>();

  StringBuilder builder = new StringBuilder();

  OnSuccessListener<StringBuilder> verifyCompletion =
      verifiedMetadata -> {
        builder.append(verifiedMetadata);
        source.setResult(builder);
      };

  OnSuccessListener<StorageMetadata> updateCompletion =
      updatedMetadata -> {
        builder.append("Updated Metadata.\n");
        dumpMetadata(builder, updatedMetadata);
        getMetadata(ref).addOnSuccessListener(executor, verifyCompletion);
      };

  OnSuccessListener<StringBuilder> getCompletion =
      originalMetadata -> {
        builder.append(originalMetadata);
        builder.append("Updating Metadata.\n");
        ref.updateMetadata(metadata).addOnSuccessListener(executor, updateCompletion);
      };

  getMetadata(ref).addOnSuccessListener(executor, getCompletion);

  return source.getTask();
}
 
Example 7
Source File: SyncEngine.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/** Resolves tasks waiting for this batch id to get acknowledged by server, if there are any. */
private void resolvePendingWriteTasks(int batchId) {
  if (pendingWritesCallbacks.containsKey(batchId)) {
    for (TaskCompletionSource<Void> task : pendingWritesCallbacks.get(batchId)) {
      task.setResult(null);
    }

    pendingWritesCallbacks.remove(batchId);
  }
}
 
Example 8
Source File: FirebaseContextProvider.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public Task<HttpsCallableContext> getContext() {

  if (tokenProvider == null) {
    TaskCompletionSource<HttpsCallableContext> tcs = new TaskCompletionSource<>();
    tcs.setResult(new HttpsCallableContext(null, instanceId.get().getToken()));
    return tcs.getTask();
  }

  return tokenProvider
      .get()
      .getAccessToken(false)
      .continueWith(
          task -> {
            String authToken = null;
            if (!task.isSuccessful()) {
              Exception exception = task.getException();
              if (exception instanceof FirebaseNoSignedInUserException) {
                // Firebase Auth is linked in, but nobody is signed in, which is fine.
              } else {
                throw exception;
              }
            } else {
              authToken = task.getResult().getToken();
            }

            String instanceIdToken = instanceId.get().getToken();

            return new HttpsCallableContext(authToken, instanceIdToken);
          });
}
 
Example 9
Source File: LineLoginHelper.java    From custom-auth-samples with Apache License 2.0 5 votes vote down vote up
private Task<String> getFirebaseAuthToken(Context context, final String lineAccessToken) {
    final TaskCompletionSource<String> source = new TaskCompletionSource<>();

    // STEP 2: Exchange LINE access token for Firebase Custom Auth token
    HashMap<String, String> validationObject = new HashMap<>();
    validationObject.put("token", lineAccessToken);

    // Exchange LINE Access Token for Firebase Auth Token
    Response.Listener<JSONObject> responseListener = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                String firebaseToken = response.getString("firebase_token");
                Log.d(TAG, "Firebase Token = " + firebaseToken);
                source.setResult(firebaseToken);
            } catch (Exception e) {
                source.setException(e);
            }
        }
    };

    Response.ErrorListener errorListener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, error.toString());
            source.setException(error);
        }
    };

    JsonObjectRequest fbTokenRequest = new JsonObjectRequest(
            Request.Method.POST, mLineAcessscodeVerificationEndpoint,
            new JSONObject(validationObject),
            responseListener, errorListener);

    NetworkSingleton.getInstance(context).addToRequestQueue(fbTokenRequest);

    return source.getTask();
}
 
Example 10
Source File: MainActivity.java    From custom-auth-samples with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param kakaoAccessToken Access token retrieved after successful Kakao Login
 * @return Task object that will call validation server and retrieve firebase token
 */
private Task<String> getFirebaseJwt(final String kakaoAccessToken) {
    final TaskCompletionSource<String> source = new TaskCompletionSource<>();

    RequestQueue queue = Volley.newRequestQueue(this);
    String url = getResources().getString(R.string.validation_server_domain) + "/verifyToken";
    HashMap<String, String> validationObject = new HashMap<>();
    validationObject.put("token", kakaoAccessToken);

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(validationObject), new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                String firebaseToken = response.getString("firebase_token");
                source.setResult(firebaseToken);
            } catch (Exception e) {
                source.setException(e);
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, error.toString());
            source.setException(error);
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            params.put("token", kakaoAccessToken);
            return params;
        }
    };

    queue.add(request);
    return source.getTask();
}
 
Example 11
Source File: SnapshotCoordinator.java    From android-basic-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a task that will complete when given file is closed.  Returns immediately if the
 * file is not open.
 *
 * @param filename - the file name in question.
 */
public Task<Result> waitForClosed(String filename) {
  final TaskCompletionSource<Result> taskCompletionSource = new TaskCompletionSource<>();

  final CountDownLatch latch;
  synchronized (this) {
    latch = opened.get(filename);
  }

  if (latch == null) {
    taskCompletionSource.setResult(null);

    return taskCompletionSource.getTask();
  }

  new AsyncTask<Void, Void, Void>() {
    @Override
    protected Void doInBackground(Void... voids) {
      Result result = new CountDownTask(latch).await();
      taskCompletionSource.setResult(result);

      return null;
    }
  }.execute();

  return taskCompletionSource.getTask();
}
 
Example 12
Source File: SnapshotCoordinator.java    From android-basic-samples with Apache License 2.0 5 votes vote down vote up
@NonNull
private Task<Void> setIsOpeningTask(String filename) {
  TaskCompletionSource<Void> source = new TaskCompletionSource<>();

  if (isAlreadyOpen(filename)) {
    source.setException(new IllegalStateException(filename + " is already open!"));
  } else if (isAlreadyClosing(filename)) {
    source.setException(new IllegalStateException(filename + " is current closing!"));
  } else {
    setIsOpening(filename);
    source.setResult(null);
  }
  return source.getTask();
}
 
Example 13
Source File: SnapshotCoordinator.java    From android-basic-samples with Apache License 2.0 5 votes vote down vote up
@NonNull
private Task<Void> setIsClosingTask(String filename) {
  TaskCompletionSource<Void> source = new TaskCompletionSource<>();

  if (!isAlreadyOpen(filename)) {
    source.setException(new IllegalStateException(filename + " is already closed!"));
  } else if (isAlreadyClosing(filename)) {
    source.setException(new IllegalStateException(filename + " is current closing!"));
  } else {
    setIsClosing(filename);
    source.setResult(null);
  }
  return source.getTask();
}
 
Example 14
Source File: EmptyCredentialsProvider.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
@Override
public Task<String> getToken() {
  TaskCompletionSource<String> source = new TaskCompletionSource<>();
  source.setResult(null);
  return source.getTask();
}