diff --git a/app/src/main/java/com/firebase/uidemo/auth/AnonymousUpgradeActivity.java b/app/src/main/java/com/firebase/uidemo/auth/AnonymousUpgradeActivity.java index 41a0b308b..4453c4cbd 100644 --- a/app/src/main/java/com/firebase/uidemo/auth/AnonymousUpgradeActivity.java +++ b/app/src/main/java/com/firebase/uidemo/auth/AnonymousUpgradeActivity.java @@ -57,48 +57,22 @@ protected void onCreate(@Nullable Bundle savedInstanceState) { handleSignInResult(ErrorCodes.ANONYMOUS_UPGRADE_MERGE_CONFLICT, response); } - mBinding.anonSignIn.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - signInAnonymously(); - } - }); - - mBinding.beginFlow.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - startAuthUI(); - } - }); - - mBinding.resolveMerge.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - resolveMerge(); - } - }); - - mBinding.signOut.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - signOut(); - } - }); + mBinding.anonSignIn.setOnClickListener(view -> signInAnonymously()); + mBinding.beginFlow.setOnClickListener(view -> startAuthUI()); + mBinding.resolveMerge.setOnClickListener(view -> resolveMerge()); + mBinding.signOut.setOnClickListener(view -> signOut()); } public void signInAnonymously() { FirebaseAuth.getInstance().signInAnonymously() - .addOnCompleteListener(this, new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - updateUI(); - - if (task.isSuccessful()) { - setStatus("Signed in anonymously as user " - + getUserIdentifier(task.getResult().getUser())); - } else { - setStatus("Anonymous sign in failed."); - } + .addOnCompleteListener(this, task -> { + updateUI(); + + if (task.isSuccessful()) { + setStatus("Signed in anonymously as user " + + getUserIdentifier(task.getResult().getUser())); + } else { + setStatus("Anonymous sign in failed."); } }); } @@ -122,31 +96,25 @@ public void resolveMerge() { // TODO: Show how to do good data moving FirebaseAuth.getInstance().signInWithCredential(mPendingCredential) - .addOnCompleteListener(this, new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - mPendingCredential = null; - updateUI(); - - if (task.isSuccessful()) { - setStatus("Signed in as " + getUserIdentifier(task.getResult() - .getUser())); - } else { - Log.w(TAG, "Merge failed", task.getException()); - setStatus("Failed to resolve merge conflict, see logs."); - } + .addOnCompleteListener(this, task -> { + mPendingCredential = null; + updateUI(); + + if (task.isSuccessful()) { + setStatus("Signed in as " + getUserIdentifier(task.getResult() + .getUser())); + } else { + Log.w(TAG, "Merge failed", task.getException()); + setStatus("Failed to resolve merge conflict, see logs."); } }); } public void signOut() { AuthUI.getInstance().signOut(this) - .addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - setStatus(null); - updateUI(); - } + .addOnCompleteListener(task -> { + setStatus(null); + updateUI(); }); } diff --git a/app/src/main/java/com/firebase/uidemo/auth/AuthUiActivity.java b/app/src/main/java/com/firebase/uidemo/auth/AuthUiActivity.java index a011d4173..3d396f4d3 100644 --- a/app/src/main/java/com/firebase/uidemo/auth/AuthUiActivity.java +++ b/app/src/main/java/com/firebase/uidemo/auth/AuthUiActivity.java @@ -91,12 +91,7 @@ public void onCreate(@Nullable Bundle savedInstanceState) { setGoogleScopesEnabled(false); } else { setGoogleScopesEnabled(mBinding.googleProvider.isChecked()); - mBinding.googleProvider.setOnCheckedChangeListener(new OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton compoundButton, boolean checked) { - setGoogleScopesEnabled(checked); - } - }); + mBinding.googleProvider.setOnCheckedChangeListener((compoundButton, checked) -> setGoogleScopesEnabled(checked)); } if (ConfigurationUtils.isFacebookMisconfigured(this)) { @@ -106,76 +101,45 @@ public void onCheckedChanged(CompoundButton compoundButton, boolean checked) { setFacebookPermissionsEnabled(false); } else { setFacebookPermissionsEnabled(mBinding.facebookProvider.isChecked()); - mBinding.facebookProvider.setOnCheckedChangeListener(new OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton compoundButton, boolean checked) { - setFacebookPermissionsEnabled(checked); - } - }); - } - - mBinding.emailLinkProvider.setOnCheckedChangeListener(new OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - flipPasswordProviderCheckbox(isChecked); - } - }); + mBinding.facebookProvider.setOnCheckedChangeListener((compoundButton, checked) -> setFacebookPermissionsEnabled(checked)); + } - mBinding.emailProvider.setOnCheckedChangeListener(new OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - flipEmailLinkProviderCheckbox(isChecked); - } - }); + mBinding.emailLinkProvider.setOnCheckedChangeListener((buttonView, isChecked) -> flipPasswordProviderCheckbox(isChecked)); + + mBinding.emailProvider.setOnCheckedChangeListener((buttonView, isChecked) -> flipEmailLinkProviderCheckbox(isChecked)); mBinding.emailLinkProvider.setChecked(false); mBinding.emailProvider.setChecked(true); // The custom layout in this app only supports Email and Google providers. - mBinding.customLayout.setOnCheckedChangeListener(new OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton compoundButton, boolean checked) { - if (checked) { - mBinding.googleProvider.setChecked(true); - mBinding.emailProvider.setChecked(true); - - mBinding.facebookProvider.setChecked(false); - mBinding.twitterProvider.setChecked(false); - mBinding.emailLinkProvider.setChecked(false); - mBinding.phoneProvider.setChecked(false); - mBinding.anonymousProvider.setChecked(false); - mBinding.microsoftProvider.setChecked(false); - mBinding.yahooProvider.setChecked(false); - mBinding.appleProvider.setChecked(false); - mBinding.githubProvider.setChecked(false); - } + mBinding.customLayout.setOnCheckedChangeListener((compoundButton, checked) -> { + if (checked) { + mBinding.googleProvider.setChecked(true); + mBinding.emailProvider.setChecked(true); + + mBinding.facebookProvider.setChecked(false); + mBinding.twitterProvider.setChecked(false); + mBinding.emailLinkProvider.setChecked(false); + mBinding.phoneProvider.setChecked(false); + mBinding.anonymousProvider.setChecked(false); + mBinding.microsoftProvider.setChecked(false); + mBinding.yahooProvider.setChecked(false); + mBinding.appleProvider.setChecked(false); + mBinding.githubProvider.setChecked(false); } }); // useEmulator can't be reversed until the FirebaseApp is cleared, so we make this // checkbox "sticky" until the app is restarted - mBinding.useAuthEmulator.setOnCheckedChangeListener(new OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (isChecked) { - mBinding.useAuthEmulator.setEnabled(false); - } + mBinding.useAuthEmulator.setOnCheckedChangeListener((buttonView, isChecked) -> { + if (isChecked) { + mBinding.useAuthEmulator.setEnabled(false); } }); - mBinding.signIn.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - signIn(); - } - }); + mBinding.signIn.setOnClickListener(view -> signIn()); - mBinding.signInSilent.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - silentSignIn(); - } - }); + mBinding.signInSilent.setOnClickListener(view -> silentSignIn()); if (ConfigurationUtils.isGoogleMisconfigured(this) || ConfigurationUtils.isFacebookMisconfigured(this)) { @@ -274,14 +238,11 @@ private Intent getSignInIntent(@Nullable String link) { public void silentSignIn() { getAuthUI().silentSignIn(this, getSelectedProviders()) - .addOnCompleteListener(this, new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - if (task.isSuccessful()) { - startSignedInActivity(null); - } else { - showSnackbar(R.string.sign_in_failed); - } + .addOnCompleteListener(this, task -> { + if (task.isSuccessful()) { + startSignedInActivity(null); + } else { + showSnackbar(R.string.sign_in_failed); } }); } diff --git a/app/src/main/java/com/firebase/uidemo/auth/SignedInActivity.java b/app/src/main/java/com/firebase/uidemo/auth/SignedInActivity.java index ac97462a1..98bd5ac76 100644 --- a/app/src/main/java/com/firebase/uidemo/auth/SignedInActivity.java +++ b/app/src/main/java/com/firebase/uidemo/auth/SignedInActivity.java @@ -82,34 +82,21 @@ public void onCreate(@Nullable Bundle savedInstanceState) { populateProfile(response); populateIdpToken(response); - mBinding.deleteAccount.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - deleteAccountClicked(); - } - }); + mBinding.deleteAccount.setOnClickListener(view -> deleteAccountClicked()); - mBinding.signOut.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - signOut(); - } - }); + mBinding.signOut.setOnClickListener(view -> signOut()); } public void signOut() { AuthUI.getInstance() .signOut(this) - .addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - if (task.isSuccessful()) { - startActivity(AuthUiActivity.createIntent(SignedInActivity.this)); - finish(); - } else { - Log.w(TAG, "signOut:failure", task.getException()); - showSnackbar(R.string.sign_out_failed); - } + .addOnCompleteListener(task -> { + if (task.isSuccessful()) { + startActivity(AuthUiActivity.createIntent(SignedInActivity.this)); + finish(); + } else { + Log.w(TAG, "signOut:failure", task.getException()); + showSnackbar(R.string.sign_out_failed); } }); } @@ -117,12 +104,7 @@ public void onComplete(@NonNull Task task) { public void deleteAccountClicked() { new AlertDialog.Builder(this) .setMessage("Are you sure you want to delete this account?") - .setPositiveButton("Yes, nuke it!", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - deleteAccount(); - } - }) + .setPositiveButton("Yes, nuke it!", (dialogInterface, i) -> deleteAccount()) .setNegativeButton("No", null) .show(); } @@ -130,15 +112,12 @@ public void onClick(DialogInterface dialogInterface, int i) { private void deleteAccount() { AuthUI.getInstance() .delete(this) - .addOnCompleteListener(this, new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - if (task.isSuccessful()) { - startActivity(AuthUiActivity.createIntent(SignedInActivity.this)); - finish(); - } else { - showSnackbar(R.string.delete_account_failed); - } + .addOnCompleteListener(this, task -> { + if (task.isSuccessful()) { + startActivity(AuthUiActivity.createIntent(SignedInActivity.this)); + finish(); + } else { + showSnackbar(R.string.delete_account_failed); } }); } diff --git a/app/src/main/java/com/firebase/uidemo/database/firestore/FirestoreChatActivity.java b/app/src/main/java/com/firebase/uidemo/database/firestore/FirestoreChatActivity.java index 509257316..59af0408b 100644 --- a/app/src/main/java/com/firebase/uidemo/database/firestore/FirestoreChatActivity.java +++ b/app/src/main/java/com/firebase/uidemo/database/firestore/FirestoreChatActivity.java @@ -65,34 +65,16 @@ protected void onCreate(@Nullable Bundle savedInstanceState) { mBinding.messagesList.setHasFixedSize(true); mBinding.messagesList.setLayoutManager(manager); - mBinding.messagesList.addOnLayoutChangeListener(new View.OnLayoutChangeListener() { - @Override - public void onLayoutChange(View view, int left, int top, int right, int bottom, - int oldLeft, int oldTop, int oldRight, int oldBottom) { - if (bottom < oldBottom) { - mBinding.messagesList.postDelayed(new Runnable() { - @Override - public void run() { - mBinding.messagesList.smoothScrollToPosition(0); - } - }, 100); - } + mBinding.messagesList.addOnLayoutChangeListener((view, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> { + if (bottom < oldBottom) { + mBinding.messagesList.postDelayed(() -> mBinding.messagesList.smoothScrollToPosition( + 0), 100); } }); - ImeHelper.setImeOnDoneListener(mBinding.messageEdit, new ImeHelper.DonePressedListener() { - @Override - public void onDonePressed() { - onSendClick(); - } - }); + ImeHelper.setImeOnDoneListener(mBinding.messageEdit, () -> onSendClick()); - mBinding.sendButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - onSendClick(); - } - }); + mBinding.sendButton.setOnClickListener(view -> onSendClick()); } @Override @@ -180,11 +162,7 @@ public void onDataChanged() { } private void onAddMessage(@NonNull Chat chat) { - sChatCollection.add(chat).addOnFailureListener(this, new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - Log.e(TAG, "Failed to write message", e); - } - }); + sChatCollection.add(chat).addOnFailureListener(this, + e -> Log.e(TAG, "Failed to write message", e)); } } diff --git a/app/src/main/java/com/firebase/uidemo/database/firestore/FirestorePagingActivity.java b/app/src/main/java/com/firebase/uidemo/database/firestore/FirestorePagingActivity.java index eb5bdb288..6563ef410 100644 --- a/app/src/main/java/com/firebase/uidemo/database/firestore/FirestorePagingActivity.java +++ b/app/src/main/java/com/firebase/uidemo/database/firestore/FirestorePagingActivity.java @@ -84,51 +84,43 @@ protected void onBindViewHolder(@NonNull ItemViewHolder holder, holder.bind(model); } }; - adapter.addLoadStateListener(new Function1() { - @Override - public Unit invoke(CombinedLoadStates states) { - LoadState refresh = states.getRefresh(); - LoadState append = states.getAppend(); - - if (refresh instanceof LoadState.Error || append instanceof LoadState.Error) { - showToast("An error occurred."); - adapter.retry(); - } + adapter.addLoadStateListener(states -> { + LoadState refresh = states.getRefresh(); + LoadState append = states.getAppend(); - if (append instanceof LoadState.Loading) { - mBinding.swipeRefreshLayout.setRefreshing(true); - } + if (refresh instanceof LoadState.Error || append instanceof LoadState.Error) { + showToast("An error occurred."); + adapter.retry(); + } - if (append instanceof LoadState.NotLoading) { - LoadState.NotLoading notLoading = (LoadState.NotLoading) append; - if (notLoading.getEndOfPaginationReached()) { - // This indicates that the user has scrolled - // until the end of the data set. - mBinding.swipeRefreshLayout.setRefreshing(false); - showToast("Reached end of data set."); - return null; - } + if (append instanceof LoadState.Loading) { + mBinding.swipeRefreshLayout.setRefreshing(true); + } - if (refresh instanceof LoadState.NotLoading) { - // This indicates the most recent load - // has finished. - mBinding.swipeRefreshLayout.setRefreshing(false); - return null; - } + if (append instanceof LoadState.NotLoading) { + LoadState.NotLoading notLoading = (LoadState.NotLoading) append; + if (notLoading.getEndOfPaginationReached()) { + // This indicates that the user has scrolled + // until the end of the data set. + mBinding.swipeRefreshLayout.setRefreshing(false); + showToast("Reached end of data set."); + return null; + } + + if (refresh instanceof LoadState.NotLoading) { + // This indicates the most recent load + // has finished. + mBinding.swipeRefreshLayout.setRefreshing(false); + return null; } - return null; } + return null; }); mBinding.pagingRecycler.setLayoutManager(new LinearLayoutManager(this)); mBinding.pagingRecycler.setAdapter(adapter); - mBinding.swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { - @Override - public void onRefresh() { - adapter.refresh(); - } - }); + mBinding.swipeRefreshLayout.setOnRefreshListener(() -> adapter.refresh()); } @Override @@ -141,15 +133,12 @@ public boolean onCreateOptionsMenu(@NonNull Menu menu) { public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() == R.id.item_add_data) { showToast("Adding data..."); - createItems().addOnCompleteListener(this, new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - if (task.isSuccessful()) { - showToast("Data added."); - } else { - Log.w(TAG, "addData", task.getException()); - showToast("Error adding data."); - } + createItems().addOnCompleteListener(this, task -> { + if (task.isSuccessful()) { + showToast("Data added."); + } else { + Log.w(TAG, "addData", task.getException()); + showToast("Error adding data."); } }); diff --git a/app/src/main/java/com/firebase/uidemo/database/realtime/FirebaseDbPagingActivity.java b/app/src/main/java/com/firebase/uidemo/database/realtime/FirebaseDbPagingActivity.java index 0201017cb..f741a47f3 100644 --- a/app/src/main/java/com/firebase/uidemo/database/realtime/FirebaseDbPagingActivity.java +++ b/app/src/main/java/com/firebase/uidemo/database/realtime/FirebaseDbPagingActivity.java @@ -115,12 +115,9 @@ protected void onError(DatabaseError databaseError) { mBinding.pagingRecycler.setAdapter(mAdapter); // Reload data on swipe - mBinding.swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { - @Override - public void onRefresh() { - //Reload Data - mAdapter.refresh(); - } + mBinding.swipeRefreshLayout.setOnRefreshListener(() -> { + //Reload Data + mAdapter.refresh(); }); } diff --git a/app/src/main/java/com/firebase/uidemo/database/realtime/RealtimeDbChatActivity.java b/app/src/main/java/com/firebase/uidemo/database/realtime/RealtimeDbChatActivity.java index 59948bc65..381893f7c 100644 --- a/app/src/main/java/com/firebase/uidemo/database/realtime/RealtimeDbChatActivity.java +++ b/app/src/main/java/com/firebase/uidemo/database/realtime/RealtimeDbChatActivity.java @@ -58,19 +58,9 @@ protected void onCreate(@Nullable Bundle savedInstanceState) { mBinding.messagesList.setHasFixedSize(true); mBinding.messagesList.setLayoutManager(new LinearLayoutManager(this)); - ImeHelper.setImeOnDoneListener(mBinding.messageEdit, new ImeHelper.DonePressedListener() { - @Override - public void onDonePressed() { - onSendClick(); - } - }); + ImeHelper.setImeOnDoneListener(mBinding.messageEdit, () -> onSendClick()); - mBinding.sendButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - onSendClick(); - } - }); + mBinding.sendButton.setOnClickListener(view -> onSendClick()); } @Override @@ -157,12 +147,9 @@ public void onDataChanged() { } protected void onAddMessage(@NonNull Chat chat) { - sChatQuery.getRef().push().setValue(chat, new DatabaseReference.CompletionListener() { - @Override - public void onComplete(DatabaseError error, DatabaseReference reference) { - if (error != null) { - Log.e(TAG, "Failed to write message", error.toException()); - } + sChatQuery.getRef().push().setValue(chat, (error, reference) -> { + if (error != null) { + Log.e(TAG, "Failed to write message", error.toException()); } }); } diff --git a/app/src/main/java/com/firebase/uidemo/storage/ImageActivity.java b/app/src/main/java/com/firebase/uidemo/storage/ImageActivity.java index add52b665..bf2f57a80 100644 --- a/app/src/main/java/com/firebase/uidemo/storage/ImageActivity.java +++ b/app/src/main/java/com/firebase/uidemo/storage/ImageActivity.java @@ -49,25 +49,17 @@ protected void onCreate(@Nullable Bundle savedInstanceState) { mBinding = ActivityImageBinding.inflate(getLayoutInflater()); setContentView(mBinding.getRoot()); - mBinding.buttonDownloadDirect.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - // Download directly from StorageReference using Glide - // (See MyAppGlideModule for Loader registration) - GlideApp.with(ImageActivity.this) - .load(mImageRef) - .centerCrop() - .transition(DrawableTransitionOptions.withCrossFade()) - .into(mBinding.firstImage); - } + mBinding.buttonDownloadDirect.setOnClickListener(view -> { + // Download directly from StorageReference using Glide + // (See MyAppGlideModule for Loader registration) + GlideApp.with(ImageActivity.this) + .load(mImageRef) + .centerCrop() + .transition(DrawableTransitionOptions.withCrossFade()) + .into(mBinding.firstImage); }); - mBinding.buttonChoosePhoto.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - choosePhoto(); - } - }); + mBinding.buttonChoosePhoto.setOnClickListener(view -> choosePhoto()); // By default, Cloud Storage files require authentication to read or write. // For this sample to function correctly, enable Anonymous Auth in the Firebase console: @@ -115,26 +107,20 @@ private void uploadPhoto(Uri uri) { String uuid = UUID.randomUUID().toString(); mImageRef = FirebaseStorage.getInstance().getReference(uuid); mImageRef.putFile(uri) - .addOnSuccessListener(this, new OnSuccessListener() { - @Override - public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { - if (BuildConfig.DEBUG) { - Log.d(TAG, "uploadPhoto:onSuccess:" + - taskSnapshot.getMetadata().getReference().getPath()); - } - Toast.makeText(ImageActivity.this, "Image uploaded", - Toast.LENGTH_SHORT).show(); - - showDownloadUI(); + .addOnSuccessListener(this, taskSnapshot -> { + if (BuildConfig.DEBUG) { + Log.d(TAG, "uploadPhoto:onSuccess:" + + taskSnapshot.getMetadata().getReference().getPath()); } + Toast.makeText(ImageActivity.this, "Image uploaded", + Toast.LENGTH_SHORT).show(); + + showDownloadUI(); }) - .addOnFailureListener(this, new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - Log.w(TAG, "uploadPhoto:onError", e); - Toast.makeText(ImageActivity.this, "Upload failed", - Toast.LENGTH_SHORT).show(); - } + .addOnFailureListener(this, e -> { + Log.w(TAG, "uploadPhoto:onError", e); + Toast.makeText(ImageActivity.this, "Upload failed", + Toast.LENGTH_SHORT).show(); }); } diff --git a/auth/src/main/java/com/firebase/ui/auth/AuthUI.java b/auth/src/main/java/com/firebase/ui/auth/AuthUI.java index c9c6673c8..15cef29bd 100644 --- a/auth/src/main/java/com/firebase/ui/auth/AuthUI.java +++ b/auth/src/main/java/com/firebase/ui/auth/AuthUI.java @@ -360,33 +360,25 @@ public Task silentSignIn(@NonNull Context context, ProviderUtils.providerIdToAccountType(GoogleAuthProvider .PROVIDER_ID)) .build()) - .continueWithTask(new Continuation>() { - @Override - public Task then(@NonNull Task task) { - Credential credential = task.getResult().getCredential(); - String email = credential.getId(); - String password = credential.getPassword(); - - if (TextUtils.isEmpty(password)) { - return GoogleSignIn.getClient(appContext, - new GoogleSignInOptions.Builder(googleOptions) - .setAccountName(email) - .build()) - .silentSignIn() - .continueWithTask(new Continuation>() { - @Override - public Task then( - @NonNull Task task) { - AuthCredential authCredential = GoogleAuthProvider - .getCredential( - task.getResult().getIdToken(), null); - return mAuth.signInWithCredential(authCredential); - } - }); - } else { - return mAuth.signInWithEmailAndPassword(email, password); - } + .continueWithTask(task -> { + Credential credential = task.getResult().getCredential(); + String email1 = credential.getId(); + String password = credential.getPassword(); + + if (TextUtils.isEmpty(password)) { + return GoogleSignIn.getClient(appContext, + new GoogleSignInOptions.Builder(googleOptions) + .setAccountName(email1) + .build()) + .silentSignIn() + .continueWithTask(task1 -> { + AuthCredential authCredential = GoogleAuthProvider + .getCredential( + task1.getResult().getIdToken(), null); + return mAuth.signInWithCredential(authCredential); + }); + } else { + return mAuth.signInWithEmailAndPassword(email1, password); } }); } @@ -411,34 +403,28 @@ public Task signOut(@NonNull Context context) { : Tasks.forResult((Void) null); maybeDisableAutoSignIn - .continueWith(new Continuation() { - @Override - public Void then(@NonNull Task task) { - // We want to ignore a specific exception, since it's not a good reason - // to fail (see Issue 1156). - Exception e = task.getException(); - if (e instanceof ApiException - && ((ApiException) e).getStatusCode() == CommonStatusCodes - .CANCELED) { - Log.w(TAG, "Could not disable auto-sign in, maybe there are no " + - "SmartLock accounts available?", e); - return null; - } - - return task.getResult(); + .continueWith(task -> { + // We want to ignore a specific exception, since it's not a good reason + // to fail (see Issue 1156). + Exception e = task.getException(); + if (e instanceof ApiException + && ((ApiException) e).getStatusCode() == CommonStatusCodes + .CANCELED) { + Log.w(TAG, "Could not disable auto-sign in, maybe there are no " + + "SmartLock accounts available?", e); + return null; } + + return task.getResult(); }); return Tasks.whenAll( signOutIdps(context), maybeDisableAutoSignIn - ).continueWith(new Continuation() { - @Override - public Void then(@NonNull Task task) { - task.getResult(); // Propagate exceptions - mAuth.signOut(); - return null; - } + ).continueWith(task -> { + task.getResult(); // Propagate exceptions + mAuth.signOut(); + return null; }); } @@ -462,47 +448,38 @@ public Task delete(@NonNull final Context context) { final List credentials = getCredentialsFromFirebaseUser(currentUser); // Ensure the order in which tasks are executed properly destructures the user. - return signOutIdps(context).continueWithTask(new Continuation>() { - @Override - public Task then(@NonNull Task task) { - task.getResult(); // Propagate exception if there was one + return signOutIdps(context).continueWithTask(task -> { + task.getResult(); // Propagate exception if there was one - if (!GoogleApiUtils.isPlayServicesAvailable(context)) { - Log.w(TAG, "Google Play services not available during delete"); - return Tasks.forResult((Void) null); - } - - final CredentialsClient client = GoogleApiUtils.getCredentialsClient(context); - List> credentialTasks = new ArrayList<>(); - for (Credential credential : credentials) { - credentialTasks.add(client.delete(credential)); - } - return Tasks.whenAll(credentialTasks) - .continueWith(new Continuation() { - @Override - public Void then(@NonNull Task task) { - Exception e = task.getException(); - Throwable t = e == null ? null : e.getCause(); - if (!(t instanceof ApiException) - || ((ApiException) t).getStatusCode() != - CommonStatusCodes.CANCELED) { - // Only propagate the exception if it isn't an invalid account - // one. This can occur if we failed to save the credential or it - // was deleted elsewhere. However, a lack of stored credential - // doesn't mean fully deleting the user failed. - return task.getResult(); - } - - return null; - } - }); + if (!GoogleApiUtils.isPlayServicesAvailable(context)) { + Log.w(TAG, "Google Play services not available during delete"); + return Tasks.forResult((Void) null); } - }).continueWithTask(new Continuation>() { - @Override - public Task then(@NonNull Task task) { - task.getResult(); // Propagate exception if there was one - return currentUser.delete(); + + final CredentialsClient client = GoogleApiUtils.getCredentialsClient(context); + List> credentialTasks = new ArrayList<>(); + for (Credential credential : credentials) { + credentialTasks.add(client.delete(credential)); } + return Tasks.whenAll(credentialTasks) + .continueWith(task1 -> { + Exception e = task1.getException(); + Throwable t = e == null ? null : e.getCause(); + if (!(t instanceof ApiException) + || ((ApiException) t).getStatusCode() != + CommonStatusCodes.CANCELED) { + // Only propagate the exception if it isn't an invalid account + // one. This can occur if we failed to save the credential or it + // was deleted elsewhere. However, a lack of stored credential + // doesn't mean fully deleting the user failed. + return task1.getResult(); + } + + return null; + }); + }).continueWithTask(task -> { + task.getResult(); // Propagate exception if there was one + return currentUser.delete(); }); } @@ -1140,7 +1117,7 @@ public GoogleBuilder setSignInOptions(@NonNull GoogleSignInOptions options) { public IdpConfig build() { if (!getParams().containsKey(ExtraConstants.GOOGLE_SIGN_IN_OPTIONS)) { validateWebClientId(); - setScopes(Collections.emptyList()); + setScopes(Collections.emptyList()); } return super.build(); diff --git a/auth/src/main/java/com/firebase/ui/auth/IdpResponse.java b/auth/src/main/java/com/firebase/ui/auth/IdpResponse.java index ea7c29a08..009d3e2a8 100644 --- a/auth/src/main/java/com/firebase/ui/auth/IdpResponse.java +++ b/auth/src/main/java/com/firebase/ui/auth/IdpResponse.java @@ -42,12 +42,12 @@ public class IdpResponse implements Parcelable { @Override public IdpResponse createFromParcel(Parcel in) { return new IdpResponse( - in.readParcelable(User.class.getClassLoader()), + in.readParcelable(User.class.getClassLoader()), in.readString(), in.readString(), in.readInt() == 1, (FirebaseUiException) in.readSerializable(), - in.readParcelable(AuthCredential.class.getClassLoader()) + in.readParcelable(AuthCredential.class.getClassLoader()) ); } diff --git a/auth/src/main/java/com/firebase/ui/auth/KickoffActivity.java b/auth/src/main/java/com/firebase/ui/auth/KickoffActivity.java index ba00e0e51..bdbc63c34 100644 --- a/auth/src/main/java/com/firebase/ui/auth/KickoffActivity.java +++ b/auth/src/main/java/com/firebase/ui/auth/KickoffActivity.java @@ -61,23 +61,15 @@ protected void onFailure(@NonNull Exception e) { : Tasks.forResult((Void) null); checkPlayServicesTask - .addOnSuccessListener(this, new OnSuccessListener() { - @Override - public void onSuccess(Void aVoid) { - if (savedInstanceState != null) { - return; - } - - mKickstarter.start(); + .addOnSuccessListener(this, aVoid -> { + if (savedInstanceState != null) { + return; } + + mKickstarter.start(); }) - .addOnFailureListener(this, new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - finish(RESULT_CANCELED, IdpResponse.getErrorIntent(new FirebaseUiException( - ErrorCodes.PLAY_SERVICES_UPDATE_CANCELLED, e))); - } - }); + .addOnFailureListener(this, e -> finish(RESULT_CANCELED, IdpResponse.getErrorIntent(new FirebaseUiException( + ErrorCodes.PLAY_SERVICES_UPDATE_CANCELLED, e)))); } @Override diff --git a/auth/src/main/java/com/firebase/ui/auth/data/model/User.java b/auth/src/main/java/com/firebase/ui/auth/data/model/User.java index 91c0b1605..3979b2a8f 100644 --- a/auth/src/main/java/com/firebase/ui/auth/data/model/User.java +++ b/auth/src/main/java/com/firebase/ui/auth/data/model/User.java @@ -23,7 +23,7 @@ public User createFromParcel(Parcel in) { in.readString(), in.readString(), in.readString(), - in.readParcelable(Uri.class.getClassLoader())); + in.readParcelable(Uri.class.getClassLoader())); } @Override diff --git a/auth/src/main/java/com/firebase/ui/auth/data/remote/AnonymousSignInHandler.java b/auth/src/main/java/com/firebase/ui/auth/data/remote/AnonymousSignInHandler.java index 6e531c3fb..daf873700 100644 --- a/auth/src/main/java/com/firebase/ui/auth/data/remote/AnonymousSignInHandler.java +++ b/auth/src/main/java/com/firebase/ui/auth/data/remote/AnonymousSignInHandler.java @@ -41,24 +41,14 @@ protected void onCreate() { public void startSignIn(@NonNull FirebaseAuth auth, @NonNull HelperActivityBase activity, @NonNull String providerId) { - setResult(Resource.forLoading()); + setResult(Resource.forLoading()); // Calling signInAnonymously() will always return the same anonymous user if already // available. This is enforced by the client SDK. mAuth.signInAnonymously() - .addOnSuccessListener(new OnSuccessListener() { - @Override - public void onSuccess(AuthResult result) { - setResult(Resource.forSuccess(initResponse( - result.getAdditionalUserInfo().isNewUser()))); - } - }) - .addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - setResult(Resource.forFailure(e)); - } - }); + .addOnSuccessListener(result -> setResult(Resource.forSuccess(initResponse( + result.getAdditionalUserInfo().isNewUser())))) + .addOnFailureListener(e -> setResult(Resource.forFailure(e))); } diff --git a/auth/src/main/java/com/firebase/ui/auth/data/remote/EmailSignInHandler.java b/auth/src/main/java/com/firebase/ui/auth/data/remote/EmailSignInHandler.java index 3fc02701b..d0b846468 100644 --- a/auth/src/main/java/com/firebase/ui/auth/data/remote/EmailSignInHandler.java +++ b/auth/src/main/java/com/firebase/ui/auth/data/remote/EmailSignInHandler.java @@ -42,7 +42,7 @@ public void onActivityResult(int requestCode, int resultCode, @Nullable Intent d } else if (requestCode == RequestCodes.EMAIL_FLOW) { IdpResponse response = IdpResponse.fromResultIntent(data); if (response == null) { - setResult(Resource.forFailure(new UserCancellationException())); + setResult(Resource.forFailure(new UserCancellationException())); } else { setResult(Resource.forSuccess(response)); } diff --git a/auth/src/main/java/com/firebase/ui/auth/data/remote/FacebookSignInHandler.java b/auth/src/main/java/com/firebase/ui/auth/data/remote/FacebookSignInHandler.java index 6ca01defb..c89dfb9a7 100644 --- a/auth/src/main/java/com/firebase/ui/auth/data/remote/FacebookSignInHandler.java +++ b/auth/src/main/java/com/firebase/ui/auth/data/remote/FacebookSignInHandler.java @@ -68,7 +68,7 @@ protected void onCreate() { List permissions = getArguments().getParams() .getStringArrayList(ExtraConstants.FACEBOOK_PERMISSIONS); permissions = new ArrayList<>( - permissions == null ? Collections.emptyList() : permissions); + permissions == null ? Collections.emptyList() : permissions); // Ensure we have email and public_profile permissions if (!permissions.contains(EMAIL)) { permissions.add(EMAIL); } @@ -101,7 +101,7 @@ protected void onCleared() { private class Callback implements FacebookCallback { @Override public void onSuccess(LoginResult result) { - setResult(Resource.forLoading()); + setResult(Resource.forLoading()); GraphRequest request = GraphRequest.newMeRequest(result.getAccessToken(), new ProfileRequest(result)); @@ -114,12 +114,12 @@ public void onSuccess(LoginResult result) { @Override public void onCancel() { - setResult(Resource.forFailure(new UserCancellationException())); + setResult(Resource.forFailure(new UserCancellationException())); } @Override public void onError(FacebookException e) { - setResult(Resource.forFailure(new FirebaseUiException( + setResult(Resource.forFailure(new FirebaseUiException( ErrorCodes.PROVIDER_ERROR, e))); } } @@ -135,12 +135,12 @@ public ProfileRequest(LoginResult result) { public void onCompleted(JSONObject object, GraphResponse response) { FacebookRequestError error = response.getError(); if (error != null) { - setResult(Resource.forFailure(new FirebaseUiException( + setResult(Resource.forFailure(new FirebaseUiException( ErrorCodes.PROVIDER_ERROR, error.getException()))); return; } if (object == null) { - setResult(Resource.forFailure(new FirebaseUiException( + setResult(Resource.forFailure(new FirebaseUiException( ErrorCodes.PROVIDER_ERROR, "Facebook graph request failed"))); return; } diff --git a/auth/src/main/java/com/firebase/ui/auth/data/remote/GenericIdpAnonymousUpgradeLinkingHandler.java b/auth/src/main/java/com/firebase/ui/auth/data/remote/GenericIdpAnonymousUpgradeLinkingHandler.java index 9222dd992..7838c681c 100644 --- a/auth/src/main/java/com/firebase/ui/auth/data/remote/GenericIdpAnonymousUpgradeLinkingHandler.java +++ b/auth/src/main/java/com/firebase/ui/auth/data/remote/GenericIdpAnonymousUpgradeLinkingHandler.java @@ -29,7 +29,7 @@ public GenericIdpAnonymousUpgradeLinkingHandler(Application application) { public void startSignIn(@NonNull FirebaseAuth auth, @NonNull HelperActivityBase activity, @NonNull String providerId) { - setResult(Resource.forLoading()); + setResult(Resource.forLoading()); FlowParameters flowParameters = activity.getFlowParams(); OAuthProvider provider = buildOAuthProvider(providerId, auth); @@ -47,24 +47,16 @@ private void handleAnonymousUpgradeLinkingFlow(final HelperActivityBase activity final FlowParameters flowParameters) { final boolean useEmulator = activity.getAuthUI().isUseEmulator(); AuthOperationManager.getInstance().safeGenericIdpSignIn(activity, provider, flowParameters) - .addOnSuccessListener(new OnSuccessListener() { - @Override - public void onSuccess(AuthResult authResult) { - // Pass the credential so we can sign-in on the after the merge - // conflict is resolved. - handleSuccess( - useEmulator, - provider.getProviderId(), - authResult.getUser(), (OAuthCredential) authResult.getCredential(), - /* setPendingCredential= */true); - } + .addOnSuccessListener(authResult -> { + // Pass the credential so we can sign-in on the after the merge + // conflict is resolved. + handleSuccess( + useEmulator, + provider.getProviderId(), + authResult.getUser(), (OAuthCredential) authResult.getCredential(), + /* setPendingCredential= */true); }) - .addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - setResult(Resource.forFailure(e)); - } - }); + .addOnFailureListener(e -> setResult(Resource.forFailure(e))); } } diff --git a/auth/src/main/java/com/firebase/ui/auth/data/remote/GenericIdpSignInHandler.java b/auth/src/main/java/com/firebase/ui/auth/data/remote/GenericIdpSignInHandler.java index fecfa8d18..13ba2b851 100644 --- a/auth/src/main/java/com/firebase/ui/auth/data/remote/GenericIdpSignInHandler.java +++ b/auth/src/main/java/com/firebase/ui/auth/data/remote/GenericIdpSignInHandler.java @@ -71,7 +71,7 @@ public static AuthUI.IdpConfig getGenericFacebookConfig() { @Override public final void startSignIn(@NonNull HelperActivityBase activity) { - setResult(Resource.forLoading()); + setResult(Resource.forLoading()); startSignIn(activity.getAuth(), activity, getArguments().getProviderId()); } @@ -79,7 +79,7 @@ public final void startSignIn(@NonNull HelperActivityBase activity) { public void startSignIn(@NonNull FirebaseAuth auth, @NonNull HelperActivityBase activity, @NonNull String providerId) { - setResult(Resource.forLoading()); + setResult(Resource.forLoading()); FlowParameters flowParameters = activity.getFlowParams(); OAuthProvider provider = buildOAuthProvider(providerId, auth); @@ -98,45 +98,37 @@ protected void handleNormalSignInFlow(final FirebaseAuth auth, final boolean useEmulator = activity.getAuthUI().isUseEmulator(); auth.startActivityForSignInWithProvider(activity, provider) .addOnSuccessListener( - new OnSuccessListener() { - @Override - public void onSuccess(@NonNull AuthResult authResult) { - handleSuccess( - useEmulator, - provider.getProviderId(), - authResult.getUser(), - (OAuthCredential) authResult.getCredential(), - authResult.getAdditionalUserInfo().isNewUser()); - } - }) + authResult -> handleSuccess( + useEmulator, + provider.getProviderId(), + authResult.getUser(), + (OAuthCredential) authResult.getCredential(), + authResult.getAdditionalUserInfo().isNewUser())) .addOnFailureListener( - new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - if (e instanceof FirebaseAuthException) { - FirebaseAuthError error = - FirebaseAuthError.fromException((FirebaseAuthException) e); - - if (e instanceof FirebaseAuthUserCollisionException) { - FirebaseAuthUserCollisionException collisionException = - (FirebaseAuthUserCollisionException) e; - - setResult(Resource.forFailure( - new FirebaseUiUserCollisionException( - ErrorCodes.ERROR_GENERIC_IDP_RECOVERABLE_ERROR, - "Recoverable error.", - provider.getProviderId(), - collisionException.getEmail(), - collisionException.getUpdatedCredential()))); - } else if (error == FirebaseAuthError.ERROR_WEB_CONTEXT_CANCELED) { - setResult(Resource.forFailure( - new UserCancellationException())); - } else { - setResult(Resource.forFailure(e)); - } + e -> { + if (e instanceof FirebaseAuthException) { + FirebaseAuthError error = + FirebaseAuthError.fromException((FirebaseAuthException) e); + + if (e instanceof FirebaseAuthUserCollisionException) { + FirebaseAuthUserCollisionException collisionException = + (FirebaseAuthUserCollisionException) e; + + setResult(Resource.forFailure( + new FirebaseUiUserCollisionException( + ErrorCodes.ERROR_GENERIC_IDP_RECOVERABLE_ERROR, + "Recoverable error.", + provider.getProviderId(), + collisionException.getEmail(), + collisionException.getUpdatedCredential()))); + } else if (error == FirebaseAuthError.ERROR_WEB_CONTEXT_CANCELED) { + setResult(Resource.forFailure( + new UserCancellationException())); } else { - setResult(Resource.forFailure(e)); + setResult(Resource.forFailure(e)); } + } else { + setResult(Resource.forFailure(e)); } }); @@ -151,70 +143,59 @@ private void handleAnonymousUpgradeFlow(final FirebaseAuth auth, auth.getCurrentUser() .startActivityForLinkWithProvider(activity, provider) .addOnSuccessListener( - new OnSuccessListener() { - @Override - public void onSuccess(@NonNull AuthResult authResult) { - handleSuccess( - useEmulator, - provider.getProviderId(), - authResult.getUser(), - (OAuthCredential) authResult.getCredential(), - authResult.getAdditionalUserInfo().isNewUser()); - } - }) + authResult -> handleSuccess( + useEmulator, + provider.getProviderId(), + authResult.getUser(), + (OAuthCredential) authResult.getCredential(), + authResult.getAdditionalUserInfo().isNewUser())) .addOnFailureListener( - new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - if (!(e instanceof FirebaseAuthUserCollisionException)) { - setResult(Resource.forFailure(e)); - return; - } - - FirebaseAuthUserCollisionException collisionException = - (FirebaseAuthUserCollisionException) e; - final AuthCredential credential = - collisionException.getUpdatedCredential(); - final String email = - collisionException.getEmail(); - - // Case 1: Anonymous user trying to link with an existing user - // Case 2: Anonymous user trying to link with a provider keyed - // by an email that already belongs to an existing account - // (linking flow) - ProviderUtils.fetchSortedProviders(auth, flowParameters, email) - .addOnSuccessListener(new OnSuccessListener>() { - @Override - public void onSuccess(List providers) { - if (providers.isEmpty()) { - String errorMessage = - "Unable to complete the linkingflow -" + - " the user is using " + - "unsupported providers."; - setResult(Resource.forFailure( - new FirebaseUiException( - ErrorCodes.DEVELOPER_ERROR, - errorMessage))); - return; - } - - if (providers.contains(provider.getProviderId())) { - // Case 1 - handleMergeFailure(credential); - } else { - // Case 2 - linking flow to be handled by - // SocialProviderResponseHandler - setResult(Resource.forFailure( - new FirebaseUiUserCollisionException( - ErrorCodes.ERROR_GENERIC_IDP_RECOVERABLE_ERROR, - "Recoverable error.", - provider.getProviderId(), - email, - credential))); - } - } - }); + e -> { + if (!(e instanceof FirebaseAuthUserCollisionException)) { + setResult(Resource.forFailure(e)); + return; } + + FirebaseAuthUserCollisionException collisionException = + (FirebaseAuthUserCollisionException) e; + final AuthCredential credential = + collisionException.getUpdatedCredential(); + final String email = + collisionException.getEmail(); + + // Case 1: Anonymous user trying to link with an existing user + // Case 2: Anonymous user trying to link with a provider keyed + // by an email that already belongs to an existing account + // (linking flow) + ProviderUtils.fetchSortedProviders(auth, flowParameters, email) + .addOnSuccessListener(providers -> { + if (providers.isEmpty()) { + String errorMessage = + "Unable to complete the linkingflow -" + + " the user is using " + + "unsupported providers."; + setResult(Resource.forFailure( + new FirebaseUiException( + ErrorCodes.DEVELOPER_ERROR, + errorMessage))); + return; + } + + if (providers.contains(provider.getProviderId())) { + // Case 1 + handleMergeFailure(credential); + } else { + // Case 2 - linking flow to be handled by + // SocialProviderResponseHandler + setResult(Resource.forFailure( + new FirebaseUiUserCollisionException( + ErrorCodes.ERROR_GENERIC_IDP_RECOVERABLE_ERROR, + "Recoverable error.", + provider.getProviderId(), + email, + credential))); + } + }); }); } @@ -273,7 +254,7 @@ protected void handleSuccess(boolean isUseEmulator, } response.setNewUser(isNewUser); - setResult(Resource.forSuccess(response.build())); + setResult(Resource.forSuccess(response.build())); } protected void handleSuccess(boolean isUseEmulator, @@ -288,7 +269,7 @@ protected void handleSuccess(boolean isUseEmulator, protected void handleMergeFailure(@NonNull AuthCredential credential) { IdpResponse failureResponse = new IdpResponse.Builder() .setPendingCredential(credential).build(); - setResult(Resource.forFailure(new FirebaseAuthAnonymousUpgradeException( + setResult(Resource.forFailure(new FirebaseAuthAnonymousUpgradeException( ErrorCodes.ANONYMOUS_UPGRADE_MERGE_CONFLICT, failureResponse))); } @@ -298,7 +279,7 @@ public void onActivityResult(int requestCode, int resultCode, @Nullable Intent d if (requestCode == RequestCodes.GENERIC_IDP_SIGN_IN_FLOW) { IdpResponse response = IdpResponse.fromResultIntent(data); if (response == null) { - setResult(Resource.forFailure(new UserCancellationException())); + setResult(Resource.forFailure(new UserCancellationException())); } else { setResult(Resource.forSuccess(response)); } diff --git a/auth/src/main/java/com/firebase/ui/auth/data/remote/GoogleSignInHandler.java b/auth/src/main/java/com/firebase/ui/auth/data/remote/GoogleSignInHandler.java index a992ac784..e494a4cb6 100644 --- a/auth/src/main/java/com/firebase/ui/auth/data/remote/GoogleSignInHandler.java +++ b/auth/src/main/java/com/firebase/ui/auth/data/remote/GoogleSignInHandler.java @@ -66,15 +66,15 @@ public void startSignIn(@NonNull FirebaseAuth auth, } private void start() { - setResult(Resource.forLoading()); - setResult(Resource.forFailure(new IntentRequiredException( + setResult(Resource.forLoading()); + setResult(Resource.forFailure(new IntentRequiredException( GoogleSignIn.getClient(getApplication(), getSignInOptions()).getSignInIntent(), RequestCodes.GOOGLE_PROVIDER))); } private GoogleSignInOptions getSignInOptions() { GoogleSignInOptions.Builder builder = new GoogleSignInOptions.Builder( - mConfig.getParams().getParcelable( + mConfig.getParams().getParcelable( ExtraConstants.GOOGLE_SIGN_IN_OPTIONS)); if (!TextUtils.isEmpty(mEmail)) { @@ -103,13 +103,13 @@ public void onActivityResult(int requestCode, int resultCode, @Nullable Intent d // Google remembers the account so the picker doesn't appear twice for the user. start(); } else if (e.getStatusCode() == GoogleSignInStatusCodes.SIGN_IN_CANCELLED) { - setResult(Resource.forFailure(new UserCancellationException())); + setResult(Resource.forFailure(new UserCancellationException())); } else { if (e.getStatusCode() == CommonStatusCodes.DEVELOPER_ERROR) { Log.w(TAG, "Developer error: this application is misconfigured. " + "Check your SHA1 and package name in the Firebase console."); } - setResult(Resource.forFailure(new FirebaseUiException( + setResult(Resource.forFailure(new FirebaseUiException( ErrorCodes.PROVIDER_ERROR, "Code: " + e.getStatusCode() + ", message: " + e.getMessage()))); } diff --git a/auth/src/main/java/com/firebase/ui/auth/data/remote/PhoneSignInHandler.java b/auth/src/main/java/com/firebase/ui/auth/data/remote/PhoneSignInHandler.java index d8cac81e7..a93ee1b94 100644 --- a/auth/src/main/java/com/firebase/ui/auth/data/remote/PhoneSignInHandler.java +++ b/auth/src/main/java/com/firebase/ui/auth/data/remote/PhoneSignInHandler.java @@ -39,7 +39,7 @@ public void onActivityResult(int requestCode, int resultCode, @Nullable Intent d if (requestCode == RequestCodes.PHONE_FLOW) { IdpResponse response = IdpResponse.fromResultIntent(data); if (response == null) { - setResult(Resource.forFailure(new UserCancellationException())); + setResult(Resource.forFailure(new UserCancellationException())); } else { setResult(Resource.forSuccess(response)); } diff --git a/auth/src/main/java/com/firebase/ui/auth/data/remote/ProfileMerger.java b/auth/src/main/java/com/firebase/ui/auth/data/remote/ProfileMerger.java index 730e42d50..2eb19bd0c 100644 --- a/auth/src/main/java/com/firebase/ui/auth/data/remote/ProfileMerger.java +++ b/auth/src/main/java/com/firebase/ui/auth/data/remote/ProfileMerger.java @@ -52,11 +52,6 @@ public Task then(@NonNull Task task) { .setPhotoUri(photoUri) .build()) .addOnFailureListener(new TaskFailureLogger(TAG, "Error updating profile")) - .continueWithTask(new Continuation>() { - @Override - public Task then(@NonNull Task task) { - return Tasks.forResult(authResult); - } - }); + .continueWithTask(task1 -> Tasks.forResult(authResult)); } } diff --git a/auth/src/main/java/com/firebase/ui/auth/data/remote/SignInKickstarter.java b/auth/src/main/java/com/firebase/ui/auth/data/remote/SignInKickstarter.java index 9731903ce..5cc3a38f3 100644 --- a/auth/src/main/java/com/firebase/ui/auth/data/remote/SignInKickstarter.java +++ b/auth/src/main/java/com/firebase/ui/auth/data/remote/SignInKickstarter.java @@ -56,7 +56,7 @@ public SignInKickstarter(Application application) { public void start() { if (!TextUtils.isEmpty(getArguments().emailLink)) { - setResult(Resource.forFailure(new IntentRequiredException( + setResult(Resource.forFailure(new IntentRequiredException( EmailLinkCatcherActivity.createIntent(getApplication(), getArguments()), RequestCodes.EMAIL_FLOW))); return; @@ -68,25 +68,17 @@ public void start() { if (pendingResultTask != null) { pendingResultTask .addOnSuccessListener( - new OnSuccessListener() { - @Override - public void onSuccess(AuthResult authResult) { - final IdpResponse response = new IdpResponse.Builder( - new User.Builder( - authResult.getCredential().getProvider(), - authResult.getUser().getEmail()).build()) - .build(); - handleSuccess(response, authResult); + authResult -> { + final IdpResponse response = new IdpResponse.Builder( + new User.Builder( + authResult.getCredential().getProvider(), + authResult.getUser().getEmail()).build()) + .build(); + handleSuccess(response, authResult); - } }) .addOnFailureListener( - new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - setResult(Resource.forFailure(e)); - } - }); + e -> setResult(Resource.forFailure(e))); return; } @@ -100,30 +92,27 @@ public void onFailure(@NonNull Exception e) { boolean willRequestCredentials = supportPasswords || accountTypes.size() > 0; if (getArguments().enableCredentials && willRequestCredentials) { - setResult(Resource.forLoading()); + setResult(Resource.forLoading()); GoogleApiUtils.getCredentialsClient(getApplication()) .request(new CredentialRequest.Builder() .setPasswordLoginSupported(supportPasswords) .setAccountTypes(accountTypes.toArray(new String[accountTypes.size()])) .build()) - .addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - try { - handleCredential( - task.getResult(ApiException.class).getCredential()); - } catch (ResolvableApiException e) { - if (e.getStatusCode() == CommonStatusCodes.RESOLUTION_REQUIRED) { - setResult(Resource.forFailure( - new PendingIntentRequiredException( - e.getResolution(), RequestCodes.CRED_HINT))); - } else { - startAuthMethodChoice(); - } - } catch (ApiException e) { + .addOnCompleteListener(task -> { + try { + handleCredential( + task.getResult(ApiException.class).getCredential()); + } catch (ResolvableApiException e) { + if (e.getStatusCode() == CommonStatusCodes.RESOLUTION_REQUIRED) { + setResult(Resource.forFailure( + new PendingIntentRequiredException( + e.getResolution(), RequestCodes.CRED_HINT))); + } else { startAuthMethodChoice(); } + } catch (ApiException e) { + startAuthMethodChoice(); } }); } else { @@ -138,12 +127,12 @@ private void startAuthMethodChoice() { switch (firstProvider) { case EMAIL_LINK_PROVIDER: case EmailAuthProvider.PROVIDER_ID: - setResult(Resource.forFailure(new IntentRequiredException( + setResult(Resource.forFailure(new IntentRequiredException( EmailActivity.createIntent(getApplication(), getArguments()), RequestCodes.EMAIL_FLOW))); break; case PhoneAuthProvider.PROVIDER_ID: - setResult(Resource.forFailure(new IntentRequiredException( + setResult(Resource.forFailure(new IntentRequiredException( PhoneActivity.createIntent( getApplication(), getArguments(), firstIdpConfig.getParams()), RequestCodes.PHONE_FLOW))); @@ -153,7 +142,7 @@ private void startAuthMethodChoice() { break; } } else { - setResult(Resource.forFailure(new IntentRequiredException( + setResult(Resource.forFailure(new IntentRequiredException( AuthMethodPickerActivity.createIntent(getApplication(), getArguments()), RequestCodes.AUTH_PICKER_FLOW))); } @@ -162,14 +151,14 @@ private void startAuthMethodChoice() { private void redirectSignIn(String provider, String id) { switch (provider) { case EmailAuthProvider.PROVIDER_ID: - setResult(Resource.forFailure(new IntentRequiredException( + setResult(Resource.forFailure(new IntentRequiredException( EmailActivity.createIntent(getApplication(), getArguments(), id), RequestCodes.EMAIL_FLOW))); break; case PhoneAuthProvider.PROVIDER_ID: Bundle args = new Bundle(); args.putString(ExtraConstants.PHONE, id); - setResult(Resource.forFailure(new IntentRequiredException( + setResult(Resource.forFailure(new IntentRequiredException( PhoneActivity.createIntent( getApplication(), getArguments(), @@ -177,7 +166,7 @@ private void redirectSignIn(String provider, String id) { RequestCodes.PHONE_FLOW))); break; default: - setResult(Resource.forFailure(new IntentRequiredException( + setResult(Resource.forFailure(new IntentRequiredException( SingleSignInActivity.createIntent( getApplication(), getArguments(), @@ -216,14 +205,14 @@ public void onActivityResult(int requestCode, int resultCode, @Nullable Intent d } IdpResponse response = IdpResponse.fromResultIntent(data); if (response == null) { - setResult(Resource.forFailure(new UserCancellationException())); + setResult(Resource.forFailure(new UserCancellationException())); } else if (response.isSuccessful()) { setResult(Resource.forSuccess(response)); } else if (response.getError().getErrorCode() == ErrorCodes.ANONYMOUS_UPGRADE_MERGE_CONFLICT) { handleMergeFailure(response); } else { - setResult(Resource.forFailure(response.getError())); + setResult(Resource.forFailure(response.getError())); } } } @@ -243,27 +232,19 @@ private void handleCredential(final Credential credential) { final IdpResponse response = new IdpResponse.Builder( new User.Builder(EmailAuthProvider.PROVIDER_ID, id).build()).build(); - setResult(Resource.forLoading()); + setResult(Resource.forLoading()); getAuth().signInWithEmailAndPassword(id, password) - .addOnSuccessListener(new OnSuccessListener() { - @Override - public void onSuccess(AuthResult result) { - handleSuccess(response, result); - } - }) - .addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - if (e instanceof FirebaseAuthInvalidUserException - || e instanceof FirebaseAuthInvalidCredentialsException) { - // In this case the credential saved in SmartLock was not - // a valid credential, we should delete it from SmartLock - // before continuing. - GoogleApiUtils.getCredentialsClient(getApplication()) - .delete(credential); - } - startAuthMethodChoice(); + .addOnSuccessListener(result -> handleSuccess(response, result)) + .addOnFailureListener(e -> { + if (e instanceof FirebaseAuthInvalidUserException + || e instanceof FirebaseAuthInvalidCredentialsException) { + // In this case the credential saved in SmartLock was not + // a valid credential, we should delete it from SmartLock + // before continuing. + GoogleApiUtils.getCredentialsClient(getApplication()) + .delete(credential); } + startAuthMethodChoice(); }); } } diff --git a/auth/src/main/java/com/firebase/ui/auth/ui/InvisibleActivityBase.java b/auth/src/main/java/com/firebase/ui/auth/ui/InvisibleActivityBase.java index a950a07db..9767f8944 100644 --- a/auth/src/main/java/com/firebase/ui/auth/ui/InvisibleActivityBase.java +++ b/auth/src/main/java/com/firebase/ui/auth/ui/InvisibleActivityBase.java @@ -63,24 +63,16 @@ public void showProgress(int message) { @Override public void hideProgress() { - doAfterTimeout(new Runnable() { - @Override - public void run() { - mLastShownTime = 0; - mProgressBar.setVisibility(View.GONE); - } + doAfterTimeout(() -> { + mLastShownTime = 0; + mProgressBar.setVisibility(View.GONE); }); } @Override public void finish(int resultCode, @Nullable Intent intent) { setResult(resultCode, intent); - doAfterTimeout(new Runnable() { - @Override - public void run() { - finish(); - } - }); + doAfterTimeout(() -> finish()); } /** diff --git a/auth/src/main/java/com/firebase/ui/auth/ui/InvisibleFragmentBase.java b/auth/src/main/java/com/firebase/ui/auth/ui/InvisibleFragmentBase.java index 7b54ec617..c57b824b6 100644 --- a/auth/src/main/java/com/firebase/ui/auth/ui/InvisibleFragmentBase.java +++ b/auth/src/main/java/com/firebase/ui/auth/ui/InvisibleFragmentBase.java @@ -60,13 +60,10 @@ public void showProgress(int message) { @Override public void hideProgress() { - doAfterTimeout(new Runnable() { - @Override - public void run() { - mLastShownTime = 0; - mProgressBar.setVisibility(View.GONE); - mFrameLayout.setVisibility(View.GONE); - } + doAfterTimeout(() -> { + mLastShownTime = 0; + mProgressBar.setVisibility(View.GONE); + mFrameLayout.setVisibility(View.GONE); }); } diff --git a/auth/src/main/java/com/firebase/ui/auth/ui/email/CheckEmailHandler.java b/auth/src/main/java/com/firebase/ui/auth/ui/email/CheckEmailHandler.java index 13f0360b4..7498d7c39 100644 --- a/auth/src/main/java/com/firebase/ui/auth/ui/email/CheckEmailHandler.java +++ b/auth/src/main/java/com/firebase/ui/auth/ui/email/CheckEmailHandler.java @@ -25,7 +25,7 @@ public CheckEmailHandler(Application application) { } public void fetchCredential() { - setResult(Resource.forFailure(new PendingIntentRequiredException( + setResult(Resource.forFailure(new PendingIntentRequiredException( Credentials.getClient(getApplication()).getHintPickerIntent( new HintRequest.Builder().setEmailAddressIdentifierSupported(true).build()), RequestCodes.CRED_HINT @@ -33,17 +33,14 @@ public void fetchCredential() { } public void fetchProvider(final String email) { - setResult(Resource.forLoading()); + setResult(Resource.forLoading()); ProviderUtils.fetchTopProvider(getAuth(), getArguments(), email) - .addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - if (task.isSuccessful()) { - setResult(Resource.forSuccess( - new User.Builder(task.getResult(), email).build())); - } else { - setResult(Resource.forFailure(task.getException())); - } + .addOnCompleteListener(task -> { + if (task.isSuccessful()) { + setResult(Resource.forSuccess( + new User.Builder(task.getResult(), email).build())); + } else { + setResult(Resource.forFailure(task.getException())); } }); } @@ -51,21 +48,18 @@ public void onComplete(@NonNull Task task) { public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if (requestCode != RequestCodes.CRED_HINT || resultCode != Activity.RESULT_OK) { return; } - setResult(Resource.forLoading()); + setResult(Resource.forLoading()); final Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY); final String email = credential.getId(); ProviderUtils.fetchTopProvider(getAuth(), getArguments(), email) - .addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - if (task.isSuccessful()) { - setResult(Resource.forSuccess(new User.Builder(task.getResult(), email) - .setName(credential.getName()) - .setPhotoUri(credential.getProfilePictureUri()) - .build())); - } else { - setResult(Resource.forFailure(task.getException())); - } + .addOnCompleteListener(task -> { + if (task.isSuccessful()) { + setResult(Resource.forSuccess(new User.Builder(task.getResult(), email) + .setName(credential.getName()) + .setPhotoUri(credential.getProfilePictureUri()) + .build())); + } else { + setResult(Resource.forFailure(task.getException())); } }); } diff --git a/auth/src/main/java/com/firebase/ui/auth/ui/email/EmailLinkCatcherActivity.java b/auth/src/main/java/com/firebase/ui/auth/ui/email/EmailLinkCatcherActivity.java index e5faf6baf..50a7bfb0f 100644 --- a/auth/src/main/java/com/firebase/ui/auth/ui/email/EmailLinkCatcherActivity.java +++ b/auth/src/main/java/com/firebase/ui/auth/ui/email/EmailLinkCatcherActivity.java @@ -118,11 +118,7 @@ private AlertDialog buildAlertDialog(final int errorCode) { return alertDialog.setTitle(titleText) .setMessage(messageText) .setPositiveButton(R.string.fui_email_link_dismiss_button, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - finish(errorCode, null); - } - }) + (dialog, id) -> finish(errorCode, null)) .create(); } diff --git a/auth/src/main/java/com/firebase/ui/auth/ui/email/EmailLinkFragment.java b/auth/src/main/java/com/firebase/ui/auth/ui/email/EmailLinkFragment.java index a74b1db32..27ce2ddbe 100644 --- a/auth/src/main/java/com/firebase/ui/auth/ui/email/EmailLinkFragment.java +++ b/auth/src/main/java/com/firebase/ui/auth/ui/email/EmailLinkFragment.java @@ -124,12 +124,7 @@ private void initHandler() { @Override protected void onSuccess(@NonNull String email) { Log.w(TAG, "Email for email link sign in sent successfully."); - doAfterTimeout(new Runnable() { - @Override - public void run() { - mTopLevelView.setVisibility(View.VISIBLE); - } - }); + doAfterTimeout(() -> mTopLevelView.setVisibility(View.VISIBLE)); mEmailSent = true; } @@ -150,12 +145,7 @@ private void setBodyText(View view, final String email) { } private void setOnClickListeners(View view, final String email) { - view.findViewById(R.id.trouble_signing_in).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - mListener.onTroubleSigningIn(email); - } - }); + view.findViewById(R.id.trouble_signing_in).setOnClickListener(v -> mListener.onTroubleSigningIn(email)); } private void setPrivacyFooter(View view) { diff --git a/auth/src/main/java/com/firebase/ui/auth/ui/email/RecoverPasswordActivity.java b/auth/src/main/java/com/firebase/ui/auth/ui/email/RecoverPasswordActivity.java index c1409e546..2bb2e1913 100644 --- a/auth/src/main/java/com/firebase/ui/auth/ui/email/RecoverPasswordActivity.java +++ b/auth/src/main/java/com/firebase/ui/auth/ui/email/RecoverPasswordActivity.java @@ -135,12 +135,7 @@ private void showEmailSentDialog(String email) { new AlertDialog.Builder(this) .setTitle(R.string.fui_title_confirm_recover_password) .setMessage(getString(R.string.fui_confirm_recovery_body, email)) - .setOnDismissListener(new DialogInterface.OnDismissListener() { - @Override - public void onDismiss(DialogInterface dialog) { - finish(RESULT_OK, new Intent()); - } - }) + .setOnDismissListener(dialog -> finish(RESULT_OK, new Intent())) .setPositiveButton(android.R.string.ok, null) .show(); } diff --git a/auth/src/main/java/com/firebase/ui/auth/ui/email/RegisterEmailFragment.java b/auth/src/main/java/com/firebase/ui/auth/ui/email/RegisterEmailFragment.java index 623e0f6dc..d1d2d21f4 100644 --- a/auth/src/main/java/com/firebase/ui/auth/ui/email/RegisterEmailFragment.java +++ b/auth/src/main/java/com/firebase/ui/auth/ui/email/RegisterEmailFragment.java @@ -206,12 +206,7 @@ public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceStat } private void safeRequestFocus(final View v) { - v.post(new Runnable() { - @Override - public void run() { - v.requestFocus(); - } - }); + v.post(() -> v.requestFocus()); } @Override diff --git a/auth/src/main/java/com/firebase/ui/auth/ui/idp/AuthMethodPickerActivity.java b/auth/src/main/java/com/firebase/ui/auth/ui/idp/AuthMethodPickerActivity.java index 1de2a3338..58a1c7fcf 100644 --- a/auth/src/main/java/com/firebase/ui/auth/ui/idp/AuthMethodPickerActivity.java +++ b/auth/src/main/java/com/firebase/ui/auth/ui/idp/AuthMethodPickerActivity.java @@ -356,17 +356,14 @@ private void handleResponse(@NonNull IdpResponse response) { } } }); - view.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (isOffline()) { - Snackbar.make(findViewById(android.R.id.content), getString(R.string.fui_no_internet), Snackbar.LENGTH_SHORT).show(); - return; - } - - provider.startSignIn(getAuth(), AuthMethodPickerActivity.this, - idpConfig.getProviderId()); + view.setOnClickListener(view1 -> { + if (isOffline()) { + Snackbar.make(findViewById(android.R.id.content), getString(R.string.fui_no_internet), Snackbar.LENGTH_SHORT).show(); + return; } + + provider.startSignIn(getAuth(), AuthMethodPickerActivity.this, + idpConfig.getProviderId()); }); } diff --git a/auth/src/main/java/com/firebase/ui/auth/ui/idp/WelcomeBackIdpPrompt.java b/auth/src/main/java/com/firebase/ui/auth/ui/idp/WelcomeBackIdpPrompt.java index 1da1ba20d..0f3e2319c 100644 --- a/auth/src/main/java/com/firebase/ui/auth/ui/idp/WelcomeBackIdpPrompt.java +++ b/auth/src/main/java/com/firebase/ui/auth/ui/idp/WelcomeBackIdpPrompt.java @@ -177,12 +177,7 @@ protected void onFailure(@NonNull Exception e) { existingUser.getEmail(), providerName)); - mDoneButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - mProvider.startSignIn(getAuth(), WelcomeBackIdpPrompt.this, providerId); - } - }); + mDoneButton.setOnClickListener(view -> mProvider.startSignIn(getAuth(), WelcomeBackIdpPrompt.this, providerId)); handler.getOperation().observe(this, new ResourceObserver(this) { @Override diff --git a/auth/src/main/java/com/firebase/ui/auth/ui/phone/CheckPhoneHandler.java b/auth/src/main/java/com/firebase/ui/auth/ui/phone/CheckPhoneHandler.java index 325f0d2b1..63a38b54d 100644 --- a/auth/src/main/java/com/firebase/ui/auth/ui/phone/CheckPhoneHandler.java +++ b/auth/src/main/java/com/firebase/ui/auth/ui/phone/CheckPhoneHandler.java @@ -24,7 +24,7 @@ public CheckPhoneHandler(Application application) { } public void fetchCredential() { - setResult(Resource.forFailure(new PendingIntentRequiredException( + setResult(Resource.forFailure(new PendingIntentRequiredException( Credentials.getClient(getApplication()).getHintPickerIntent( new HintRequest.Builder().setPhoneNumberIdentifierSupported(true).build()), RequestCodes.CRED_HINT diff --git a/auth/src/main/java/com/firebase/ui/auth/ui/phone/CheckPhoneNumberFragment.java b/auth/src/main/java/com/firebase/ui/auth/ui/phone/CheckPhoneNumberFragment.java index 588485be2..573bdf88a 100644 --- a/auth/src/main/java/com/firebase/ui/auth/ui/phone/CheckPhoneNumberFragment.java +++ b/auth/src/main/java/com/firebase/ui/auth/ui/phone/CheckPhoneNumberFragment.java @@ -92,12 +92,7 @@ public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceStat } requireActivity().setTitle(getString(R.string.fui_verify_phone_number_title)); - ImeHelper.setImeOnDoneListener(mPhoneEditText, new ImeHelper.DonePressedListener() { - @Override - public void onDonePressed() { - onNext(); - } - }); + ImeHelper.setImeOnDoneListener(mPhoneEditText, () -> onNext()); mSubmitButton.setOnClickListener(this); setupPrivacyDisclosures(); @@ -207,12 +202,7 @@ private void setupCountrySpinner() { mCountryListSpinner.init(params); // Clear error when spinner is clicked on - mCountryListSpinner.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - mPhoneInputLayout.setError(null); - } - }); + mCountryListSpinner.setOnClickListener(v -> mPhoneInputLayout.setError(null)); } private void setDefaultCountryForSpinner() { diff --git a/auth/src/main/java/com/firebase/ui/auth/ui/phone/CountryListSpinner.java b/auth/src/main/java/com/firebase/ui/auth/ui/phone/CountryListSpinner.java index 3b94a4690..6fd11f641 100644 --- a/auth/src/main/java/com/firebase/ui/auth/ui/phone/CountryListSpinner.java +++ b/auth/src/main/java/com/firebase/ui/auth/ui/phone/CountryListSpinner.java @@ -288,12 +288,7 @@ public void show(final int selected) { final ListView listView = dialog.getListView(); listView.setFastScrollEnabled(true); listView.setScrollbarFadingEnabled(false); - listView.postDelayed(new Runnable() { - @Override - public void run() { - listView.setSelection(selected); - } - }, DELAY_MILLIS); + listView.postDelayed(() -> listView.setSelection(selected), DELAY_MILLIS); dialog.show(); } diff --git a/auth/src/main/java/com/firebase/ui/auth/ui/phone/PhoneNumberVerificationHandler.java b/auth/src/main/java/com/firebase/ui/auth/ui/phone/PhoneNumberVerificationHandler.java index f096b31bf..16d032986 100644 --- a/auth/src/main/java/com/firebase/ui/auth/ui/phone/PhoneNumberVerificationHandler.java +++ b/auth/src/main/java/com/firebase/ui/auth/ui/phone/PhoneNumberVerificationHandler.java @@ -29,7 +29,7 @@ public PhoneNumberVerificationHandler(Application application) { } public void verifyPhoneNumber(@NonNull Activity activity, final String number, boolean force) { - setResult(Resource.forLoading()); + setResult(Resource.forLoading()); PhoneAuthOptions.Builder optionsBuilder = PhoneAuthOptions.newBuilder(getAuth()) .setPhoneNumber(number) .setTimeout(AUTO_RETRIEVAL_TIMEOUT_SECONDS, TimeUnit.SECONDS) @@ -43,7 +43,7 @@ public void onVerificationCompleted(@NonNull PhoneAuthCredential credential) { @Override public void onVerificationFailed(@NonNull FirebaseException e) { - setResult(Resource.forFailure(e)); + setResult(Resource.forFailure(e)); } @Override @@ -51,7 +51,7 @@ public void onCodeSent(@NonNull String verificationId, @NonNull PhoneAuthProvider.ForceResendingToken token) { mVerificationId = verificationId; mForceResendingToken = token; - setResult(Resource.forFailure( + setResult(Resource.forFailure( new PhoneNumberVerificationRequiredException(number))); } }); diff --git a/auth/src/main/java/com/firebase/ui/auth/ui/phone/SubmitConfirmationCodeFragment.java b/auth/src/main/java/com/firebase/ui/auth/ui/phone/SubmitConfirmationCodeFragment.java index 572e9c30d..26badc4b0 100644 --- a/auth/src/main/java/com/firebase/ui/auth/ui/phone/SubmitConfirmationCodeFragment.java +++ b/auth/src/main/java/com/firebase/ui/auth/ui/phone/SubmitConfirmationCodeFragment.java @@ -59,12 +59,7 @@ public class SubmitConfirmationCodeFragment extends FragmentBase { private static final String EXTRA_MILLIS_UNTIL_FINISHED = "millis_until_finished"; private final Handler mLooper = new Handler(); - private final Runnable mCountdown = new Runnable() { - @Override - public void run() { - processCountdownTick(); - } - }; + private final Runnable mCountdown = () -> processCountdownTick(); private PhoneNumberVerificationHandler mHandler; private String mPhoneNumber; @@ -121,7 +116,7 @@ public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceStat PrivacyDisclosureUtils.setupTermsOfServiceFooter( requireContext(), getFlowParams(), - view.findViewById(R.id.email_footer_tos_and_pp_text)); + view.findViewById(R.id.email_footer_tos_and_pp_text)); } @Override @@ -130,12 +125,9 @@ public void onActivityCreated(@Nullable Bundle savedInstanceState) { new ViewModelProvider(requireActivity()) .get(PhoneProviderResponseHandler.class) .getOperation() - .observe(getViewLifecycleOwner(), new Observer>() { - @Override - public void onChanged(@Nullable Resource resource) { - if (resource.getState() == State.FAILURE) { - mConfirmationCodeEditText.setText(""); - } + .observe(getViewLifecycleOwner(), resource -> { + if (resource.getState() == State.FAILURE) { + mConfirmationCodeEditText.setText(""); } }); } @@ -208,27 +200,19 @@ public void whileIncomplete() {} private void setupEditPhoneNumberTextView() { mPhoneTextView.setText(mPhoneNumber); - mPhoneTextView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - requireActivity().getSupportFragmentManager().popBackStack(); - } - }); + mPhoneTextView.setOnClickListener(v -> requireActivity().getSupportFragmentManager().popBackStack()); } private void setupResendConfirmationCodeTextView() { - mResendCodeTextView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - mHandler.verifyPhoneNumber(requireActivity(), mPhoneNumber, true); - - mResendCodeTextView.setVisibility(View.GONE); - mCountDownTextView.setVisibility(View.VISIBLE); - mCountDownTextView.setText(String.format(getString(R.string.fui_resend_code_in), - RESEND_WAIT_MILLIS / 1000)); - mMillisUntilFinished = RESEND_WAIT_MILLIS; - mLooper.postDelayed(mCountdown, TICK_INTERVAL_MILLIS); - } + mResendCodeTextView.setOnClickListener(v -> { + mHandler.verifyPhoneNumber(requireActivity(), mPhoneNumber, true); + + mResendCodeTextView.setVisibility(View.GONE); + mCountDownTextView.setVisibility(View.VISIBLE); + mCountDownTextView.setText(String.format(getString(R.string.fui_resend_code_in), + RESEND_WAIT_MILLIS / 1000)); + mMillisUntilFinished = RESEND_WAIT_MILLIS; + mLooper.postDelayed(mCountdown, TICK_INTERVAL_MILLIS); }); } diff --git a/auth/src/main/java/com/firebase/ui/auth/util/data/AuthOperationManager.java b/auth/src/main/java/com/firebase/ui/auth/util/data/AuthOperationManager.java index 97fcb2ece..db016ccef 100644 --- a/auth/src/main/java/com/firebase/ui/auth/util/data/AuthOperationManager.java +++ b/auth/src/main/java/com/firebase/ui/auth/util/data/AuthOperationManager.java @@ -99,14 +99,11 @@ public Task safeLink(final AuthCredential credential, final FlowParameters flowParameters) { return getScratchAuth(flowParameters) .signInWithCredential(credential) - .continueWithTask(new Continuation>() { - @Override - public Task then(@NonNull Task task) throws Exception { - if (task.isSuccessful()) { - return task.getResult().getUser().linkWithCredential(credentialToLink); - } - return task; + .continueWithTask(task -> { + if (task.isSuccessful()) { + return task.getResult().getUser().linkWithCredential(credentialToLink); } + return task; }); } diff --git a/auth/src/main/java/com/firebase/ui/auth/util/data/ProviderUtils.java b/auth/src/main/java/com/firebase/ui/auth/util/data/ProviderUtils.java index b00e0f87d..e1d3d8681 100644 --- a/auth/src/main/java/com/firebase/ui/auth/util/data/ProviderUtils.java +++ b/auth/src/main/java/com/firebase/ui/auth/util/data/ProviderUtils.java @@ -264,19 +264,16 @@ public static Task fetchTopProvider( @NonNull FlowParameters params, @NonNull String email) { return fetchSortedProviders(auth, params, email) - .continueWithTask(new Continuation, Task>() { - @Override - public Task then(@NonNull Task> task) { - if (!task.isSuccessful()) { - return Tasks.forException(task.getException()); - } - List providers = task.getResult(); + .continueWithTask(task -> { + if (!task.isSuccessful()) { + return Tasks.forException(task.getException()); + } + List providers = task.getResult(); - if (providers.isEmpty()) { - return Tasks.forResult(null); - } else { - return Tasks.forResult(providers.get(0)); - } + if (providers.isEmpty()) { + return Tasks.forResult(null); + } else { + return Tasks.forResult(providers.get(0)); } }); } diff --git a/auth/src/main/java/com/firebase/ui/auth/util/ui/ImeHelper.java b/auth/src/main/java/com/firebase/ui/auth/util/ui/ImeHelper.java index de14925d7..9421db3b0 100644 --- a/auth/src/main/java/com/firebase/ui/auth/util/ui/ImeHelper.java +++ b/auth/src/main/java/com/firebase/ui/auth/util/ui/ImeHelper.java @@ -17,23 +17,20 @@ public interface DonePressedListener { public static void setImeOnDoneListener(EditText doneEditText, final DonePressedListener listener) { - doneEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView view, int actionId, KeyEvent event) { - if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) { - if (event.getAction() == KeyEvent.ACTION_UP) { - listener.onDonePressed(); - } - - // We need to return true even if we didn't handle the event to continue - // receiving future callbacks. - return true; - } else if (actionId == EditorInfo.IME_ACTION_DONE) { + doneEditText.setOnEditorActionListener((view, actionId, event) -> { + if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) { + if (event.getAction() == KeyEvent.ACTION_UP) { listener.onDonePressed(); - return true; } - return false; + + // We need to return true even if we didn't handle the event to continue + // receiving future callbacks. + return true; + } else if (actionId == EditorInfo.IME_ACTION_DONE) { + listener.onDonePressed(); + return true; } + return false; }); } } diff --git a/auth/src/main/java/com/firebase/ui/auth/viewmodel/SignInViewModelBase.java b/auth/src/main/java/com/firebase/ui/auth/viewmodel/SignInViewModelBase.java index c0594db1c..97e48b46d 100644 --- a/auth/src/main/java/com/firebase/ui/auth/viewmodel/SignInViewModelBase.java +++ b/auth/src/main/java/com/firebase/ui/auth/viewmodel/SignInViewModelBase.java @@ -36,7 +36,7 @@ protected void handleMergeFailure(@NonNull AuthCredential credential) { } protected void handleMergeFailure(@NonNull IdpResponse failureResponse) { - setResult(Resource.forFailure(new FirebaseAuthAnonymousUpgradeException( + setResult(Resource.forFailure(new FirebaseAuthAnonymousUpgradeException( ErrorCodes.ANONYMOUS_UPGRADE_MERGE_CONFLICT, failureResponse))); } diff --git a/auth/src/main/java/com/firebase/ui/auth/viewmodel/email/EmailLinkSendEmailHandler.java b/auth/src/main/java/com/firebase/ui/auth/viewmodel/email/EmailLinkSendEmailHandler.java index 9c92a2018..f53c092b1 100644 --- a/auth/src/main/java/com/firebase/ui/auth/viewmodel/email/EmailLinkSendEmailHandler.java +++ b/auth/src/main/java/com/firebase/ui/auth/viewmodel/email/EmailLinkSendEmailHandler.java @@ -30,7 +30,7 @@ public void sendSignInLinkToEmail(@NonNull final String email, if (getAuth() == null) { return; } - setResult(Resource.forLoading()); + setResult(Resource.forLoading()); final String anonymousUserId = AuthOperationManager.getInstance().canUpgradeAnonymous(getAuth(), getArguments()) @@ -42,17 +42,14 @@ public void sendSignInLinkToEmail(@NonNull final String email, sessionId, anonymousUserId, idpResponseForLinking, forceSameDevice); getAuth().sendSignInLinkToEmail(email, mutatedSettings) - .addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - if (task.isSuccessful()) { - EmailLinkPersistenceManager.getInstance().saveEmail(getApplication(), - email, sessionId, anonymousUserId); + .addOnCompleteListener(task -> { + if (task.isSuccessful()) { + EmailLinkPersistenceManager.getInstance().saveEmail(getApplication(), + email, sessionId, anonymousUserId); - setResult(Resource.forSuccess(email)); - } else { - setResult(Resource.forFailure(task.getException())); - } + setResult(Resource.forSuccess(email)); + } else { + setResult(Resource.forFailure(task.getException())); } }); } diff --git a/auth/src/main/java/com/firebase/ui/auth/viewmodel/email/EmailLinkSignInHandler.java b/auth/src/main/java/com/firebase/ui/auth/viewmodel/email/EmailLinkSignInHandler.java index 0436eeac9..33f494218 100644 --- a/auth/src/main/java/com/firebase/ui/auth/viewmodel/email/EmailLinkSignInHandler.java +++ b/auth/src/main/java/com/firebase/ui/auth/viewmodel/email/EmailLinkSignInHandler.java @@ -41,11 +41,11 @@ public EmailLinkSignInHandler(Application application) { } public void startSignIn() { - setResult(Resource.forLoading()); + setResult(Resource.forLoading()); String link = getArguments().emailLink; if (!getAuth().isSignInWithEmailLink(link)) { - setResult(Resource.forFailure( + setResult(Resource.forFailure( new FirebaseUiException(ErrorCodes.INVALID_EMAIL_LINK_ERROR))); return; } @@ -65,14 +65,14 @@ public void startSignIn() { if (isDifferentDeviceFlow(sessionRecord, sessionIdFromLink)) { if (TextUtils.isEmpty(sessionIdFromLink)) { // There should always be a valid session ID in the link - setResult(Resource.forFailure( + setResult(Resource.forFailure( new FirebaseUiException(ErrorCodes.INVALID_EMAIL_LINK_ERROR))); return; } if (forceSameDevice || !TextUtils.isEmpty(anonymousUserIdFromLink)) { // In both cases, the link was meant to be completed on the same device. // For anonymous user upgrade, we don't support the cross device flow. - setResult(Resource.forFailure( + setResult(Resource.forFailure( new FirebaseUiException(ErrorCodes.EMAIL_LINK_WRONG_DEVICE_ERROR))); return; } @@ -89,7 +89,7 @@ public void startSignIn() { if (getAuth().getCurrentUser() == null || (getAuth().getCurrentUser().isAnonymous() && !anonymousUserIdFromLink.equals(getAuth().getCurrentUser().getUid()))) { - setResult(Resource.forFailure( + setResult(Resource.forFailure( new FirebaseUiException( ErrorCodes.EMAIL_LINK_DIFFERENT_ANONYMOUS_USER_ERROR))); return; @@ -100,7 +100,7 @@ public void startSignIn() { } public void finishSignIn(String email) { - setResult(Resource.forLoading()); + setResult(Resource.forLoading()); finishSignIn(email, /*response=*/null); } @@ -112,7 +112,7 @@ private void finishSignIn(SessionRecord sessionRecord) { private void finishSignIn(@NonNull String email, @Nullable IdpResponse response) { if (TextUtils.isEmpty(email)) { - setResult(Resource.forFailure( + setResult(Resource.forFailure( new FirebaseUiException(ErrorCodes.EMAIL_MISMATCH_ERROR))); return; } @@ -130,24 +130,21 @@ private void finishSignIn(@NonNull String email, @Nullable IdpResponse response) private void determineDifferentDeviceErrorFlowAndFinish(@NonNull String oobCode, @Nullable final String providerId) { getAuth().checkActionCode(oobCode).addOnCompleteListener( - new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - if (task.isSuccessful()) { - if (!TextUtils.isEmpty(providerId)) { - setResult(Resource.forFailure( - new FirebaseUiException( - ErrorCodes.EMAIL_LINK_CROSS_DEVICE_LINKING_ERROR))); - return; - } - // The email link is valid, we can ask the user for their email - setResult(Resource.forFailure( - new FirebaseUiException( - ErrorCodes.EMAIL_LINK_PROMPT_FOR_EMAIL_ERROR))); - } else { - setResult(Resource.forFailure( - new FirebaseUiException(ErrorCodes.INVALID_EMAIL_LINK_ERROR))); + task -> { + if (task.isSuccessful()) { + if (!TextUtils.isEmpty(providerId)) { + setResult(Resource.forFailure( + new FirebaseUiException( + ErrorCodes.EMAIL_LINK_CROSS_DEVICE_LINKING_ERROR))); + return; } + // The email link is valid, we can ask the user for their email + setResult(Resource.forFailure( + new FirebaseUiException( + ErrorCodes.EMAIL_LINK_PROMPT_FOR_EMAIL_ERROR))); + } else { + setResult(Resource.forFailure( + new FirebaseUiException(ErrorCodes.INVALID_EMAIL_LINK_ERROR))); } }); } @@ -164,54 +161,40 @@ private void handleLinkingFlow(final AuthOperationManager authOperationManager, if (authOperationManager.canUpgradeAnonymous(getAuth(), getArguments())) { authOperationManager.safeLink(emailLinkCredential, storedCredentialForLink, getArguments()) - .addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - persistenceManager.clearAllData(getApplication()); - if (task.isSuccessful()) { - handleMergeFailure(storedCredentialForLink); - } else { - setResult(Resource.forFailure(task.getException())); - } + .addOnCompleteListener(task -> { + persistenceManager.clearAllData(getApplication()); + if (task.isSuccessful()) { + handleMergeFailure(storedCredentialForLink); + } else { + setResult(Resource.forFailure(task.getException())); } }); } else { getAuth().signInWithCredential(emailLinkCredential) - .continueWithTask(new Continuation>() { - @Override - public Task then(@NonNull Task task) { - persistenceManager.clearAllData(getApplication()); - if (!task.isSuccessful()) { - return task; - } - return task.getResult().getUser() - .linkWithCredential(storedCredentialForLink) - .continueWithTask(new ProfileMerger(response)) - .addOnFailureListener(new TaskFailureLogger(TAG, - "linkWithCredential+merge failed.")); + .continueWithTask(task -> { + persistenceManager.clearAllData(getApplication()); + if (!task.isSuccessful()) { + return task; } + return task.getResult().getUser() + .linkWithCredential(storedCredentialForLink) + .continueWithTask(new ProfileMerger(response)) + .addOnFailureListener(new TaskFailureLogger(TAG, + "linkWithCredential+merge failed.")); }) - .addOnSuccessListener(new OnSuccessListener() { - @Override - public void onSuccess(AuthResult authResult) { - FirebaseUser user = authResult.getUser(); - IdpResponse response = new IdpResponse.Builder( - new User.Builder(EmailAuthProvider - .EMAIL_LINK_SIGN_IN_METHOD, - user.getEmail()) - .setName(user.getDisplayName()) - .setPhotoUri(user.getPhotoUrl()) - .build()) - .build(); - handleSuccess(response, authResult); - } + .addOnSuccessListener(authResult -> { + FirebaseUser user = authResult.getUser(); + IdpResponse response1 = new IdpResponse.Builder( + new User.Builder(EmailAuthProvider + .EMAIL_LINK_SIGN_IN_METHOD, + user.getEmail()) + .setName(user.getDisplayName()) + .setPhotoUri(user.getPhotoUrl()) + .build()) + .build(); + handleSuccess(response1, authResult); }) - .addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - setResult(Resource.forFailure(e)); - } - }); + .addOnFailureListener(e -> setResult(Resource.forFailure(e))); } } @@ -230,31 +213,25 @@ private void handleNormalFlow(final AuthOperationManager authOperationManager, // Either regular sign in or anonymous user upgrade authOperationManager.signInAndLinkWithCredential(getAuth(), getArguments(), emailLinkCredential) - .addOnSuccessListener(new OnSuccessListener() { - @Override - public void onSuccess(AuthResult authResult) { - persistenceManager.clearAllData(getApplication()); - - FirebaseUser user = authResult.getUser(); - IdpResponse response = new IdpResponse.Builder( - new User.Builder(EMAIL_LINK_PROVIDER, - user.getEmail()) - .setName(user.getDisplayName()) - .setPhotoUri(user.getPhotoUrl()) - .build()) - .build(); - handleSuccess(response, authResult); - } + .addOnSuccessListener(authResult -> { + persistenceManager.clearAllData(getApplication()); + + FirebaseUser user = authResult.getUser(); + IdpResponse response = new IdpResponse.Builder( + new User.Builder(EMAIL_LINK_PROVIDER, + user.getEmail()) + .setName(user.getDisplayName()) + .setPhotoUri(user.getPhotoUrl()) + .build()) + .build(); + handleSuccess(response, authResult); }) - .addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - persistenceManager.clearAllData(getApplication()); - if (e instanceof FirebaseAuthUserCollisionException) { - handleMergeFailure(emailLinkCredentialForLinking); - } else { - setResult(Resource.forFailure(e)); - } + .addOnFailureListener(e -> { + persistenceManager.clearAllData(getApplication()); + if (e instanceof FirebaseAuthUserCollisionException) { + handleMergeFailure(emailLinkCredentialForLinking); + } else { + setResult(Resource.forFailure(e)); } }); } diff --git a/auth/src/main/java/com/firebase/ui/auth/viewmodel/email/EmailProviderResponseHandler.java b/auth/src/main/java/com/firebase/ui/auth/viewmodel/email/EmailProviderResponseHandler.java index f8adbc519..96cdaa8c6 100644 --- a/auth/src/main/java/com/firebase/ui/auth/viewmodel/email/EmailProviderResponseHandler.java +++ b/auth/src/main/java/com/firebase/ui/auth/viewmodel/email/EmailProviderResponseHandler.java @@ -41,14 +41,14 @@ public EmailProviderResponseHandler(Application application) { public void startSignIn(@NonNull final IdpResponse response, @NonNull final String password) { if (!response.isSuccessful()) { - setResult(Resource.forFailure(response.getError())); + setResult(Resource.forFailure(response.getError())); return; } if (!response.getProviderType().equals(EmailAuthProvider.PROVIDER_ID)) { throw new IllegalStateException( "This handler can only be used with the email provider"); } - setResult(Resource.forLoading()); + setResult(Resource.forLoading()); final AuthOperationManager authOperationManager = AuthOperationManager.getInstance(); final String email = response.getEmail(); @@ -58,39 +58,27 @@ public void startSignIn(@NonNull final IdpResponse response, @NonNull final Stri password) .continueWithTask(new ProfileMerger(response)) .addOnFailureListener(new TaskFailureLogger(TAG, "Error creating user")) - .addOnSuccessListener(new OnSuccessListener() { - @Override - public void onSuccess(AuthResult result) { - handleSuccess(response, result); - } - }) - .addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - if (e instanceof FirebaseAuthUserCollisionException) { - if (authOperationManager.canUpgradeAnonymous(getAuth(), - getArguments())) { - AuthCredential credential = EmailAuthProvider.getCredential(email, - password); - handleMergeFailure(credential); - } else { - Log.w(TAG, "Got a collision error during a non-upgrade flow", e); - - // Collision with existing user email without anonymous upgrade - // it should be very hard for the user to even get to this error - // due to CheckEmailFragment. - ProviderUtils.fetchTopProvider(getAuth(), getArguments(), email) - .addOnSuccessListener(new StartWelcomeBackFlow(email)) - .addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - setResult(Resource.forFailure(e)); - } - }); - } + .addOnSuccessListener(result -> handleSuccess(response, result)) + .addOnFailureListener(e -> { + if (e instanceof FirebaseAuthUserCollisionException) { + if (authOperationManager.canUpgradeAnonymous(getAuth(), + getArguments())) { + AuthCredential credential = EmailAuthProvider.getCredential(email, + password); + handleMergeFailure(credential); } else { - setResult(Resource.forFailure(e)); + Log.w(TAG, "Got a collision error during a non-upgrade flow", e); + + // Collision with existing user email without anonymous upgrade + // it should be very hard for the user to even get to this error + // due to CheckEmailFragment. + ProviderUtils.fetchTopProvider(getAuth(), getArguments(), email) + .addOnSuccessListener(new StartWelcomeBackFlow(email)) + .addOnFailureListener(e1 -> setResult(Resource.forFailure( + e1))); } + } else { + setResult(Resource.forFailure(e)); } }); } @@ -108,13 +96,13 @@ public void onSuccess(@Nullable String provider) { Log.w(TAG, "No providers known for user (" + mEmail + ") this email address may be reserved."); - setResult(Resource.forFailure( + setResult(Resource.forFailure( new FirebaseUiException(ErrorCodes.UNKNOWN_ERROR))); return; } if (EmailAuthProvider.PROVIDER_ID.equalsIgnoreCase(provider)) { - setResult(Resource.forFailure(new IntentRequiredException( + setResult(Resource.forFailure(new IntentRequiredException( WelcomeBackPasswordPrompt.createIntent( getApplication(), getArguments(), @@ -124,7 +112,7 @@ public void onSuccess(@Nullable String provider) { RequestCodes.WELCOME_BACK_EMAIL_FLOW ))); } else if (EMAIL_LINK_PROVIDER.equalsIgnoreCase(provider)) { - setResult(Resource.forFailure(new IntentRequiredException( + setResult(Resource.forFailure(new IntentRequiredException( WelcomeBackEmailLinkPrompt.createIntent( getApplication(), getArguments(), @@ -134,7 +122,7 @@ public void onSuccess(@Nullable String provider) { RequestCodes.WELCOME_BACK_EMAIL_LINK_FLOW ))); } else { - setResult(Resource.forFailure(new IntentRequiredException( + setResult(Resource.forFailure(new IntentRequiredException( WelcomeBackIdpPrompt.createIntent( getApplication(), getArguments(), diff --git a/auth/src/main/java/com/firebase/ui/auth/viewmodel/email/RecoverPasswordHandler.java b/auth/src/main/java/com/firebase/ui/auth/viewmodel/email/RecoverPasswordHandler.java index 6e004cabc..aca55034a 100644 --- a/auth/src/main/java/com/firebase/ui/auth/viewmodel/email/RecoverPasswordHandler.java +++ b/auth/src/main/java/com/firebase/ui/auth/viewmodel/email/RecoverPasswordHandler.java @@ -19,19 +19,16 @@ public RecoverPasswordHandler(Application application) { } public void startReset(@NonNull final String email, @Nullable ActionCodeSettings actionCodeSettings) { - setResult(Resource.forLoading()); + setResult(Resource.forLoading()); Task reset = actionCodeSettings != null ? getAuth().sendPasswordResetEmail(email, actionCodeSettings) : getAuth().sendPasswordResetEmail(email); - reset.addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - Resource resource = task.isSuccessful() - ? Resource.forSuccess(email) - : Resource.forFailure(task.getException()); - setResult(resource); - } - }); + reset.addOnCompleteListener(task -> { + Resource resource = task.isSuccessful() + ? Resource.forSuccess(email) + : Resource.forFailure(task.getException()); + setResult(resource); + }); } } diff --git a/auth/src/main/java/com/firebase/ui/auth/viewmodel/email/WelcomeBackPasswordHandler.java b/auth/src/main/java/com/firebase/ui/auth/viewmodel/email/WelcomeBackPasswordHandler.java index 0d26017f3..d68b93b39 100644 --- a/auth/src/main/java/com/firebase/ui/auth/viewmodel/email/WelcomeBackPasswordHandler.java +++ b/auth/src/main/java/com/firebase/ui/auth/viewmodel/email/WelcomeBackPasswordHandler.java @@ -46,7 +46,7 @@ public void startSignIn(@NonNull final String email, @NonNull final String password, @NonNull final IdpResponse inputResponse, @Nullable final AuthCredential credential) { - setResult(Resource.forLoading()); + setResult(Resource.forLoading()); // Store the password before signing in so it can be used for later credential building mPendingPassword = password; @@ -75,18 +75,8 @@ public void startSignIn(@NonNull final String email, if (AuthUI.SOCIAL_PROVIDERS.contains(inputResponse.getProviderType())) { // Add the provider to the same account before triggering a merge failure. authOperationManager.safeLink(credToValidate, credential, getArguments()) - .addOnSuccessListener(new OnSuccessListener() { - @Override - public void onSuccess(AuthResult result) { - handleMergeFailure(credToValidate); - } - }) - .addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - setResult(Resource.forFailure(e)); - } - }); + .addOnSuccessListener(result -> handleMergeFailure(credToValidate)) + .addOnFailureListener(e -> setResult(Resource.forFailure(e))); } else { // The user has not tried to log in with a federated IDP containing the same email. // In this case, we just need to verify that the credential they provided is valid. @@ -94,50 +84,34 @@ public void onFailure(@NonNull Exception e) { // A merge failure occurs because the account exists and the user is anonymous. authOperationManager.validateCredential(credToValidate, getArguments()) .addOnCompleteListener( - new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - if (task.isSuccessful()) { - handleMergeFailure(credToValidate); - } else { - setResult(Resource.forFailure(task.getException())); - } + task -> { + if (task.isSuccessful()) { + handleMergeFailure(credToValidate); + } else { + setResult(Resource.forFailure(task.getException())); } }); } } else { // Kick off the flow including signing in, linking accounts, and saving with SmartLock getAuth().signInWithEmailAndPassword(email, password) - .continueWithTask(new Continuation>() { - @Override - public Task then(@NonNull Task task) throws Exception { - // Forward task failure by asking for result - AuthResult result = task.getResult(Exception.class); + .continueWithTask(task -> { + // Forward task failure by asking for result + AuthResult result = task.getResult(Exception.class); - // Task succeeded, link user if necessary - if (credential == null) { - return Tasks.forResult(result); - } else { - return result.getUser() - .linkWithCredential(credential) - .continueWithTask(new ProfileMerger(outputResponse)) - .addOnFailureListener(new TaskFailureLogger(TAG, - "linkWithCredential+merge failed.")); - } - } - }) - .addOnSuccessListener(new OnSuccessListener() { - @Override - public void onSuccess(AuthResult result) { - handleSuccess(outputResponse, result); - } - }) - .addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - setResult(Resource.forFailure(e)); + // Task succeeded, link user if necessary + if (credential == null) { + return Tasks.forResult(result); + } else { + return result.getUser() + .linkWithCredential(credential) + .continueWithTask(new ProfileMerger(outputResponse)) + .addOnFailureListener(new TaskFailureLogger(TAG, + "linkWithCredential+merge failed.")); } }) + .addOnSuccessListener(result -> handleSuccess(outputResponse, result)) + .addOnFailureListener(e -> setResult(Resource.forFailure(e))) .addOnFailureListener( new TaskFailureLogger(TAG, "signInWithEmailAndPassword failed.")); } diff --git a/auth/src/main/java/com/firebase/ui/auth/viewmodel/idp/LinkingSocialProviderResponseHandler.java b/auth/src/main/java/com/firebase/ui/auth/viewmodel/idp/LinkingSocialProviderResponseHandler.java index da8046d8f..5e5b1def9 100644 --- a/auth/src/main/java/com/firebase/ui/auth/viewmodel/idp/LinkingSocialProviderResponseHandler.java +++ b/auth/src/main/java/com/firebase/ui/auth/viewmodel/idp/LinkingSocialProviderResponseHandler.java @@ -43,7 +43,7 @@ public void setRequestedSignInCredentialForEmail(@Nullable AuthCredential creden public void startSignIn(@NonNull final IdpResponse response) { if (!response.isSuccessful()) { - setResult(Resource.forFailure(response.getError())); + setResult(Resource.forFailure(response.getError())); return; } if (isInvalidProvider(response.getProviderType())) { @@ -51,12 +51,12 @@ public void startSignIn(@NonNull final IdpResponse response) { "This handler cannot be used to link email or phone providers."); } if (mEmail != null && !mEmail.equals(response.getEmail())) { - setResult(Resource.forFailure(new FirebaseUiException + setResult(Resource.forFailure(new FirebaseUiException (ErrorCodes.EMAIL_MISMATCH_ERROR))); return; } - setResult(Resource.forLoading()); + setResult(Resource.forLoading()); // The Generic IDP flow does not return a credential - it signs us in right away. // If the user was prompted to sign-in via Generic IDP, we can link immediately. @@ -66,18 +66,8 @@ public void startSignIn(@NonNull final IdpResponse response) { if (isGenericIdpLinkingFlow(response.getProviderType())) { getAuth().getCurrentUser() .linkWithCredential(mRequestedSignInCredential) - .addOnSuccessListener(new OnSuccessListener() { - @Override - public void onSuccess(AuthResult authResult) { - handleSuccess(response, authResult); - } - }) - .addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - Resource.forFailure(e); - } - }); + .addOnSuccessListener(authResult -> handleSuccess(response, authResult)) + .addOnFailureListener(e -> Resource.forFailure(e)); return; } @@ -99,53 +89,34 @@ public void onFailure(@NonNull Exception e) { // These IDPs belong to the same account - they must be linked, but we can't lose // our anonymous user session authOperationManager.safeLink(credential, mRequestedSignInCredential, getArguments()) - .addOnSuccessListener(new OnSuccessListener() { - @Override - public void onSuccess(AuthResult result) { - handleMergeFailure(credential); - } - }) - .addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - setResult(Resource.forFailure(e)); - } - }); + .addOnSuccessListener(result -> handleMergeFailure(credential)) + .addOnFailureListener(e -> setResult(Resource.forFailure(e))); } } else { getAuth().signInWithCredential(credential) - .continueWithTask(new Continuation>() { - @Override - public Task then(@NonNull Task task) { - final AuthResult result = task.getResult(); - if (mRequestedSignInCredential == null) { - return Tasks.forResult(result); - } else { - return result.getUser() - .linkWithCredential(mRequestedSignInCredential) - .continueWith(new Continuation() { - @Override - public AuthResult then(@NonNull Task task) { - if (task.isSuccessful()) { - return task.getResult(); - } else { - // Since we've already signed in, it's too late - // to backtrack so we just ignore any errors. - return result; - } - } - }); - } + .continueWithTask(task -> { + final AuthResult result = task.getResult(); + if (mRequestedSignInCredential == null) { + return Tasks.forResult(result); + } else { + return result.getUser() + .linkWithCredential(mRequestedSignInCredential) + .continueWith(task1 -> { + if (task1.isSuccessful()) { + return task1.getResult(); + } else { + // Since we've already signed in, it's too late + // to backtrack so we just ignore any errors. + return result; + } + }); } }) - .addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - if (task.isSuccessful()) { - handleSuccess(response, task.getResult()); - } else { - setResult(Resource.forFailure(task.getException())); - } + .addOnCompleteListener(task -> { + if (task.isSuccessful()) { + handleSuccess(response, task.getResult()); + } else { + setResult(Resource.forFailure(task.getException())); } }); } diff --git a/auth/src/main/java/com/firebase/ui/auth/viewmodel/idp/SocialProviderResponseHandler.java b/auth/src/main/java/com/firebase/ui/auth/viewmodel/idp/SocialProviderResponseHandler.java index f85591b72..da2ce914b 100644 --- a/auth/src/main/java/com/firebase/ui/auth/viewmodel/idp/SocialProviderResponseHandler.java +++ b/auth/src/main/java/com/firebase/ui/auth/viewmodel/idp/SocialProviderResponseHandler.java @@ -46,7 +46,7 @@ public SocialProviderResponseHandler(Application application) { public void startSignIn(@NonNull final IdpResponse response) { if (!response.isSuccessful() && !response.isRecoverableErrorResponse()) { - setResult(Resource.forFailure(response.getError())); + setResult(Resource.forFailure(response.getError())); return; } @@ -55,7 +55,7 @@ public void startSignIn(@NonNull final IdpResponse response) { "This handler cannot be used with email or phone providers"); } - setResult(Resource.forLoading()); + setResult(Resource.forLoading()); // Recoverable error flows (linking) for Generic OAuth providers are handled here. // For Generic OAuth providers, the credential is set on the IdpResponse, as @@ -71,73 +71,57 @@ public void startSignIn(@NonNull final IdpResponse response) { getArguments(), credential) .continueWithTask(new ProfileMerger(response)) - .addOnSuccessListener(new OnSuccessListener() { - @Override - public void onSuccess(AuthResult result) { - handleSuccess(response, result); - } - }) - .addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - // For some reason disabled users can hit FirebaseAuthUserCollisionException - // so we have to handle this special case. - boolean isDisabledUser = (e instanceof FirebaseAuthInvalidUserException); - if (e instanceof FirebaseAuthException) { - FirebaseAuthException authEx = (FirebaseAuthException) e; - FirebaseAuthError fae = FirebaseAuthError.fromException(authEx); - if (fae == FirebaseAuthError.ERROR_USER_DISABLED) { - isDisabledUser = true; - } + .addOnSuccessListener(result -> handleSuccess(response, result)) + .addOnFailureListener(e -> { + // For some reason disabled users can hit FirebaseAuthUserCollisionException + // so we have to handle this special case. + boolean isDisabledUser = (e instanceof FirebaseAuthInvalidUserException); + if (e instanceof FirebaseAuthException) { + FirebaseAuthException authEx = (FirebaseAuthException) e; + FirebaseAuthError fae = FirebaseAuthError.fromException(authEx); + if (fae == FirebaseAuthError.ERROR_USER_DISABLED) { + isDisabledUser = true; } + } - if (isDisabledUser) { - setResult(Resource.forFailure( - new FirebaseUiException(ErrorCodes.ERROR_USER_DISABLED) - )); - } else if (e instanceof FirebaseAuthUserCollisionException) { - final String email = response.getEmail(); - if (email == null) { - setResult(Resource.forFailure(e)); - return; - } - - // There can be a collision due to: - // CASE 1: Anon user signing in with a credential that belongs to an - // existing user. - // CASE 2: non - anon user signing in with a credential that does not - // belong to an existing user, but the email matches an existing user - // that has another social IDP. We need to link this new IDP to this - // existing user. - // CASE 3: CASE 2 with an anonymous user. We link the new IDP to the - // same account before handling invoking a merge failure. - ProviderUtils.fetchSortedProviders(getAuth(), getArguments(), email) - .addOnSuccessListener(new OnSuccessListener>() { - @Override - public void onSuccess(List providers) { - if (providers.contains(response.getProviderType())) { - // Case 1 - handleMergeFailure(credential); - } else if (providers.isEmpty()) { - setResult(Resource.forFailure( - new FirebaseUiException( - ErrorCodes.DEVELOPER_ERROR, - "No supported providers."))); - } else { - // Case 2 & 3 - we need to link - startWelcomeBackFlowForLinking( - providers.get(0), response); - } - } - }) - .addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - setResult(Resource.forFailure( - e)); - } - }); + if (isDisabledUser) { + setResult(Resource.forFailure( + new FirebaseUiException(ErrorCodes.ERROR_USER_DISABLED) + )); + } else if (e instanceof FirebaseAuthUserCollisionException) { + final String email = response.getEmail(); + if (email == null) { + setResult(Resource.forFailure(e)); + return; } + + // There can be a collision due to: + // CASE 1: Anon user signing in with a credential that belongs to an + // existing user. + // CASE 2: non - anon user signing in with a credential that does not + // belong to an existing user, but the email matches an existing user + // that has another social IDP. We need to link this new IDP to this + // existing user. + // CASE 3: CASE 2 with an anonymous user. We link the new IDP to the + // same account before handling invoking a merge failure. + ProviderUtils.fetchSortedProviders(getAuth(), getArguments(), email) + .addOnSuccessListener(providers -> { + if (providers.contains(response.getProviderType())) { + // Case 1 + handleMergeFailure(credential); + } else if (providers.isEmpty()) { + setResult(Resource.forFailure( + new FirebaseUiException( + ErrorCodes.DEVELOPER_ERROR, + "No supported providers."))); + } else { + // Case 2 & 3 - we need to link + startWelcomeBackFlowForLinking( + providers.get(0), response); + } + }) + .addOnFailureListener(e1 -> setResult(Resource.forFailure( + e1))); } }); } @@ -150,7 +134,7 @@ public void startWelcomeBackFlowForLinking(String provider, IdpResponse response if (provider.equals(EmailAuthProvider.PROVIDER_ID)) { // Start email welcome back flow - setResult(Resource.forFailure(new IntentRequiredException( + setResult(Resource.forFailure(new IntentRequiredException( WelcomeBackPasswordPrompt.createIntent( getApplication(), getArguments(), @@ -159,7 +143,7 @@ public void startWelcomeBackFlowForLinking(String provider, IdpResponse response ))); } else if (provider.equals(EMAIL_LINK_PROVIDER)) { // Start email link welcome back flow - setResult(Resource.forFailure(new IntentRequiredException( + setResult(Resource.forFailure(new IntentRequiredException( WelcomeBackEmailLinkPrompt.createIntent( getApplication(), getArguments(), @@ -168,7 +152,7 @@ public void startWelcomeBackFlowForLinking(String provider, IdpResponse response ))); } else { // Start Idp welcome back flow - setResult(Resource.forFailure(new IntentRequiredException( + setResult(Resource.forFailure(new IntentRequiredException( WelcomeBackIdpPrompt.createIntent( getApplication(), getArguments(), @@ -192,31 +176,23 @@ public void onActivityResult(int requestCode, int resultCode, @Nullable Intent d } else { e = response.getError(); } - setResult(Resource.forFailure(e)); + setResult(Resource.forFailure(e)); } } } private void handleGenericIdpLinkingFlow(@NonNull final IdpResponse idpResponse) { ProviderUtils.fetchSortedProviders(getAuth(), getArguments(), idpResponse.getEmail()) - .addOnSuccessListener(new OnSuccessListener>() { - @Override - public void onSuccess(@NonNull List providers) { - if (providers.isEmpty()) { - setResult(Resource.forFailure( - new FirebaseUiException(ErrorCodes.DEVELOPER_ERROR, - "No supported providers."))); - return; - } - startWelcomeBackFlowForLinking(providers.get(0), idpResponse); + .addOnSuccessListener(providers -> { + if (providers.isEmpty()) { + setResult(Resource.forFailure( + new FirebaseUiException(ErrorCodes.DEVELOPER_ERROR, + "No supported providers."))); + return; } + startWelcomeBackFlowForLinking(providers.get(0), idpResponse); }) - .addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - setResult(Resource.forFailure(e)); - } - }); + .addOnFailureListener(e -> setResult(Resource.forFailure(e))); } private boolean isEmailOrPhoneProvider(@NonNull String provider) { diff --git a/auth/src/main/java/com/firebase/ui/auth/viewmodel/phone/PhoneProviderResponseHandler.java b/auth/src/main/java/com/firebase/ui/auth/viewmodel/phone/PhoneProviderResponseHandler.java index 71e4b9735..fc94bf141 100644 --- a/auth/src/main/java/com/firebase/ui/auth/viewmodel/phone/PhoneProviderResponseHandler.java +++ b/auth/src/main/java/com/firebase/ui/auth/viewmodel/phone/PhoneProviderResponseHandler.java @@ -25,7 +25,7 @@ public PhoneProviderResponseHandler(Application application) { public void startSignIn(@NonNull PhoneAuthCredential credential, @NonNull final IdpResponse response) { if (!response.isSuccessful()) { - setResult(Resource.forFailure(response.getError())); + setResult(Resource.forFailure(response.getError())); return; } if (!response.getProviderType().equals(PhoneAuthProvider.PROVIDER_ID)) { @@ -33,27 +33,19 @@ public void startSignIn(@NonNull PhoneAuthCredential credential, "This handler cannot be used without a phone response."); } - setResult(Resource.forLoading()); + setResult(Resource.forLoading()); AuthOperationManager.getInstance() .signInAndLinkWithCredential(getAuth(), getArguments(), credential) - .addOnSuccessListener(new OnSuccessListener() { - @Override - public void onSuccess(AuthResult result) { - handleSuccess(response, result); - } - }) - .addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - if (e instanceof FirebaseAuthUserCollisionException) { - // With phone auth, this only happens if we are trying to upgrade - // an anonymous account using a phone number that is already registered - // on another account - handleMergeFailure(((FirebaseAuthUserCollisionException) e).getUpdatedCredential()); - } else { - setResult(Resource.forFailure(e)); - } + .addOnSuccessListener(result -> handleSuccess(response, result)) + .addOnFailureListener(e -> { + if (e instanceof FirebaseAuthUserCollisionException) { + // With phone auth, this only happens if we are trying to upgrade + // an anonymous account using a phone number that is already registered + // on another account + handleMergeFailure(((FirebaseAuthUserCollisionException) e).getUpdatedCredential()); + } else { + setResult(Resource.forFailure(e)); } }); } diff --git a/auth/src/main/java/com/firebase/ui/auth/viewmodel/smartlock/SmartLockHandler.java b/auth/src/main/java/com/firebase/ui/auth/viewmodel/smartlock/SmartLockHandler.java index 89f5183bf..f45aa547c 100644 --- a/auth/src/main/java/com/firebase/ui/auth/viewmodel/smartlock/SmartLockHandler.java +++ b/auth/src/main/java/com/firebase/ui/auth/viewmodel/smartlock/SmartLockHandler.java @@ -52,7 +52,7 @@ public void onActivityResult(int requestCode, int resultCode) { Log.e(TAG, "SAVE: Canceled by user."); FirebaseUiException exception = new FirebaseUiException( ErrorCodes.UNKNOWN_ERROR, "Save canceled by user."); - setResult(Resource.forFailure(exception)); + setResult(Resource.forFailure(exception)); } } } @@ -71,33 +71,30 @@ public void saveCredentials(@Nullable Credential credential) { setResult(Resource.forSuccess(mResponse)); return; } - setResult(Resource.forLoading()); + setResult(Resource.forLoading()); if (credential == null) { - setResult(Resource.forFailure(new FirebaseUiException( + setResult(Resource.forFailure(new FirebaseUiException( ErrorCodes.UNKNOWN_ERROR, "Failed to build credential."))); return; } deleteUnusedCredentials(); getCredentialsClient().save(credential) - .addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - if (task.isSuccessful()) { - setResult(Resource.forSuccess(mResponse)); - } else if (task.getException() instanceof ResolvableApiException) { - ResolvableApiException rae = (ResolvableApiException) task.getException(); - setResult(Resource.forFailure( - new PendingIntentRequiredException( - rae.getResolution(), RequestCodes.CRED_SAVE))); - } else { - Log.w(TAG, "Non-resolvable exception: " + task.getException()); - setResult(Resource.forFailure(new FirebaseUiException( - ErrorCodes.UNKNOWN_ERROR, - "Error when saving credential.", - task.getException()))); - } + .addOnCompleteListener(task -> { + if (task.isSuccessful()) { + setResult(Resource.forSuccess(mResponse)); + } else if (task.getException() instanceof ResolvableApiException) { + ResolvableApiException rae = (ResolvableApiException) task.getException(); + setResult(Resource.forFailure( + new PendingIntentRequiredException( + rae.getResolution(), RequestCodes.CRED_SAVE))); + } else { + Log.w(TAG, "Non-resolvable exception: " + task.getException()); + setResult(Resource.forFailure(new FirebaseUiException( + ErrorCodes.UNKNOWN_ERROR, + "Error when saving credential.", + task.getException()))); } }); } diff --git a/auth/src/test/java/com/firebase/ui/auth/testhelpers/ResourceMatchers.java b/auth/src/test/java/com/firebase/ui/auth/testhelpers/ResourceMatchers.java index 007e32fcc..d53cb18ff 100644 --- a/auth/src/test/java/com/firebase/ui/auth/testhelpers/ResourceMatchers.java +++ b/auth/src/test/java/com/firebase/ui/auth/testhelpers/ResourceMatchers.java @@ -24,44 +24,31 @@ public static ArgumentMatcher> isFailure() { } public static ArgumentMatcher> isFailureWithCode(final int code) { - return new ArgumentMatcher>() { - @Override - public boolean matches(Resource argument) { - if (argument.getState() != State.FAILURE) { - return false; - } - - if (argument.getException() == null) { - return false; - } + return argument -> { + if (argument.getState() != State.FAILURE) { + return false; + } - if (!(argument.getException() instanceof FirebaseUiException)) { - return false; - } + if (argument.getException() == null) { + return false; + } - FirebaseUiException fue = (FirebaseUiException) argument.getException(); - return fue.getErrorCode() == code; + if (!(argument.getException() instanceof FirebaseUiException)) { + return false; } + + FirebaseUiException fue = (FirebaseUiException) argument.getException(); + return fue.getErrorCode() == code; }; } public static ArgumentMatcher> isSuccessWith(final T result) { - return new ArgumentMatcher>() { - @Override - public boolean matches(Resource argument) { - return argument.getState() == State.SUCCESS - && argument.getValue().equals(result); - } - }; + return argument -> argument.getState() == State.SUCCESS + && argument.getValue().equals(result); } private static ArgumentMatcher> isState(final State state) { - return new ArgumentMatcher>() { - @Override - public boolean matches(Resource argument) { - return argument.getState() == state; - } - }; + return argument -> argument.getState() == state; } } diff --git a/auth/src/test/java/com/firebase/ui/auth/viewmodel/AnonymousSignInHandlerTest.java b/auth/src/test/java/com/firebase/ui/auth/viewmodel/AnonymousSignInHandlerTest.java index d693eae66..ff819e104 100644 --- a/auth/src/test/java/com/firebase/ui/auth/viewmodel/AnonymousSignInHandlerTest.java +++ b/auth/src/test/java/com/firebase/ui/auth/viewmodel/AnonymousSignInHandlerTest.java @@ -77,7 +77,7 @@ public void testStartSignIn_expectSuccess() { InOrder inOrder = inOrder(mResponseObserver); inOrder.verify(mResponseObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); ArgumentCaptor> captor = ArgumentCaptor.forClass(Resource.class); inOrder.verify(mResponseObserver).onChanged(captor.capture()); @@ -92,7 +92,7 @@ public void testStartSignIn_expectFailure() { mHandler.getOperation().observeForever(mResponseObserver); when(mMockAuth.signInAnonymously()) - .thenReturn(AutoCompleteTask.forFailure(new Exception("FAILED"))); + .thenReturn(AutoCompleteTask.forFailure(new Exception("FAILED"))); mHandler.startSignIn(mMockActivity); @@ -100,9 +100,9 @@ public void testStartSignIn_expectFailure() { InOrder inOrder = inOrder(mResponseObserver); inOrder.verify(mResponseObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); inOrder.verify(mResponseObserver) - .onChanged(argThat(ResourceMatchers.isFailure())); + .onChanged(argThat(ResourceMatchers.isFailure())); } } diff --git a/auth/src/test/java/com/firebase/ui/auth/viewmodel/EmailLinkSendEmailHandlerTest.java b/auth/src/test/java/com/firebase/ui/auth/viewmodel/EmailLinkSendEmailHandlerTest.java index b11f54710..17bc9421a 100644 --- a/auth/src/test/java/com/firebase/ui/auth/viewmodel/EmailLinkSendEmailHandlerTest.java +++ b/auth/src/test/java/com/firebase/ui/auth/viewmodel/EmailLinkSendEmailHandlerTest.java @@ -74,7 +74,7 @@ public void testSendSignInLinkToEmail_normalFlow_expectSuccess() { ActionCodeSettings actionCodeSettings = ActionCodeSettings.newBuilder().setUrl(URL).build(); when(mMockAuth.sendSignInLinkToEmail(any(String.class), any(ActionCodeSettings.class))) - .thenReturn(AutoCompleteTask.forSuccess(null)); + .thenReturn(AutoCompleteTask.forSuccess(null)); mHandler.sendSignInLinkToEmail(TestConstants.EMAIL, actionCodeSettings, null, forceSameDevice); @@ -95,7 +95,7 @@ public void testSendSignInLinkToEmail_normalFlow_expectSuccess() { ArgumentCaptor> captor = ArgumentCaptor.forClass(Resource.class); InOrder inOrder = inOrder(mResponseObserver); inOrder.verify(mResponseObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); inOrder.verify(mResponseObserver).onChanged(captor.capture()); @@ -111,7 +111,7 @@ public void testSendSignInLinkToEmail_normalFlow_expectFailure() { ActionCodeSettings actionCodeSettings = ActionCodeSettings.newBuilder().setUrl(URL).build(); when(mMockAuth.sendSignInLinkToEmail(any(String.class), any(ActionCodeSettings.class))) - .thenReturn(AutoCompleteTask.forFailure(new Exception())); + .thenReturn(AutoCompleteTask.forFailure(new Exception())); mHandler.sendSignInLinkToEmail(TestConstants.EMAIL, actionCodeSettings, null, forceSameDevice); @@ -127,7 +127,7 @@ public void testSendSignInLinkToEmail_normalFlow_expectFailure() { ArgumentCaptor> captor = ArgumentCaptor.forClass(Resource.class); InOrder inOrder = inOrder(mResponseObserver); inOrder.verify(mResponseObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); inOrder.verify(mResponseObserver).onChanged(captor.capture()); assertThat(captor.getValue().getState()).isEqualTo(State.FAILURE); @@ -141,7 +141,7 @@ public void testSendSignInLinkToEmail_linkingFlow_expectSuccess() { ActionCodeSettings actionCodeSettings = ActionCodeSettings.newBuilder().setUrl(URL).build(); when(mMockAuth.sendSignInLinkToEmail(any(String.class), any(ActionCodeSettings.class))) - .thenReturn(AutoCompleteTask.forFailure(new Exception())); + .thenReturn(AutoCompleteTask.forFailure(new Exception())); IdpResponse idpResponseForLinking = buildFacebookIdpResponseForLinking(); mHandler.sendSignInLinkToEmail(TestConstants.EMAIL, actionCodeSettings, @@ -158,7 +158,7 @@ public void testSendSignInLinkToEmail_linkingFlow_expectSuccess() { ArgumentCaptor> captor = ArgumentCaptor.forClass(Resource.class); InOrder inOrder = inOrder(mResponseObserver); inOrder.verify(mResponseObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); inOrder.verify(mResponseObserver).onChanged(captor.capture()); assertThat(captor.getValue().getState()).isEqualTo(State.FAILURE); diff --git a/auth/src/test/java/com/firebase/ui/auth/viewmodel/GenericIdpAnonymousUpgradeLinkingHandlerTest.java b/auth/src/test/java/com/firebase/ui/auth/viewmodel/GenericIdpAnonymousUpgradeLinkingHandlerTest.java index cf350a831..8243b8516 100644 --- a/auth/src/test/java/com/firebase/ui/auth/viewmodel/GenericIdpAnonymousUpgradeLinkingHandlerTest.java +++ b/auth/src/test/java/com/firebase/ui/auth/viewmodel/GenericIdpAnonymousUpgradeLinkingHandlerTest.java @@ -137,7 +137,7 @@ public void testStartSignIn_anonymousUpgradeLinkingFlow_expectIdpResponseWithCre InOrder inOrder = inOrder(mResponseObserver); inOrder.verify(mResponseObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); ArgumentCaptor> resolveCaptor = ArgumentCaptor.forClass(Resource.class); diff --git a/auth/src/test/java/com/firebase/ui/auth/viewmodel/GenericIdpSignInHandlerTest.java b/auth/src/test/java/com/firebase/ui/auth/viewmodel/GenericIdpSignInHandlerTest.java index 43c88eb95..8096a12c6 100644 --- a/auth/src/test/java/com/firebase/ui/auth/viewmodel/GenericIdpSignInHandlerTest.java +++ b/auth/src/test/java/com/firebase/ui/auth/viewmodel/GenericIdpSignInHandlerTest.java @@ -131,7 +131,7 @@ public void testStartSignIn_normalSignInFlow_expectSuccess() { InOrder inOrder = inOrder(mResponseObserver); inOrder.verify(mResponseObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); ArgumentCaptor> resourceCaptor = ArgumentCaptor.forClass(Resource.class); @@ -155,7 +155,7 @@ public void testStartSignIn_normalSignInFlowWithRecoverableError_expectFailure() collisionException.zzb(EMAIL).zza(credential); when(mMockAuth.startActivityForSignInWithProvider(any(Activity.class), any(OAuthProvider.class))) - .thenReturn(AutoCompleteTask.forFailure(collisionException)); + .thenReturn(AutoCompleteTask.forFailure(collisionException)); mockOAuthProvider(MICROSOFT_PROVIDER); mHandler.startSignIn(mMockAuth, mMockActivity, MICROSOFT_PROVIDER); @@ -167,7 +167,7 @@ public void testStartSignIn_normalSignInFlowWithRecoverableError_expectFailure() InOrder inOrder = inOrder(mResponseObserver); inOrder.verify(mResponseObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); ArgumentCaptor> resourceCaptor = ArgumentCaptor.forClass(Resource.class); @@ -187,7 +187,7 @@ public void testStartSignIn_normalSignInFlowWithError_expectFailure() { = new FirebaseAuthException("foo", "bar"); when(mMockAuth.startActivityForSignInWithProvider(any(Activity.class), any(OAuthProvider.class))) - .thenReturn(AutoCompleteTask.forFailure(firebaseAuthException)); + .thenReturn(AutoCompleteTask.forFailure(firebaseAuthException)); mockOAuthProvider(MICROSOFT_PROVIDER); mHandler.startSignIn(mMockAuth, mMockActivity, MICROSOFT_PROVIDER); @@ -201,7 +201,7 @@ public void testStartSignIn_normalSignInFlowWithError_expectFailure() { InOrder inOrder = inOrder(mResponseObserver); inOrder.verify(mResponseObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); ArgumentCaptor> resourceCaptor = ArgumentCaptor.forClass(Resource.class); @@ -232,7 +232,7 @@ public void testStartSignIn_anonymousUpgradeFlow_expectSuccess() { InOrder inOrder = inOrder(mResponseObserver); inOrder.verify(mResponseObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); ArgumentCaptor> resourceCaptor = ArgumentCaptor.forClass(Resource.class); @@ -259,11 +259,11 @@ public void testStartSignIn_anonymousUpgradeFlowWithConflict_expectRecoverableEr collisionException.zzb(EMAIL).zza(credential); when(mMockAuth.getCurrentUser().startActivityForLinkWithProvider( any(Activity.class), any(OAuthProvider.class))) - .thenReturn(AutoCompleteTask.forFailure(collisionException)); + .thenReturn(AutoCompleteTask.forFailure(collisionException)); // Case 1: Anon user signing in with an existing account when(mMockAuth.fetchSignInMethodsForEmail(any(String.class))) - .thenReturn(AutoCompleteTask.forSuccess( + .thenReturn(AutoCompleteTask.forSuccess( new FakeSignInMethodQueryResult(Arrays.asList( MICROSOFT_PROVIDER)))); @@ -278,7 +278,7 @@ public void testStartSignIn_anonymousUpgradeFlowWithConflict_expectRecoverableEr InOrder inOrder = inOrder(mResponseObserver); inOrder.verify(mResponseObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); ArgumentCaptor> resolveCaptor = ArgumentCaptor.forClass(Resource.class); @@ -304,12 +304,12 @@ public void testStartSignIn_anonymousUpgradeFlowWithConflict_expectRecoverableLi when(mMockAuth.getCurrentUser().startActivityForLinkWithProvider( any(Activity.class), any(OAuthProvider.class))) - .thenReturn(AutoCompleteTask.forFailure(collisionException)); + .thenReturn(AutoCompleteTask.forFailure(collisionException)); // Case 2: Anonymous user trying to link with a provider keyed by an email that already // belongs to an existing account when(mMockAuth.fetchSignInMethodsForEmail(any(String.class))) - .thenReturn(AutoCompleteTask.forSuccess( + .thenReturn(AutoCompleteTask.forSuccess( new FakeSignInMethodQueryResult(Arrays.asList( GoogleAuthProvider.PROVIDER_ID)))); @@ -324,7 +324,7 @@ public void testStartSignIn_anonymousUpgradeFlowWithConflict_expectRecoverableLi InOrder inOrder = inOrder(mResponseObserver); inOrder.verify(mResponseObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); ArgumentCaptor> resolveCaptor = ArgumentCaptor.forClass(Resource.class); diff --git a/auth/src/test/java/com/firebase/ui/auth/viewmodel/LinkingSocialProviderResponseHandlerTest.java b/auth/src/test/java/com/firebase/ui/auth/viewmodel/LinkingSocialProviderResponseHandlerTest.java index 87c0301b8..1e00707b5 100644 --- a/auth/src/test/java/com/firebase/ui/auth/viewmodel/LinkingSocialProviderResponseHandlerTest.java +++ b/auth/src/test/java/com/firebase/ui/auth/viewmodel/LinkingSocialProviderResponseHandlerTest.java @@ -99,9 +99,9 @@ public void testSignIn_withSameIdp_expectSuccess() { InOrder inOrder = inOrder(mResponseObserver); inOrder.verify(mResponseObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); inOrder.verify(mResponseObserver) - .onChanged(argThat(ResourceMatchers.isSuccess())); + .onChanged(argThat(ResourceMatchers.isSuccess())); } @@ -125,7 +125,7 @@ public void testSignIn_anonymousUpgradeEnabledWithSameIdp_expectMergeFailure() { InOrder inOrder = inOrder(mResponseObserver); inOrder.verify(mResponseObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); ArgumentCaptor> resolveCaptor = ArgumentCaptor.forClass(Resource.class); @@ -179,9 +179,9 @@ public void testSignIn_withDifferentIdp_expectSuccess() { InOrder inOrder = inOrder(mResponseObserver); inOrder.verify(mResponseObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); inOrder.verify(mResponseObserver) - .onChanged(argThat(ResourceMatchers.isSuccess())); + .onChanged(argThat(ResourceMatchers.isSuccess())); } @Test @@ -223,7 +223,7 @@ public void testSignIn_anonymousUpgradeEnabledWithDifferentIdp_expectMergeFailur InOrder inOrder = inOrder(mResponseObserver); inOrder.verify(mResponseObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); ArgumentCaptor> resolveCaptor = ArgumentCaptor.forClass(Resource.class); @@ -265,7 +265,7 @@ public void testSignIn_genericIdpLinkingFlow_expectImmediateLink() { InOrder inOrder = inOrder(mResponseObserver); inOrder.verify(mResponseObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); ArgumentCaptor> resolveCaptor = ArgumentCaptor.forClass(Resource.class); diff --git a/auth/src/test/java/com/firebase/ui/auth/viewmodel/PhoneProviderResponseHandlerTest.java b/auth/src/test/java/com/firebase/ui/auth/viewmodel/PhoneProviderResponseHandlerTest.java index a54232fb3..e49954172 100644 --- a/auth/src/test/java/com/firebase/ui/auth/viewmodel/PhoneProviderResponseHandlerTest.java +++ b/auth/src/test/java/com/firebase/ui/auth/viewmodel/PhoneProviderResponseHandlerTest.java @@ -80,7 +80,7 @@ public void testSignIn_withValidCredentialAndNewUser_expectSuccess() { mHandler.startSignIn(mCredential, response); verify(mMockAuth).signInWithCredential(mCredential); - verify(mResponseObserver).onChanged(argThat(ResourceMatchers.isSuccess())); + verify(mResponseObserver).onChanged(argThat(ResourceMatchers.isSuccess())); } @Test @@ -98,7 +98,7 @@ public void testSignIn_autoUpgradeAnonymousEnabledWithNewUser_expectSuccess() { mHandler.startSignIn(mCredential, response); verify(mMockAuth.getCurrentUser()).linkWithCredential(mCredential); - verify(mResponseObserver).onChanged(argThat(ResourceMatchers.isSuccess())); + verify(mResponseObserver).onChanged(argThat(ResourceMatchers.isSuccess())); } @@ -113,7 +113,7 @@ public void testSignIn_autoUpgradeAnonymousEnabledWithExistingUser_expectMergeFa AuthCredential.class, mCredential); when(mMockAuth.getCurrentUser().linkWithCredential(mCredential)) - .thenReturn(AutoCompleteTask.forFailure(ex)); + .thenReturn(AutoCompleteTask.forFailure(ex)); IdpResponse response = new IdpResponse.Builder(new User.Builder( PhoneAuthProvider.PROVIDER_ID, TestConstants.EMAIL).build()) @@ -125,7 +125,7 @@ public void testSignIn_autoUpgradeAnonymousEnabledWithExistingUser_expectMergeFa InOrder inOrder = inOrder(mResponseObserver); inOrder.verify(mResponseObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); ArgumentCaptor> resolveCaptor = ArgumentCaptor.forClass(Resource.class); diff --git a/auth/src/test/java/com/firebase/ui/auth/viewmodel/RecoverPasswordHandlerTest.java b/auth/src/test/java/com/firebase/ui/auth/viewmodel/RecoverPasswordHandlerTest.java index cd1d699ff..335e21fbf 100644 --- a/auth/src/test/java/com/firebase/ui/auth/viewmodel/RecoverPasswordHandlerTest.java +++ b/auth/src/test/java/com/firebase/ui/auth/viewmodel/RecoverPasswordHandlerTest.java @@ -64,79 +64,79 @@ public void setUp() { public void testReset_sendsRecoverEmail() { // Send password email succeeds when(mMockAuth.sendPasswordResetEmail(TestConstants.EMAIL)) - .thenReturn(AutoCompleteTask.forSuccess(null)); + .thenReturn(AutoCompleteTask.forSuccess(null)); // Begin observation, then send the email mHandler.getOperation().observeForever(mObserver); mHandler.startReset(TestConstants.EMAIL, null); // Should get in-progress resource - verify(mObserver).onChanged(argThat(ResourceMatchers.isLoading())); + verify(mObserver).onChanged(argThat(ResourceMatchers.isLoading())); // Firebase auth should be called verify(mMockAuth).sendPasswordResetEmail(TestConstants.EMAIL); // Should get the success resource - verify(mObserver).onChanged(argThat(ResourceMatchers.isSuccess())); + verify(mObserver).onChanged(argThat(ResourceMatchers.isSuccess())); } @Test public void testReset_propagatesFailure() { // Send password email fails when(mMockAuth.sendPasswordResetEmail(TestConstants.EMAIL)) - .thenReturn(AutoCompleteTask.forFailure(new Exception("FAILED"))); + .thenReturn(AutoCompleteTask.forFailure(new Exception("FAILED"))); // Begin observation, then send the email mHandler.getOperation().observeForever(mObserver); mHandler.startReset(TestConstants.EMAIL, null); // Should get in-progress resource - verify(mObserver).onChanged(argThat(ResourceMatchers.isLoading())); + verify(mObserver).onChanged(argThat(ResourceMatchers.isLoading())); // Firebase auth should be called verify(mMockAuth).sendPasswordResetEmail(TestConstants.EMAIL); // Should get the success resource - verify(mObserver).onChanged(argThat(ResourceMatchers.isFailure())); + verify(mObserver).onChanged(argThat(ResourceMatchers.isFailure())); } @Test public void testReset_sendsCustomRecoverEmail() { // Send password email succeeds when(mMockAuth.sendPasswordResetEmail(TestConstants.EMAIL, mPasswordResetSettings )) - .thenReturn(AutoCompleteTask.forSuccess(null)); + .thenReturn(AutoCompleteTask.forSuccess(null)); // Begin observation, then send the email mHandler.getOperation().observeForever(mObserver); mHandler.startReset(TestConstants.EMAIL, mPasswordResetSettings); // Should get in-progress resource - verify(mObserver).onChanged(argThat(ResourceMatchers.isLoading())); + verify(mObserver).onChanged(argThat(ResourceMatchers.isLoading())); // Firebase auth should be called verify(mMockAuth).sendPasswordResetEmail(TestConstants.EMAIL, mPasswordResetSettings); // Should get the success resource - verify(mObserver).onChanged(argThat(ResourceMatchers.isSuccess())); + verify(mObserver).onChanged(argThat(ResourceMatchers.isSuccess())); } @Test public void testCustomReset_propagatesFailure() { // Send password email fails when(mMockAuth.sendPasswordResetEmail(TestConstants.EMAIL, mPasswordResetSettings)) - .thenReturn(AutoCompleteTask.forFailure(new Exception("FAILED"))); + .thenReturn(AutoCompleteTask.forFailure(new Exception("FAILED"))); // Begin observation, then send the email mHandler.getOperation().observeForever(mObserver); mHandler.startReset(TestConstants.EMAIL, mPasswordResetSettings); // Should get in-progress resource - verify(mObserver).onChanged(argThat(ResourceMatchers.isLoading())); + verify(mObserver).onChanged(argThat(ResourceMatchers.isLoading())); // Firebase auth should be called verify(mMockAuth).sendPasswordResetEmail(TestConstants.EMAIL, mPasswordResetSettings); // Should get the success resource - verify(mObserver).onChanged(argThat(ResourceMatchers.isFailure())); + verify(mObserver).onChanged(argThat(ResourceMatchers.isFailure())); } } diff --git a/auth/src/test/java/com/firebase/ui/auth/viewmodel/SmartLockHandlerTest.java b/auth/src/test/java/com/firebase/ui/auth/viewmodel/SmartLockHandlerTest.java index dd6812e3e..908b7b2a8 100644 --- a/auth/src/test/java/com/firebase/ui/auth/viewmodel/SmartLockHandlerTest.java +++ b/auth/src/test/java/com/firebase/ui/auth/viewmodel/SmartLockHandlerTest.java @@ -73,12 +73,12 @@ public void testSaveCredentials_success() { mHandler.getOperation().observeForever(mResultObserver); when(mMockCredentials.save(any(Credential.class))) - .thenReturn(AutoCompleteTask.forSuccess(null)); + .thenReturn(AutoCompleteTask.forSuccess(null)); mHandler.saveCredentials(TestHelper.getMockFirebaseUser(), TestConstants.PASSWORD, null); - verify(mResultObserver).onChanged(argThat(ResourceMatchers.isLoading())); - verify(mResultObserver).onChanged(argThat(ResourceMatchers.isSuccess())); + verify(mResultObserver).onChanged(argThat(ResourceMatchers.isLoading())); + verify(mResultObserver).onChanged(argThat(ResourceMatchers.isSuccess())); } @Test @@ -88,7 +88,7 @@ public void testSaveCredentials_resolution() { // Mock credentials to throw an RAE ResolvableApiException mockRae = mock(ResolvableApiException.class); when(mMockCredentials.save(any(Credential.class))) - .thenReturn(AutoCompleteTask.forFailure(mockRae)); + .thenReturn(AutoCompleteTask.forFailure(mockRae)); // Kick off save mHandler.saveCredentials(TestHelper.getMockFirebaseUser(), TestConstants.PASSWORD, null); @@ -96,7 +96,7 @@ public void testSaveCredentials_resolution() { InOrder inOrder = inOrder(mResultObserver); inOrder.verify(mResultObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); // Make sure we get a resolution ArgumentCaptor> resolveCaptor = @@ -110,7 +110,7 @@ public void testSaveCredentials_resolution() { // Make sure we get success inOrder.verify(mResultObserver) - .onChanged(argThat(ResourceMatchers.isSuccess())); + .onChanged(argThat(ResourceMatchers.isSuccess())); } @Test @@ -118,12 +118,12 @@ public void testSaveCredentials_failure() { mHandler.getOperation().observeForever(mResultObserver); when(mMockCredentials.save(any(Credential.class))) - .thenReturn(AutoCompleteTask.forFailure(new Exception("FAILED"))); + .thenReturn(AutoCompleteTask.forFailure(new Exception("FAILED"))); mHandler.saveCredentials(TestHelper.getMockFirebaseUser(), TestConstants.PASSWORD, null); - verify(mResultObserver).onChanged(argThat(ResourceMatchers.isLoading())); - verify(mResultObserver).onChanged(argThat(ResourceMatchers.isFailure())); + verify(mResultObserver).onChanged(argThat(ResourceMatchers.isLoading())); + verify(mResultObserver).onChanged(argThat(ResourceMatchers.isFailure())); } } diff --git a/auth/src/test/java/com/firebase/ui/auth/viewmodel/SocialProviderResponseHandlerTest.java b/auth/src/test/java/com/firebase/ui/auth/viewmodel/SocialProviderResponseHandlerTest.java index 60a418c98..a1f110887 100644 --- a/auth/src/test/java/com/firebase/ui/auth/viewmodel/SocialProviderResponseHandlerTest.java +++ b/auth/src/test/java/com/firebase/ui/auth/viewmodel/SocialProviderResponseHandlerTest.java @@ -94,9 +94,9 @@ public void testSignInIdp_success() { InOrder inOrder = inOrder(mResultObserver); inOrder.verify(mResultObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); inOrder.verify(mResultObserver) - .onChanged(argThat(ResourceMatchers.isSuccess())); + .onChanged(argThat(ResourceMatchers.isSuccess())); } @Test(expected = IllegalStateException.class) @@ -118,7 +118,7 @@ public void testSignInResponse_failure() { mHandler.startSignIn(response); - verify(mResultObserver).onChanged(argThat(ResourceMatchers.isFailure())); + verify(mResultObserver).onChanged(argThat(ResourceMatchers.isFailure())); } @Test @@ -126,7 +126,7 @@ public void testSignInIdp_disabled() { mHandler.getOperation().observeForever(mResultObserver); when(mMockAuth.signInWithCredential(any(AuthCredential.class))) - .thenReturn(AutoCompleteTask.forFailure( + .thenReturn(AutoCompleteTask.forFailure( new FirebaseAuthException("ERROR_USER_DISABLED", "disabled"))); IdpResponse response = new IdpResponse.Builder(new User.Builder( @@ -136,7 +136,7 @@ public void testSignInIdp_disabled() { mHandler.startSignIn(response); verify(mResultObserver).onChanged( - argThat(ResourceMatchers.isFailureWithCode(ErrorCodes.ERROR_USER_DISABLED))); + argThat(ResourceMatchers.isFailureWithCode(ErrorCodes.ERROR_USER_DISABLED))); } @Test @@ -144,10 +144,10 @@ public void testSignInIdp_resolution() { mHandler.getOperation().observeForever(mResultObserver); when(mMockAuth.signInWithCredential(any(AuthCredential.class))) - .thenReturn(AutoCompleteTask.forFailure( + .thenReturn(AutoCompleteTask.forFailure( new FirebaseAuthUserCollisionException("foo", "bar"))); when(mMockAuth.fetchSignInMethodsForEmail(any(String.class))) - .thenReturn(AutoCompleteTask.forSuccess( + .thenReturn(AutoCompleteTask.forSuccess( new FakeSignInMethodQueryResult(Collections.singletonList( FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD)))); @@ -163,7 +163,7 @@ public void testSignInIdp_resolution() { InOrder inOrder = inOrder(mResultObserver); inOrder.verify(mResultObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); ArgumentCaptor> resolveCaptor = ArgumentCaptor.forClass(Resource.class); @@ -176,7 +176,7 @@ public void testSignInIdp_resolution() { // Make sure we get success inOrder.verify(mResultObserver) - .onChanged(argThat(ResourceMatchers.isSuccess())); + .onChanged(argThat(ResourceMatchers.isSuccess())); } @@ -199,9 +199,9 @@ public void testSignInIdp_anonymousUserUpgradeEnabledAndNewUser_expectSuccess() InOrder inOrder = inOrder(mResultObserver); inOrder.verify(mResultObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); inOrder.verify(mResultObserver) - .onChanged(argThat(ResourceMatchers.isSuccess())); + .onChanged(argThat(ResourceMatchers.isSuccess())); } @Test @@ -210,12 +210,12 @@ public void testSignInIdp_anonymousUserUpgradeEnabledAndExistingUserWithSameIdp_ setupAnonymousUpgrade(); when(mMockAuth.getCurrentUser().linkWithCredential(any(AuthCredential.class))) - .thenReturn(AutoCompleteTask.forFailure( + .thenReturn(AutoCompleteTask.forFailure( new FirebaseAuthUserCollisionException("foo", "bar"))); // Case 1: Anon user signing in with a Google credential that belongs to an existing user. when(mMockAuth.fetchSignInMethodsForEmail(any(String.class))) - .thenReturn(AutoCompleteTask.forSuccess( + .thenReturn(AutoCompleteTask.forSuccess( new FakeSignInMethodQueryResult(Arrays.asList( GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD, FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD)))); @@ -232,7 +232,7 @@ public void testSignInIdp_anonymousUserUpgradeEnabledAndExistingUserWithSameIdp_ InOrder inOrder = inOrder(mResultObserver); inOrder.verify(mResultObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); ArgumentCaptor> resolveCaptor = ArgumentCaptor.forClass(Resource.class); @@ -250,13 +250,13 @@ public void testSignInIdp_anonymousUserUpgradeEnabledAndExistingIdpUserWithDiffe setupAnonymousUpgrade(); when(mMockAuth.getCurrentUser().linkWithCredential(any(AuthCredential.class))) - .thenReturn(AutoCompleteTask.forFailure( + .thenReturn(AutoCompleteTask.forFailure( new FirebaseAuthUserCollisionException("foo", "bar"))); // Case 2 & 3: trying to link with an account that has 1 idp, which is different from the // one that we're trying to log in with when(mMockAuth.fetchSignInMethodsForEmail(any(String.class))) - .thenReturn(AutoCompleteTask.forSuccess( + .thenReturn(AutoCompleteTask.forSuccess( new FakeSignInMethodQueryResult(Collections.singletonList( FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD)))); @@ -271,7 +271,7 @@ public void testSignInIdp_anonymousUserUpgradeEnabledAndExistingIdpUserWithDiffe InOrder inOrder = inOrder(mResultObserver); inOrder.verify(mResultObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); ArgumentCaptor> resolveCaptor = ArgumentCaptor.forClass(Resource.class); @@ -293,13 +293,13 @@ public void testSignInIdp_anonymousUserUpgradeEnabledAndExistingPasswordUserWith setupAnonymousUpgrade(); when(mMockAuth.getCurrentUser().linkWithCredential(any(AuthCredential.class))) - .thenReturn(AutoCompleteTask.forFailure( + .thenReturn(AutoCompleteTask.forFailure( new FirebaseAuthUserCollisionException("foo", "bar"))); // Case 2 & 3: trying to link with an account that has 1 password provider and logging in // with an idp that has the same email when(mMockAuth.fetchSignInMethodsForEmail(any(String.class))) - .thenReturn(AutoCompleteTask.forSuccess( + .thenReturn(AutoCompleteTask.forSuccess( new FakeSignInMethodQueryResult(Collections.singletonList( EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD)))); @@ -315,7 +315,7 @@ public void testSignInIdp_anonymousUserUpgradeEnabledAndExistingPasswordUserWith InOrder inOrder = inOrder(mResultObserver); inOrder.verify(mResultObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); ArgumentCaptor> resolveCaptor = ArgumentCaptor.forClass(Resource.class); diff --git a/auth/src/test/java/com/firebase/ui/auth/viewmodel/WelcomeBackPasswordHandlerTest.java b/auth/src/test/java/com/firebase/ui/auth/viewmodel/WelcomeBackPasswordHandlerTest.java index 694004f9e..074bb06c3 100644 --- a/auth/src/test/java/com/firebase/ui/auth/viewmodel/WelcomeBackPasswordHandlerTest.java +++ b/auth/src/test/java/com/firebase/ui/auth/viewmodel/WelcomeBackPasswordHandlerTest.java @@ -99,13 +99,13 @@ public void testSignIn_linksIdpCredential() { // Mock smartlock save to always succeed when(mMockCredentials.save(any(Credential.class))) - .thenReturn(AutoCompleteTask.forSuccess(null)); + .thenReturn(AutoCompleteTask.forSuccess(null)); // Kick off the sign in flow mHandler.startSignIn(TestConstants.EMAIL, TestConstants.PASSWORD, response, credential); // Verify that we get a loading event - verify(mResponseObserver).onChanged(argThat(ResourceMatchers.isLoading())); + verify(mResponseObserver).onChanged(argThat(ResourceMatchers.isLoading())); // Verify that sign in is called with the right arguments verify(mMockAuth).signInWithEmailAndPassword( @@ -115,7 +115,7 @@ public void testSignIn_linksIdpCredential() { verify(FakeAuthResult.INSTANCE.getUser()).linkWithCredential(credential); // Verify that we get a success event - verify(mResponseObserver).onChanged(argThat(ResourceMatchers.isSuccess())); + verify(mResponseObserver).onChanged(argThat(ResourceMatchers.isSuccess())); } @Test @@ -124,20 +124,20 @@ public void testSignIn_propagatesFailure() { // Mock sign in to always fail when(mMockAuth.signInWithEmailAndPassword(any(String.class), any(String.class))) - .thenReturn(AutoContinueTask.forFailure(new Exception("FAILED"))); + .thenReturn(AutoContinueTask.forFailure(new Exception("FAILED"))); // Kick off the sign in flow mHandler.startSignIn(TestConstants.EMAIL, TestConstants.PASSWORD, null, null); // Verify that we get a loading event - verify(mResponseObserver).onChanged(argThat(ResourceMatchers.isLoading())); + verify(mResponseObserver).onChanged(argThat(ResourceMatchers.isLoading())); // Verify that sign in is called with the right arguments verify(mMockAuth).signInWithEmailAndPassword( TestConstants.EMAIL, TestConstants.PASSWORD); // Verify that we get a failure event - verify(mResponseObserver).onChanged(argThat(ResourceMatchers.isFailure())); + verify(mResponseObserver).onChanged(argThat(ResourceMatchers.isFailure())); } @Test @@ -241,7 +241,7 @@ private void verifyMergeFailure() { InOrder inOrder = inOrder(mResponseObserver); inOrder.verify(mResponseObserver) - .onChanged(argThat(ResourceMatchers.isLoading())); + .onChanged(argThat(ResourceMatchers.isLoading())); ArgumentCaptor> resolveCaptor = ArgumentCaptor.forClass(Resource.class); diff --git a/database/src/androidTest/java/com/firebase/ui/database/FirebaseArrayOfObjectsTest.java b/database/src/androidTest/java/com/firebase/ui/database/FirebaseArrayOfObjectsTest.java index 15e43ca97..6e63ea974 100644 --- a/database/src/androidTest/java/com/firebase/ui/database/FirebaseArrayOfObjectsTest.java +++ b/database/src/androidTest/java/com/firebase/ui/database/FirebaseArrayOfObjectsTest.java @@ -48,19 +48,11 @@ public void setUp() throws Exception { .child("objects"); mArray = new FirebaseArray<>(mRef, new ClassSnapshotParser<>(Bean.class)); mRef.removeValue(); - mListener = runAndWaitUntil(mArray, new Runnable() { - @Override - public void run() { - for (int i = 1; i <= INITIAL_SIZE; i++) { - mRef.push().setValue(new Bean(i, "Text " + i, i % 2 == 0), i); - } + mListener = runAndWaitUntil(mArray, () -> { + for (int i = 1; i <= INITIAL_SIZE; i++) { + mRef.push().setValue(new Bean(i, "Text " + i, i % 2 == 0), i); } - }, new Callable() { - @Override - public Boolean call() { - return mArray.size() == INITIAL_SIZE; - } - }); + }, () -> mArray.size() == INITIAL_SIZE); } @After @@ -71,64 +63,30 @@ public void tearDown() { @Test public void testPushIncreasesSize() throws Exception { - runAndWaitUntil(mArray, new Runnable() { - @Override - public void run() { - mRef.push().setValue(new Bean(4)); - } - }, new Callable() { - @Override - public Boolean call() { - return mArray.size() == 4; - } - }); + runAndWaitUntil(mArray, () -> mRef.push().setValue(new Bean(4)), () -> mArray.size() == 4); } @Test public void testPushAppends() throws Exception { - runAndWaitUntil(mArray, new Runnable() { - @Override - public void run() { - mRef.push().setValue(new Bean(4), 4); - } - }, new Callable() { - @Override - public Boolean call() { - return mArray.get(3).getNumber() == 4; - } - }); + runAndWaitUntil(mArray, + () -> mRef.push().setValue(new Bean(4), 4), + () -> mArray.get(3).getNumber() == 4); } @Test public void testAddValueWithPriority() throws Exception { - runAndWaitUntil(mArray, new Runnable() { - @Override - public void run() { - mRef.push().setValue(new Bean(4), 0.5); - } - }, new Callable() { - @Override - public Boolean call() { - return mArray.get(3).getNumber() == 3 && mArray.get(0).getNumber() == 4; - } - }); + runAndWaitUntil(mArray, + () -> mRef.push().setValue(new Bean(4), 0.5), + () -> mArray.get(3).getNumber() == 3 && mArray.get(0).getNumber() == 4); } @Test public void testChangePriorities() throws Exception { - runAndWaitUntil(mArray, new Runnable() { - @Override - public void run() { - mArray.getSnapshot(2).getRef().setPriority(0.5); - } - }, new Callable() { - @Override - public Boolean call() { - return mArray.get(0).getNumber() == 3 - && mArray.get(1).getNumber() == 1 - && mArray.get(2).getNumber() == 2; - //return isValuesEqual(mArray, new int[]{3, 1, 2}); - } + runAndWaitUntil(mArray, () -> mArray.getSnapshot(2).getRef().setPriority(0.5), () -> { + return mArray.get(0).getNumber() == 3 + && mArray.get(1).getNumber() == 1 + && mArray.get(2).getNumber() == 2; + //return isValuesEqual(mArray, new int[]{3, 1, 2}); }); } @@ -137,29 +95,13 @@ public void testCacheInvalidates() throws Exception { final DatabaseReference pushRef = mRef.push(); // Set initial value to "5" - runAndWaitUntil(mArray, new Runnable() { - @Override - public void run() { - pushRef.setValue(new Bean(5), 100); - } - }, new Callable() { - @Override - public Boolean call() { - return mArray.get(3).getNumber() == 5; - } - }); + runAndWaitUntil(mArray, + () -> pushRef.setValue(new Bean(5), 100), + () -> mArray.get(3).getNumber() == 5); // Change the value to "6" and ensure that the change is propagated - runAndWaitUntil(mArray, new Runnable() { - @Override - public void run() { - pushRef.setValue(new Bean(6), 100); - } - }, new Callable() { - @Override - public Boolean call() { - return mArray.get(3).getNumber() == 6; - } - }); + runAndWaitUntil(mArray, + () -> pushRef.setValue(new Bean(6), 100), + () -> mArray.get(3).getNumber() == 6); } } diff --git a/database/src/androidTest/java/com/firebase/ui/database/FirebaseArrayTest.java b/database/src/androidTest/java/com/firebase/ui/database/FirebaseArrayTest.java index af7979690..d86b76d87 100644 --- a/database/src/androidTest/java/com/firebase/ui/database/FirebaseArrayTest.java +++ b/database/src/androidTest/java/com/firebase/ui/database/FirebaseArrayTest.java @@ -45,19 +45,11 @@ public void setUp() throws Exception { mRef = FirebaseDatabase.getInstance(app).getReference().child("firebasearray"); mArray = new FirebaseArray<>(mRef, new ClassSnapshotParser<>(Integer.class)); mRef.removeValue(); - mListener = runAndWaitUntil(mArray, new Runnable() { - @Override - public void run() { - for (int i = 1; i <= INITIAL_SIZE; i++) { - mRef.push().setValue(i, i); - } + mListener = runAndWaitUntil(mArray, () -> { + for (int i = 1; i <= INITIAL_SIZE; i++) { + mRef.push().setValue(i, i); } - }, new Callable() { - @Override - public Boolean call() { - return mArray.size() == INITIAL_SIZE; - } - }); + }, () -> mArray.size() == INITIAL_SIZE); } @After @@ -68,76 +60,32 @@ public void tearDown() { @Test public void testPushIncreasesSize() throws Exception { - runAndWaitUntil(mArray, new Runnable() { - @Override - public void run() { - mRef.push().setValue(4); - } - }, new Callable() { - @Override - public Boolean call() { - return mArray.size() == 4; - } - }); + runAndWaitUntil(mArray, () -> mRef.push().setValue(4), () -> mArray.size() == 4); } @Test public void testPushAppends() throws Exception { - runAndWaitUntil(mArray, new Runnable() { - @Override - public void run() { - mRef.push().setValue(4, 4); - } - }, new Callable() { - @Override - public Boolean call() { - return mArray.get(3).equals(4); - } - }); + runAndWaitUntil(mArray, () -> mRef.push().setValue(4, 4), () -> mArray.get(3).equals(4)); } @Test public void testAddValueWithPriority() throws Exception { - runAndWaitUntil(mArray, new Runnable() { - @Override - public void run() { - mRef.push().setValue(4, 0.5); - } - }, new Callable() { - @Override - public Boolean call() { - return mArray.get(3).equals(3) && mArray.get(0).equals(4); - } - }); + runAndWaitUntil(mArray, + () -> mRef.push().setValue(4, 0.5), + () -> mArray.get(3).equals(3) && mArray.get(0).equals(4)); } @Test public void testChangePriorityBackToFront() throws Exception { - runAndWaitUntil(mArray, new Runnable() { - @Override - public void run() { - mArray.getSnapshot(2).getRef().setPriority(0.5); - } - }, new Callable() { - @Override - public Boolean call() { - return isValuesEqual(mArray, new int[]{3, 1, 2}); - } - }); + runAndWaitUntil(mArray, + () -> mArray.getSnapshot(2).getRef().setPriority(0.5), + () -> isValuesEqual(mArray, new int[]{3, 1, 2})); } @Test public void testChangePriorityFrontToBack() throws Exception { - runAndWaitUntil(mArray, new Runnable() { - @Override - public void run() { - mArray.getSnapshot(0).getRef().setPriority(4); - } - }, new Callable() { - @Override - public Boolean call() { - return isValuesEqual(mArray, new int[]{2, 3, 1}); - } - }); + runAndWaitUntil(mArray, + () -> mArray.getSnapshot(0).getRef().setPriority(4), + () -> isValuesEqual(mArray, new int[]{2, 3, 1})); } } diff --git a/database/src/androidTest/java/com/firebase/ui/database/FirebaseIndexArrayOfObjectsTest.java b/database/src/androidTest/java/com/firebase/ui/database/FirebaseIndexArrayOfObjectsTest.java index e56b87af3..c807c69d3 100644 --- a/database/src/androidTest/java/com/firebase/ui/database/FirebaseIndexArrayOfObjectsTest.java +++ b/database/src/androidTest/java/com/firebase/ui/database/FirebaseIndexArrayOfObjectsTest.java @@ -50,19 +50,11 @@ public void setUp() throws Exception { mRef.removeValue(); mKeyRef.removeValue(); - mListener = runAndWaitUntil(mArray, new Runnable() { - @Override - public void run() { - for (int i = 1; i <= INITIAL_SIZE; i++) { - TestUtils.pushValue(mKeyRef, mRef, new Bean(i, "Text " + i, i % 2 == 0), i); - } + mListener = runAndWaitUntil(mArray, () -> { + for (int i = 1; i <= INITIAL_SIZE; i++) { + TestUtils.pushValue(mKeyRef, mRef, new Bean(i, "Text " + i, i % 2 == 0), i); } - }, new Callable() { - @Override - public Boolean call() { - return mArray.size() == INITIAL_SIZE; - } - }); + }, () -> mArray.size() == INITIAL_SIZE); } @After @@ -73,64 +65,34 @@ public void tearDown() { @Test public void testPushIncreasesSize() throws Exception { - runAndWaitUntil(mArray, new Runnable() { - @Override - public void run() { - TestUtils.pushValue(mKeyRef, mRef, new Bean(4), null); - } - }, new Callable() { - @Override - public Boolean call() { - return mArray.size() == 4; - } - }); + runAndWaitUntil(mArray, + () -> TestUtils.pushValue(mKeyRef, mRef, new Bean(4), null), + () -> mArray.size() == 4); } @Test public void testPushAppends() throws Exception { - runAndWaitUntil(mArray, new Runnable() { - @Override - public void run() { - TestUtils.pushValue(mKeyRef, mRef, new Bean(4), 4); - } - }, new Callable() { - @Override - public Boolean call() { - return mArray.get(3).getNumber() == 4; - } - }); + runAndWaitUntil(mArray, + () -> TestUtils.pushValue(mKeyRef, mRef, new Bean(4), 4), + () -> mArray.get(3).getNumber() == 4); } @Test public void testAddValueWithPriority() throws Exception { - runAndWaitUntil(mArray, new Runnable() { - @Override - public void run() { - TestUtils.pushValue(mKeyRef, mRef, new Bean(4), 0.5); - } - }, new Callable() { - @Override - public Boolean call() { - return mArray.get(3).getNumber() == 3 && mArray.get(0).getNumber() == 4; - } - }); + runAndWaitUntil(mArray, + () -> TestUtils.pushValue(mKeyRef, mRef, new Bean(4), 0.5), + () -> mArray.get(3).getNumber() == 3 && mArray.get(0).getNumber() == 4); } @Test public void testChangePriorities() throws Exception { - runAndWaitUntil(mArray, new Runnable() { - @Override - public void run() { - mKeyRef.child(mArray.getSnapshot(2).getKey()).setPriority(0.5); - } - }, new Callable() { - @Override - public Boolean call() { - return mArray.get(0).getNumber() == 3 - && mArray.get(1).getNumber() == 1 - && mArray.get(2).getNumber() == 2; - //return isValuesEqual(mArray, new int[]{3, 1, 2}); - } - }); + runAndWaitUntil(mArray, + () -> mKeyRef.child(mArray.getSnapshot(2).getKey()).setPriority(0.5), + () -> { + return mArray.get(0).getNumber() == 3 + && mArray.get(1).getNumber() == 1 + && mArray.get(2).getNumber() == 2; + //return isValuesEqual(mArray, new int[]{3, 1, 2}); + }); } } diff --git a/database/src/androidTest/java/com/firebase/ui/database/FirebaseIndexArrayTest.java b/database/src/androidTest/java/com/firebase/ui/database/FirebaseIndexArrayTest.java index 5f13f2316..6fb65109b 100644 --- a/database/src/androidTest/java/com/firebase/ui/database/FirebaseIndexArrayTest.java +++ b/database/src/androidTest/java/com/firebase/ui/database/FirebaseIndexArrayTest.java @@ -51,19 +51,11 @@ public void setUp() throws Exception { mRef.removeValue(); mKeyRef.removeValue(); - mListener = runAndWaitUntil(mArray, new Runnable() { - @Override - public void run() { - for (int i = 1; i <= INITIAL_SIZE; i++) { - TestUtils.pushValue(mKeyRef, mRef, i, i); - } + mListener = runAndWaitUntil(mArray, () -> { + for (int i = 1; i <= INITIAL_SIZE; i++) { + TestUtils.pushValue(mKeyRef, mRef, i, i); } - }, new Callable() { - @Override - public Boolean call() { - return mArray.size() == INITIAL_SIZE; - } - }); + }, () -> mArray.size() == INITIAL_SIZE); } @After @@ -74,61 +66,29 @@ public void tearDown() { @Test public void testPushIncreasesSize() throws Exception { - runAndWaitUntil(mArray, new Runnable() { - @Override - public void run() { - TestUtils.pushValue(mKeyRef, mRef, 4, null); - } - }, new Callable() { - @Override - public Boolean call() { - return mArray.size() == 4; - } - }); + runAndWaitUntil(mArray, + () -> TestUtils.pushValue(mKeyRef, mRef, 4, null), + () -> mArray.size() == 4); } @Test public void testPushAppends() throws Exception { - runAndWaitUntil(mArray, new Runnable() { - @Override - public void run() { - TestUtils.pushValue(mKeyRef, mRef, 4, 4); - } - }, new Callable() { - @Override - public Boolean call() { - return mArray.get(3).equals(4); - } - }); + runAndWaitUntil(mArray, + () -> TestUtils.pushValue(mKeyRef, mRef, 4, 4), + () -> mArray.get(3).equals(4)); } @Test public void testAddValueWithPriority() throws Exception { - runAndWaitUntil(mArray, new Runnable() { - @Override - public void run() { - TestUtils.pushValue(mKeyRef, mRef, 4, 0.5); - } - }, new Callable() { - @Override - public Boolean call() { - return mArray.get(3).equals(3) && mArray.get(0).equals(4); - } - }); + runAndWaitUntil(mArray, + () -> TestUtils.pushValue(mKeyRef, mRef, 4, 0.5), + () -> mArray.get(3).equals(3) && mArray.get(0).equals(4)); } @Test public void testChangePriorities() throws Exception { - runAndWaitUntil(mArray, new Runnable() { - @Override - public void run() { - mKeyRef.child(mArray.getSnapshot(2).getKey()).setPriority(0.5); - } - }, new Callable() { - @Override - public Boolean call() { - return isValuesEqual(mArray, new int[]{3, 1, 2}); - } - }); + runAndWaitUntil(mArray, + () -> mKeyRef.child(mArray.getSnapshot(2).getKey()).setPriority(0.5), + () -> isValuesEqual(mArray, new int[]{3, 1, 2})); } } diff --git a/database/src/main/java/com/firebase/ui/database/FirebaseIndexArray.java b/database/src/main/java/com/firebase/ui/database/FirebaseIndexArray.java index 563a1ad17..7b7f0d4b0 100644 --- a/database/src/main/java/com/firebase/ui/database/FirebaseIndexArray.java +++ b/database/src/main/java/com/firebase/ui/database/FirebaseIndexArray.java @@ -68,13 +68,7 @@ public FirebaseIndexArray(@NonNull Query keyQuery, @NonNull SnapshotParser parser) { super(parser); mDataRef = dataRef; - mKeySnapshots = new FirebaseArray<>(keyQuery, new SnapshotParser() { - @NonNull - @Override - public String parseSnapshot(@NonNull DataSnapshot snapshot) { - return snapshot.getKey(); - } - }); + mKeySnapshots = new FirebaseArray<>(keyQuery, snapshot -> snapshot.getKey()); } @Override diff --git a/database/src/main/java/com/firebase/ui/database/paging/FirebaseDataSource.java b/database/src/main/java/com/firebase/ui/database/paging/FirebaseDataSource.java index 268f1acbe..8d8a325b6 100644 --- a/database/src/main/java/com/firebase/ui/database/paging/FirebaseDataSource.java +++ b/database/src/main/java/com/firebase/ui/database/paging/FirebaseDataSource.java @@ -70,38 +70,32 @@ public void loadInitial(@NonNull final LoadInitialParams params, mLoadingState.postValue(LoadingState.LOADING_INITIAL); Query mInitQuery = mQuery.limitToFirst(params.requestedLoadSize); - mInitQuery.get().addOnSuccessListener(new OnSuccessListener() { - @Override - public void onSuccess(DataSnapshot dataSnapshot) { - if (dataSnapshot.exists()) { + mInitQuery.get().addOnSuccessListener(dataSnapshot -> { + if (dataSnapshot.exists()) { - //Make List of DataSnapshot - List data = new ArrayList<>(); + //Make List of DataSnapshot + List data = new ArrayList<>(); - for (DataSnapshot snapshot : dataSnapshot.getChildren()){ - data.add(snapshot); - } + for (DataSnapshot snapshot : dataSnapshot.getChildren()){ + data.add(snapshot); + } - //Get Last Key - String lastKey = getLastPageKey(data); + //Get Last Key + String lastKey = getLastPageKey(data); - //Update State - mLoadingState.postValue(LoadingState.LOADED); - mRetryRunnable = null; + //Update State + mLoadingState.postValue(LoadingState.LOADED); + mRetryRunnable = null; - callback.onResult(data, lastKey, lastKey); + callback.onResult(data, lastKey, lastKey); - } else { - mRetryRunnable = getRetryLoadInitial(params, callback); - setDatabaseNotFoundError(); - } - } - }).addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { + } else { mRetryRunnable = getRetryLoadInitial(params, callback); - setError(e); + setDatabaseNotFoundError(); } + }).addOnFailureListener(e -> { + mRetryRunnable = getRetryLoadInitial(params, callback); + setError(e); }); } @@ -119,75 +113,59 @@ public void loadAfter(@NonNull final LoadParams params, //Load params.requestedLoadSize+1 because, first data item is getting ignored. Query mNewQuery = mQuery.startAt(null, params.key).limitToFirst(params.requestedLoadSize + 1); - mNewQuery.get().addOnSuccessListener(new OnSuccessListener() { - @Override - public void onSuccess(DataSnapshot dataSnapshot) { - if (dataSnapshot.exists()) { - - //Make List of DataSnapshot - List data = new ArrayList<>(); - String lastKey = null; - - Iterator iterator = dataSnapshot.getChildren().iterator(); - - //Skip First Item - if (iterator.hasNext()) { - iterator.next(); - } - - while (iterator.hasNext()) { - DataSnapshot snapshot = iterator.next(); - data.add(snapshot); - } - - //Update State - mLoadingState.postValue(LoadingState.LOADED); - mRetryRunnable = null; - - //Detect End of Data - if (data.isEmpty()) - mLoadingState.postValue(LoadingState.FINISHED); - else { - //Get Last Key - lastKey = getLastPageKey(data); - } - - callback.onResult(data, lastKey); - - } else { - mRetryRunnable = getRetryLoadAfter(params, callback); - setDatabaseNotFoundError(); + mNewQuery.get().addOnSuccessListener(dataSnapshot -> { + if (dataSnapshot.exists()) { + + //Make List of DataSnapshot + List data = new ArrayList<>(); + String lastKey = null; + + Iterator iterator = dataSnapshot.getChildren().iterator(); + + //Skip First Item + if (iterator.hasNext()) { + iterator.next(); } - } - }).addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { + + while (iterator.hasNext()) { + DataSnapshot snapshot = iterator.next(); + data.add(snapshot); + } + + //Update State + mLoadingState.postValue(LoadingState.LOADED); + mRetryRunnable = null; + + //Detect End of Data + if (data.isEmpty()) + mLoadingState.postValue(LoadingState.FINISHED); + else { + //Get Last Key + lastKey = getLastPageKey(data); + } + + callback.onResult(data, lastKey); + + } else { mRetryRunnable = getRetryLoadAfter(params, callback); - setError(e); + setDatabaseNotFoundError(); } + }).addOnFailureListener(e -> { + mRetryRunnable = getRetryLoadAfter(params, callback); + setError(e); }); } @NonNull private Runnable getRetryLoadAfter(@NonNull final LoadParams params, @NonNull final LoadCallback callback) { - return new Runnable() { - @Override - public void run() { - loadAfter(params, callback); - } - }; + return () -> loadAfter(params, callback); } @NonNull private Runnable getRetryLoadInitial(@NonNull final LoadInitialParams params, @NonNull final LoadInitialCallback callback) { - return new Runnable() { - @Override - public void run() { - loadInitial(params, callback); - } - }; + return () -> loadInitial(params, callback); } public void retry() { diff --git a/database/src/main/java/com/firebase/ui/database/paging/FirebaseRecyclerPagingAdapter.java b/database/src/main/java/com/firebase/ui/database/paging/FirebaseRecyclerPagingAdapter.java index 0a38fbbeb..11ddeacd7 100644 --- a/database/src/main/java/com/firebase/ui/database/paging/FirebaseRecyclerPagingAdapter.java +++ b/database/src/main/java/com/firebase/ui/database/paging/FirebaseRecyclerPagingAdapter.java @@ -43,43 +43,29 @@ public abstract class FirebaseRecyclerPagingAdapter mDataSourceObserver = new Observer() { - @Override - public void onChanged(@Nullable FirebaseDataSource source) { + private final Observer mDataSourceObserver = source -> { - } }; //State Observer - private final Observer mStateObserver = new Observer() { - @Override - public void onChanged(@Nullable LoadingState state) { - if (state == null) { - return; - } - - onLoadingStateChanged(state); + private final Observer mStateObserver = state -> { + if (state == null) { + return; } + + onLoadingStateChanged(state); }; //Data Observer - private final Observer> mDataObserver = new Observer>() { - @Override - public void onChanged(@Nullable PagedList snapshots) { - if (snapshots == null) { - return; - } - submitList(snapshots); + private final Observer> mDataObserver = snapshots -> { + if (snapshots == null) { + return; } + submitList(snapshots); }; //DatabaseError Observer - private final Observer mErrorObserver = new Observer() { - @Override - public void onChanged(@Nullable DatabaseError databaseError) { - onError(databaseError); - } - }; + private final Observer mErrorObserver = databaseError -> onError(databaseError); /** * Construct a new FirestorePagingAdapter from the given {@link DatabasePagingOptions}. @@ -100,31 +86,20 @@ public void init() { //Init Data Source mDataSource = Transformations.map(mPagedList, - new Function, FirebaseDataSource>() { - @Override - public FirebaseDataSource apply(PagedList input) { - return (FirebaseDataSource) input.getDataSource(); - } - }); + input -> (FirebaseDataSource) input.getDataSource()); //Init Loading State mLoadingState = Transformations.switchMap(mPagedList, - new Function, LiveData>() { - @Override - public LiveData apply(PagedList input) { - FirebaseDataSource dataSource = (FirebaseDataSource) input.getDataSource(); - return dataSource.getLoadingState(); - } + input -> { + FirebaseDataSource dataSource = (FirebaseDataSource) input.getDataSource(); + return dataSource.getLoadingState(); }); //Init Database Error mDatabaseError = Transformations.switchMap(mPagedList, - new Function, LiveData>() { - @Override - public LiveData apply(PagedList input) { - FirebaseDataSource dataSource = (FirebaseDataSource) input.getDataSource(); - return dataSource.getLastError(); - } + input -> { + FirebaseDataSource dataSource = (FirebaseDataSource) input.getDataSource(); + return dataSource.getLastError(); }); mParser = mOptions.getParser(); diff --git a/firestore/src/androidTest/java/com/firebase/ui/firestore/FirestoreArrayTest.java b/firestore/src/androidTest/java/com/firebase/ui/firestore/FirestoreArrayTest.java index 701cda6b4..a502f9132 100644 --- a/firestore/src/androidTest/java/com/firebase/ui/firestore/FirestoreArrayTest.java +++ b/firestore/src/androidTest/java/com/firebase/ui/firestore/FirestoreArrayTest.java @@ -127,22 +127,14 @@ public void setUp() throws Exception { mListener = mArray.addChangeEventListener(new LoggingListener()); // Add some initial data - runAndVerify(new Callable>() { - @Override - public Task call() { - List tasks = new ArrayList<>(); - for (int i = 0; i < INITIAL_SIZE; i++) { - tasks.add(mCollectionRef.document().set(new IntegerDocument(i))); - } - - return Tasks.whenAll(tasks.toArray(new Task[tasks.size()])); + runAndVerify(() -> { + List tasks = new ArrayList<>(); + for (int i = 0; i < INITIAL_SIZE; i++) { + tasks.add(mCollectionRef.document().set(new IntegerDocument(i))); } - }, new Callable() { - @Override - public Boolean call() { - return mArray.size() == INITIAL_SIZE; - } - }); + + return Tasks.whenAll(tasks.toArray(new Task[tasks.size()])); + }, () -> mArray.size() == INITIAL_SIZE); } @After @@ -159,17 +151,8 @@ public void tearDown() { */ @Test public void testPushIncreasesSize() throws Exception { - runAndVerify(new Callable>() { - @Override - public Task call() { - return mCollectionRef.document().set(new IntegerDocument(4)); - } - }, new Callable() { - @Override - public Boolean call() { - return mArray.size() == (INITIAL_SIZE + 1); - } - }); + runAndVerify(() -> mCollectionRef.document().set(new IntegerDocument(4)), + () -> mArray.size() == (INITIAL_SIZE + 1)); } /** @@ -180,20 +163,12 @@ public Boolean call() { public void testAddToEnd() throws Exception { final int value = 4; - runAndVerify(new Callable>() { - @Override - public Task call() { - return mCollectionRef.document().set(new IntegerDocument(value)); + runAndVerify(() -> mCollectionRef.document().set(new IntegerDocument(value)), () -> { + if (mArray.size() == (INITIAL_SIZE + 1)) { + return mArray.get(mArray.size() - 1).field == value; } - }, new Callable() { - @Override - public Boolean call() { - if (mArray.size() == (INITIAL_SIZE + 1)) { - return mArray.get(mArray.size() - 1).field == value; - } - return false; - } + return false; }); } @@ -205,20 +180,12 @@ public Boolean call() { public void testAddToBeginning() throws Exception { final int value = -1; - runAndVerify(new Callable>() { - @Override - public Task call() { - return mCollectionRef.document().set(new IntegerDocument(value)); + runAndVerify(() -> mCollectionRef.document().set(new IntegerDocument(value)), () -> { + if (mArray.size() == (INITIAL_SIZE + 1)) { + return mArray.get(0).field == value; } - }, new Callable() { - @Override - public Boolean call() { - if (mArray.size() == (INITIAL_SIZE + 1)) { - return mArray.get(0).field == value; - } - return false; - } + return false; }); } @@ -233,12 +200,7 @@ private void runAndVerify(Callable> setup, Callable verify) thr // Run the setup action and release the semaphore when it is complete Task task = setup.call(); - task.addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - semaphore.release(); - } - }); + task.addOnCompleteListener(task1 -> semaphore.release()); // Wait for the verification condition to be met, or time out boolean isDone = false; diff --git a/firestore/src/main/java/com/firebase/ui/firestore/paging/FirestorePagingOptions.java b/firestore/src/main/java/com/firebase/ui/firestore/paging/FirestorePagingOptions.java index 272f17d14..30060b209 100644 --- a/firestore/src/main/java/com/firebase/ui/firestore/paging/FirestorePagingOptions.java +++ b/firestore/src/main/java/com/firebase/ui/firestore/paging/FirestorePagingOptions.java @@ -162,12 +162,7 @@ public Builder setQuery(@NonNull final Query query, mParser = parser; final Pager pager = new Pager<>(config, - new Function0>() { - @Override - public PagingSource invoke() { - return new FirestorePagingSource(query, source); - } - }); + () -> new FirestorePagingSource(query, source)); mPagingData = PagingLiveData.cachedIn(PagingLiveData.getLiveData(pager), mOwner.getLifecycle()); diff --git a/firestore/src/main/java/com/firebase/ui/firestore/paging/FirestorePagingSource.java b/firestore/src/main/java/com/firebase/ui/firestore/paging/FirestorePagingSource.java index 8b453d98e..8b632356e 100644 --- a/firestore/src/main/java/com/firebase/ui/firestore/paging/FirestorePagingSource.java +++ b/firestore/src/main/java/com/firebase/ui/firestore/paging/FirestorePagingSource.java @@ -38,27 +38,19 @@ public Single> loadSingle(@NonNull LoadPar task = params.getKey().getPageQuery(mQuery, params.getLoadSize()).get(mSource); } - return Single.fromCallable(new Callable>() { - @Override - public LoadResult call() throws Exception { - Tasks.await(task); - if (task.isSuccessful()) { - QuerySnapshot snapshot = task.getResult(); - PageKey nextPage = getNextPageKey(snapshot); - if (snapshot.getDocuments().isEmpty()) { - return toLoadResult(snapshot.getDocuments(), null); - } - return toLoadResult(snapshot.getDocuments(), nextPage); + return Single.fromCallable(() -> { + Tasks.await(task); + if (task.isSuccessful()) { + QuerySnapshot snapshot = task.getResult(); + PageKey nextPage = getNextPageKey(snapshot); + if (snapshot.getDocuments().isEmpty()) { + return toLoadResult(snapshot.getDocuments(), null); } - throw task.getException(); + return toLoadResult(snapshot.getDocuments(), nextPage); } + throw task.getException(); }).subscribeOn(Schedulers.io()) - .onErrorReturn(new Function>() { - @Override - public LoadResult apply(Throwable throwable) { - return new LoadResult.Error<>(throwable); - } - }); + .onErrorReturn(throwable -> new LoadResult.Error<>(throwable)); } private LoadResult toLoadResult( diff --git a/storage/src/main/java/com/firebase/ui/storage/images/FirebaseImageLoader.java b/storage/src/main/java/com/firebase/ui/storage/images/FirebaseImageLoader.java index d15b2a08b..2ed9150fe 100644 --- a/storage/src/main/java/com/firebase/ui/storage/images/FirebaseImageLoader.java +++ b/storage/src/main/java/com/firebase/ui/storage/images/FirebaseImageLoader.java @@ -130,19 +130,11 @@ public void loadData(@NonNull Priority priority, @NonNull final DataCallback callback) { mStreamTask = mRef.getStream(); mStreamTask - .addOnSuccessListener(new OnSuccessListener() { - @Override - public void onSuccess(StreamDownloadTask.TaskSnapshot snapshot) { - mInputStream = snapshot.getStream(); - callback.onDataReady(mInputStream); - } + .addOnSuccessListener(snapshot -> { + mInputStream = snapshot.getStream(); + callback.onDataReady(mInputStream); }) - .addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - callback.onLoadFailed(e); - } - }); + .addOnFailureListener(e -> callback.onLoadFailed(e)); } @Override