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

The following examples show how to use com.google.android.gms.tasks.TaskCompletionSource#getTask() . 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: Utils.java    From firebase-android-sdk with Apache License 2.0 7 votes vote down vote up
/** @return A tasks that is resolved when either of the given tasks is resolved. */
public static <T> Task<T> race(Task<T> t1, Task<T> t2) {
  final TaskCompletionSource<T> result = new TaskCompletionSource<>();
  Continuation<T, Void> continuation =
      new Continuation<T, Void>() {
        @Override
        public Void then(@NonNull Task<T> task) throws Exception {
          if (task.isSuccessful()) {
            result.trySetResult(task.getResult());
          } else {
            result.trySetException(task.getException());
          }
          return null;
        }
      };
  t1.continueWith(continuation);
  t2.continueWith(continuation);
  return result.getTask();
}
 
Example 2
Source File: DataTransportCrashlyticsReportSender.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@NonNull
public Task<CrashlyticsReportWithSessionId> sendReport(
    @NonNull CrashlyticsReportWithSessionId reportWithSessionId) {
  final CrashlyticsReport report = reportWithSessionId.getReport();

  TaskCompletionSource<CrashlyticsReportWithSessionId> tcs = new TaskCompletionSource<>();
  transport.schedule(
      Event.ofUrgent(report),
      error -> {
        if (error != null) {
          tcs.trySetException(error);
          return;
        }
        tcs.trySetResult(reportWithSessionId);
      });
  return tcs.getTask();
}
 
Example 3
Source File: DisplayCallbacksImpl.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Converts an rx maybe to task.
 *
 * <p>Since the semantics of maybe are different from task, we adopt the following rules.
 *
 * <ul>
 *   <li>Maybe that resolves to a value is resolved to a succeeding task
 *   <li>Maybe that resolves to an exception is resolved to a failed task
 *   <li>Maybe that resolves to an error is resolved to a failed task with a wrapped exception
 *   <li>Maybe that resolves to empty is resolved to succeeding Void Task
 * </ul>
 */
private static <T> Task<T> maybeToTask(Maybe<T> maybe, Scheduler scheduler) {
  TaskCompletionSource<T> tcs = new TaskCompletionSource<>();
  Disposable ignoredDisposable =
      maybe
          .doOnSuccess(tcs::setResult)
          .switchIfEmpty(
              Maybe.fromCallable(
                  () -> {
                    tcs.setResult(null);
                    return null;
                  }))
          .onErrorResumeNext(
              throwable -> {
                if (throwable instanceof Exception) {
                  tcs.setException((Exception) throwable);
                } else {
                  tcs.setException(new RuntimeException(throwable));
                }
                return Maybe.empty();
              })
          .subscribeOn(scheduler)
          .subscribe();

  return tcs.getTask();
}
 
Example 4
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 5
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 6
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 7
Source File: FirebaseInstallations.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
private Task<InstallationTokenResult> addGetAuthTokenListener() {
  TaskCompletionSource<InstallationTokenResult> taskCompletionSource =
      new TaskCompletionSource<>();
  StateListener l = new GetAuthTokenListener(utils, taskCompletionSource);
  synchronized (lock) {
    listeners.add(l);
  }
  return taskCompletionSource.getTask();
}
 
Example 8
Source File: FirestoreClient.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a task resolves when all the pending writes at the time when this method is called
 * received server acknowledgement. An acknowledgement can be either acceptance or rejections.
 */
public Task<Void> waitForPendingWrites() {
  this.verifyNotTerminated();

  final TaskCompletionSource<Void> source = new TaskCompletionSource<>();
  asyncQueue.enqueueAndForget(() -> syncEngine.registerPendingWritesTask(source));
  return source.getTask();
}
 
Example 9
Source File: TestUploadHelper.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
public static Task<Void> fileUploadQueuedCancel(
    final StringBuilder builder, final Uri sourcefile) {
  TaskCompletionSource<Void> result = new TaskCompletionSource<>();

  final StorageReference storage = FirebaseStorage.getInstance().getReference("image.jpg");
  StorageMetadata metadata =
      new StorageMetadata.Builder()
          .setContentType("text/plain")
          .setCustomMetadata("myData", "myFoo")
          .build();

  ControllableSchedulerHelper.getInstance().pause();
  final UploadTask task = storage.putFile(sourcefile, metadata);
  final Semaphore semaphore = new Semaphore(0);
  attachListeners(
      builder,
      task,
      null,
      null,
      null,
      null,
      null,
      completedTask -> {
        ControllableSchedulerHelper.getInstance().verifyCallbackThread();
        String statusMessage = "\nonComplete:Success=\n" + completedTask.isSuccessful();
        Log.i(TAG, statusMessage);
        builder.append(statusMessage);
        result.setResult(null);
      });

  // cancel while the task is still queued.
  task.cancel();

  ControllableSchedulerHelper.getInstance().resume();

  return result.getTask();
}
 
Example 10
Source File: TestCommandHelper.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
public static Task<StringBuilder> listAllFiles() {
  final StorageReference reference = FirebaseStorage.getInstance().getReference("largeDirectory");

  TaskCompletionSource<StringBuilder> result = new TaskCompletionSource<>();
  StringBuilder builder = new StringBuilder();

  Task<ListResult> listFiles = reference.listAll();

  listFiles.addOnCompleteListener(
      executor,
      task -> {
        builder.append("\nlistAll:");
        builder.append("\n  onComplete:Success=").append(task.isSuccessful());

        if (task.isSuccessful()) {
          ListResult listResult = task.getResult();
          builder.append("\n  Received Prefixes:");
          for (StorageReference prefix : listResult.getPrefixes()) {
            builder.append("\n    ").append(prefix.getPath());
          }
          builder.append("\n  Received Items:");
          for (StorageReference item : listResult.getItems()) {
            builder.append("\n    ").append(item.getPath());
          }
          Preconditions.checkState(listResult.getPageToken() == null);
        }

        result.setResult(builder);
      });
  return result.getTask();
}
 
