下面列出了android.support.annotation.AnimRes#android.support.annotation.VisibleForTesting 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@AnyThread
@VisibleForTesting
void writeState(@Nullable AuthState state) {
mPrefsLock.lock();
try {
SharedPreferences.Editor editor = mPrefs.edit();
if (state == null) {
editor.remove(KEY_STATE);
} else {
editor.putString(KEY_STATE, state.jsonSerializeString());
}
if (!editor.commit()) {
throw new IllegalStateException("Failed to write state to shared prefs");
}
} finally {
mPrefsLock.unlock();
}
}
/**
* Compares two strings that contain versions. The string should only contain
* dot-separated segments that contain an arbitrary number of digits digits [0-9].
*
* @param s1 the first string.
* @param s2 the second string.
* @return -1 if s1<s2, +1 if s1>s2 and 0 if s1=s2. If two versions are equal, the
* version with the higher number of segments is considered to be higher.
*
* @throws IllegalArgumentException if any of the strings contains an illegal
* version number.
*/
@VisibleForTesting
static int compareVersions(String s1, String s2) {
if (s1 == null || s2 == null) {
throw new IllegalArgumentException("The input values cannot be null");
}
String[] s1segments = s1.split("\\.");
String[] s2segments = s2.split("\\.");
for (int i = 0; i < s1segments.length && i < s2segments.length; i++) {
try {
int s1segment = Integer.parseInt(s1segments[i]);
int s2segment = Integer.parseInt(s2segments[i]);
if (s1segment != s2segment) {
return Integer.signum(s1segment - s2segment);
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Unable to convert version segments into"
+ " integers: " + s1segments[i] + " & " + s2segments[i],
e);
}
}
return Integer.signum(s1segments.length - s2segments.length);
}
@VisibleForTesting
Footer.Props getFooterProps(@NonNull final Context context) {
Button.Props buttonAction = null;
Button.Props linkAction = null;
final PaymentResultViewModel paymentResultViewModel = PaymentResultViewModelFactory
.createPaymentResultViewModel(props);
if (paymentResultViewModel.getLinkAction() != null) {
linkAction = new Button.Props(paymentResultViewModel.getLinkActionTitle(context),
paymentResultViewModel.getLinkAction());
}
if (paymentResultViewModel.getMainAction() != null) {
buttonAction = new Button.Props(paymentResultViewModel.getMainActionTitle(context),
paymentResultViewModel.getMainAction());
}
return new Footer.Props(buttonAction, linkAction);
}
@VisibleForTesting
int getLayoutResource() {
int layoutResource;
switch (type) {
case FIXED:
layoutResource = R.layout.bb_bottom_bar_item_fixed;
break;
case SHIFTING:
layoutResource = R.layout.bb_bottom_bar_item_shifting;
break;
case TABLET:
layoutResource = R.layout.bb_bottom_bar_item_fixed_tablet;
break;
default:
// should never happen
throw new RuntimeException("Unknown BottomBarTab type.");
}
return layoutResource;
}
@VisibleForTesting
static String longAsHex(long val) {
char[] result = new char[Long.SIZE / Byte.SIZE * 2];
int index = result.length - 1;
while (index >= 0) {
result[index--] = HEX_DIGITS[(int)(val & HALF_BYTE_MASK)];
val >>>= HALF_BYTE_WIDTH;
result[index--] = HEX_DIGITS[(int)(val & HALF_BYTE_MASK)];
val >>>= HALF_BYTE_WIDTH;
}
return new String(result);
}
@VisibleForTesting
void restoreState(Bundle savedInstanceState) {
if (savedInstanceState != null) {
isComingFromRestoredState = true;
ignoreTabReselectionListener = true;
int restoredPosition = savedInstanceState.getInt(STATE_CURRENT_SELECTED_TAB, currentTabPosition);
selectTabAtPosition(restoredPosition, false);
}
}
@SuppressWarnings("WeakerAccess")
@VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE)
public void handleWork(Context context, Intent intent) {
String action = intent.getAction();
if (action == null) {
return;
}
switch (action) {
case ACTION_CLOUD_MESSAGE_RECEIVE:
handleMessage(context, intent);
break;
case ACTION_NEW_TOKEN:
handleNewToken(context, intent);
break;
case ACTION_TOKEN_CLEANUP:
handleTokenCleanup(context, intent);
break;
case ACTION_TOKEN_RESET:
handleTokenReset(context, intent);
break;
case ACTION_TOKEN_ACQUIRE:
handleTokenAcquire(context, intent);
break;
}
}
@SuppressWarnings("WeakerAccess") // Visible for testing
@VisibleForTesting
InputStream openAssetInternal(String path) throws IOException {
if (path.startsWith(ASSETS_PREFIX)) {
final AssetManager am = getAssets();
return am.open(path.substring(ASSETS_PREFIX.length()));
} else if (path.startsWith("file:")) {
return FileUtil.openFile(URI.create(path));
} else {
return FileUtil.openFile(path);
}
}
@VisibleForTesting
double calculateMaxDistance(double leftHorizontalDistance, double rightHorizontalDistance, double maximum) {
if (leftHorizontalDistance > rightHorizontalDistance && leftHorizontalDistance > maximum) {
maximum = leftHorizontalDistance;
} else if (rightHorizontalDistance > leftHorizontalDistance && rightHorizontalDistance > maximum) {
maximum = rightHorizontalDistance;
}
return maximum;
}
/**
* Builds a URL with necessary query parameters to load in the {@link WebView}.
*
* @param rideParameters the {@link RideParameters} to build into the query
* @return the URL {@link String} to load in the {@link WebView}
*/
@NonNull
@VisibleForTesting
static String buildUrlFromRideParameters(@NonNull Context context,
@NonNull RideParameters rideParameters,
@NonNull SessionConfiguration loginConfiguration) {
final String ENDPOINT = "components";
final String ENVIRONMENT_KEY = "env";
final String HTTPS = "https";
final String PATH = "rides/";
final String SANDBOX = "sandbox";
Uri.Builder builder = new Uri.Builder();
builder.scheme(HTTPS)
.authority(ENDPOINT + "." + loginConfiguration.getEndpointRegion().getDomain())
.appendEncodedPath(PATH);
if (rideParameters.getUserAgent() == null) {
rideParameters.setUserAgent(USER_AGENT_RIDE_VIEW);
}
RideRequestDeeplink deeplink = new RideRequestDeeplink.Builder(context)
.setSessionConfiguration(loginConfiguration)
.setRideParameters(rideParameters).build();
Uri uri = deeplink.getUri();
builder.encodedQuery(uri.getEncodedQuery());
if (loginConfiguration.getEnvironment() == SessionConfiguration.Environment.SANDBOX) {
builder.appendQueryParameter(ENVIRONMENT_KEY, SANDBOX);
}
return builder.build().toString();
}
/**
* Applies the given {@code span} to the specified range from
*
* @param targetRange the range were the span will be applied to
* @param span the span to be applied
*/
@SuppressWarnings("WeakerAccess")
@VisibleForTesting
protected void addSpan(@NonNull TargetRange targetRange, @NonNull Object span) {
final int start = targetRange.getStart();
final int end = targetRange.getEnd();
// Added 1 to the span, because it seems that internally it does exclusive range
spannableContent.setSpan(span, start, end + 1, spanFlags);
}
@VisibleForTesting
SecureCredentialsManager(@NonNull AuthenticationAPIClient apiClient, @NonNull Storage storage, @NonNull CryptoUtil crypto, @NonNull JWTDecoder jwtDecoder) {
this.apiClient = apiClient;
this.storage = storage;
this.crypto = crypto;
this.gson = GsonProvider.buildGson();
this.authenticateBeforeDecrypt = false;
this.jwtDecoder = jwtDecoder;
}
@VisibleForTesting
void login() {
final Activity activity = getActivity();
checkNotNull(callback, "Callback has not been set, call setCallback to assign value.");
if ((scopes == null || scopes.isEmpty()) && (sessionConfiguration.getScopes() == null ||
sessionConfiguration.getScopes().isEmpty())) {
throw new IllegalStateException("Scopes are not yet set.");
}
getOrCreateLoginManager().login(activity);
}
@NonNull
@VisibleForTesting
protected synchronized LoginManager getOrCreateLoginManager() {
if (loginManager == null) {
loginManager = new LoginManager(getOrCreateAccessTokenStorage(),
callback,
getOrCreateSessionConfiguration(),
requestCode);
}
return loginManager;
}
@VisibleForTesting
RideRequestButtonController(
@NonNull RideRequestButtonView rideRequestButtonView,
@NonNull RidesService ridesService,
@Nullable RideRequestButtonCallback callback) {
this.rideRequestButtonView = rideRequestButtonView;
this.rideRequestButtonCallback = callback;
this.ridesService = ridesService;
this.pendingDelegate = new TimeDelegate(rideRequestButtonView, callback);
}
@VisibleForTesting
static void assertValidState(@NonNull String requestState, @Nullable String responseState) throws AuthenticationException {
if (!requestState.equals(responseState)) {
Log.e(TAG, String.format("Received state doesn't match. Received %s but expected %s", responseState, requestState));
throw new AuthenticationException(ERROR_VALUE_ACCESS_DENIED, "The received state is invalid. Try again.");
}
}
@VisibleForTesting
@Nullable InputStream getDataStream(MasterSecret masterSecret, AttachmentId attachmentId, String dataType)
{
File dataFile = getAttachmentDataFile(attachmentId, dataType);
byte[] digest = (!dataType.equals(THUMBNAIL)) ? getAttachment(attachmentId).getDigest() : null;
try {
if (dataFile != null) return new DecryptingPartInputStream(dataFile, masterSecret, digest);
else return null;
} catch (FileNotFoundException e) {
Log.w(TAG, e);
return null;
}
}
@VisibleForTesting
protected void setCheckedId(@IdRes int id) {
checkedId = id;
if (onCheckedChangeListener != null) {
onCheckedChangeListener.onCheckedChanged(this, checkedId);
}
//TODO
/*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
final AutofillManager afm = mContext.getSystemService(AutofillManager.class);
if (afm != null) {
afm.notifyValueChanged(this);
}
}*/
}
@VisibleForTesting
void readConfiguration(@NonNull final JSONObject jsonObject)
throws InvalidJsonDocumentException {
JsonParser jsonParser = JsonParser.forJson(jsonObject);
mClientId = jsonParser.getRequiredString("client_id");
mRedirectUri = jsonParser.getRequiredUri("redirect_uri");
mEndSessionRedirectUri = jsonParser.getRequiredUri("end_session_redirect_uri");
mDiscoveryUri = jsonParser.getRequiredHttpsUri("issuer_uri")
.buildUpon().appendEncodedPath(OIDC_DISCOVERY).build();
if (!isRedirectUrisRegistered()) {
throw new InvalidJsonDocumentException(
"redirect_uri and end_session_redirect_uri is not handled by any activity "
+ "in this app! "
+ "Ensure that the appAuthRedirectScheme in your build.gradle file "
+ "is correctly configured, or that an appropriate intent filter "
+ "exists in your app manifest.");
}
mScopes = new LinkedHashSet<>(jsonParser.getRequiredStringArray("scopes"));
//We can not take hash code directly from JSONObject
//because JSONObject does not follow java has code contract
mConfigHash = jsonObject.toString().hashCode();
Log.d(TAG, String.format("Configuration loaded with: \n%s", this.toString()));
}
/**
* Only called from test, creates and returns a new {@link SimpleIdlingResource}.
*/
@VisibleForTesting
@NonNull
public IdlingResource getIdlingResource() {
if (mIdlingResource == null) {
mIdlingResource = new SimpleIdlingResource();
}
return mIdlingResource;
}
@VisibleForTesting
void showRecycler() {
if (mEmptyView != null) {
mEmptyView.setVisibility(GONE);
}
setVisibility(VISIBLE);
}
@VisibleForTesting
void showRecycler() {
if (mEmptyView != null) {
mEmptyView.setVisibility(GONE);
}
setVisibility(VISIBLE);
}
/**
* Invoke button event callback
*/
@VisibleForTesting
/*package*/ void performButtonEvent(boolean state) {
if (mListener != null) {
mListener.onButtonEvent(this, state);
}
}
@VisibleForTesting
void showRecycler() {
if (mEmptyView != null) {
mEmptyView.setVisibility(GONE);
}
setVisibility(VISIBLE);
}
@VisibleForTesting
/**
* Creates a new Message object
*/
Message createMessage(
String subject,
String body,
String address) {
if (address == null || address.isEmpty()) {
throw new IllegalArgumentException("The address parameter can't be null or empty.");
} else {
// perform a simple validation of the email address
String addressParts[] = address.split("@");
if (addressParts.length != 2 || addressParts[0].length() == 0 || addressParts[1].indexOf('.') == -1) {
throw new IllegalArgumentException(
String.format("The address parameter must be a valid email address {0}", address)
);
}
}
Message message = new Message();
EmailAddress emailAddress = new EmailAddress();
emailAddress.address = address;
Recipient recipient = new Recipient();
recipient.emailAddress = emailAddress;
message.toRecipients = Collections.singletonList(recipient);
ItemBody itemBody = new ItemBody();
itemBody.content = body;
itemBody.contentType = BodyType.HTML;
message.body = itemBody;
message.subject = subject;
return message;
}
@VisibleForTesting
boolean hasRevisionBody() { return withPeer(false, C4Document::hasRevisionBody); }
@VisibleForTesting
int getPeekHeightMin() {
return this.peekHeightMin;
}
@VisibleForTesting
protected static void reset(int sdkVersionInt) {
Platform.sdkInt = sdkVersionInt;
}
@VisibleForTesting
List<Snake> getSnakes() {
return mSnakes;
}
@VisibleForTesting
GeoEnabledConsistencyReceiver(GeofencingHelper geofencingHelper) {
this.geofencingHelper = geofencingHelper;
}