Example 11
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 12
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 13
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 14
Source File: StorageReference.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes the object at this {@link StorageReference}.
 *
 * @return A {@link Task} that indicates whether the operation succeeded or failed.
 */
@NonNull
public Task<Void> delete() {
  TaskCompletionSource<Void> pendingResult = new TaskCompletionSource<>();
  StorageTaskScheduler.getInstance().scheduleCommand(new DeleteStorageTask(this, pendingResult));
  return pendingResult.getTask();
}
 
Example 15
Source File: StorageReference.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the metadata associated with this {@link StorageReference}.
 *
 * @param metadata A {@link StorageMetadata} object with the metadata to update.
 * @return a {@link Task} that will return the final {@link StorageMetadata} once the operation is
 *     complete.
 */
@SuppressWarnings("deprecation")
@NonNull
public Task<StorageMetadata> updateMetadata(@NonNull StorageMetadata metadata) {
  Preconditions.checkNotNull(metadata);

  TaskCompletionSource<StorageMetadata> pendingResult = new TaskCompletionSource<>();
  StorageTaskScheduler.getInstance()
      .scheduleCommand(new UpdateMetadataTask(this, pendingResult, metadata));
  return pendingResult.getTask();
}
 
Example 16
Source File: StorageReference.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves metadata associated with an object at this {@link StorageReference}.
 *
 * @return the metadata.
 */
@SuppressWarnings("deprecation")
@NonNull
public Task<StorageMetadata> getMetadata() {
  TaskCompletionSource<StorageMetadata> pendingResult = new TaskCompletionSource<>();
  StorageTaskScheduler.getInstance().scheduleCommand(new GetMetadataTask(this, pendingResult));
  return pendingResult.getTask();
}
 
Example 17
Source File: FirestoreClient.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/** Writes mutations. The returned task will be notified when it's written to the backend. */
public Task<Void> write(final List<Mutation> mutations) {
  this.verifyNotTerminated();
  final TaskCompletionSource<Void> source = new TaskCompletionSource<>();
  asyncQueue.enqueueAndForget(() -> syncEngine.writeMutations(mutations, source));
  return source.getTask();
}
 
Example 18
Source File: Utils.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/** Similar to Tasks.call, but takes a Callable that returns a Task. */
public static <T> Task<T> callTask(Executor executor, Callable<Task<T>> callable) {
  final TaskCompletionSource<T> tcs = new TaskCompletionSource<T>();
  executor.execute(
      new Runnable() {
        @Override
        public void run() {
          try {
            callable
                .call()
                .continueWith(
                    new Continuation<T, Void>() {
                      @Override
                      public Void then(@NonNull Task<T> task) throws Exception {
                        if (task.isSuccessful()) {
                          tcs.setResult(task.getResult());
                        } else {
                          tcs.setException(task.getException());
                        }
                        return null;
                      }
                    });
          } catch (Exception e) {
            tcs.setException(e);
          }
        }
      });
  return tcs.getTask();
}
 
Example 19
Source File: TestCommandHelper.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
public static Task<StringBuilder> testClearMetadata() {

    TaskCompletionSource<StringBuilder> source = new TaskCompletionSource<>();

    StorageMetadata fullMetadata =
        new StorageMetadata.Builder()
            .setCacheControl("cache-control")
            .setContentDisposition("content-disposition")
            .setContentEncoding("gzip")
            .setContentLanguage("de")
            .setCustomMetadata("key", "value")
            .setContentType("content-type")
            .build();

    StorageMetadata emptyMetadata =
        new StorageMetadata.Builder()
            .setCacheControl(null)
            .setContentDisposition(null)
            .setContentEncoding(null)
            .setContentLanguage(null)
            .setCustomMetadata("key", null)
            .setContentType(null)
            .build();

    StorageReference storage = FirebaseStorage.getInstance().getReference("flubbertest.txt");

    updateMetadata(storage, fullMetadata)
        .continueWithTask(
            fullMetadataTask -> {
              updateMetadata(storage, emptyMetadata)
                  .continueWith(
                      (updatedMetadataTask) -> {
                        fullMetadataTask.getResult().append(updatedMetadataTask.getResult());
                        source.setResult(fullMetadataTask.getResult());
                        return null;
                      });
              return null;
            });

    return source.getTask();
  }
 
Example 20
Source File: StorageReference.java    From firebase-android-sdk with Apache License 2.0 3 votes vote down vote up
/**
 * Asynchronously retrieves a long lived download URL with a revokable token. This can be used to
 * share the file with others, but can be revoked by a developer in the Firebase Console if
 * desired.
 *
 * @return The {@link Uri} representing the download URL. You can feed this URL into a {@link
 *     java.net.URL} and download the object via {@link URL#openStream()}.
 */
@SuppressWarnings("deprecation,unused")
@NonNull
public Task<Uri> getDownloadUrl() {
  TaskCompletionSource<Uri> pendingResult = new TaskCompletionSource<>();
  StorageTaskScheduler.getInstance().scheduleCommand(new GetDownloadUrlTask(this, pendingResult));
  return pendingResult.getTask();
}