auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean isRunningInVR() { final Context context = InstrumentationRegistry.getTargetContext(); if ((context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_TYPE_MASK) START == Configuration.UI_MODE_TYPE_VR_HEADSET) { END return true; } return false; } nit: return (context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_VR_HEADSET

Target:
private boolean isRunningInVR() { final Context context = InstrumentationRegistry.getTargetContext(); return (context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_VR_HEADSET; }
Source:
public void onRegistered(int imsRadioTech) { START if (DBG) { log("onRegistered ::"); } END synchronized (mRegistrationListeners) { mRegistrationListeners.forEach(l -> l.onRegistered(imsRadioTech)); } } this can just go on one line.

Target:
public void onRegistered(int imsRadioTech) { if (DBG) log("onRegistered ::"); synchronized (mRegistrationListeners) { mRegistrationListeners.forEach(l -> l.onRegistered(imsRadioTech)); } }
Source:
private boolean supportsConditionProviders() { ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE); return !am.isLowRamDevice() START || mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH); END } this line shouldn't be there on this branch (sorry, forgot to mention)

Target:
private boolean supportsConditionProviders() { ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE); return !am.isLowRamDevice(); }
Source:
private boolean satisfiedByNetCapabilities(NetworkCapabilities nc, boolean onlyImmutable) { long requestedCapabilities = mNetworkCapabilities; long requestedUnwantedCapabilities = mUnwantedNetworkCapabilities; long providedCapabilities = nc.mNetworkCapabilities; if (onlyImmutable) { requestedCapabilities &= ~MUTABLE_CAPABILITIES; requestedUnwantedCapabilities &= ~MUTABLE_CAPABILITIES; START providedCapabilities &= ~MUTABLE_CAPABILITIES; END } return ((providedCapabilities & requestedCapabilities) == requestedCapabilities) && ((requestedUnwantedCapabilities & providedCapabilities) == 0); } I don't think this line does anything. Rationale: you only use providedCapabilities by ANDing it to requestedCapabilities and requestedUnwantedCapabilities. These both have MUTABLE_CAPABILITIES masked out. So the result of the ANDs will be guaranteed to have MUTABLE_CAPABILITIES masked out even if this line is not present. Remove?

Target:
private boolean satisfiedByNetCapabilities(NetworkCapabilities nc, boolean onlyImmutable) { long requestedCapabilities = mNetworkCapabilities; long requestedUnwantedCapabilities = mUnwantedNetworkCapabilities; long providedCapabilities = nc.mNetworkCapabilities; if (onlyImmutable) { requestedCapabilities &= ~MUTABLE_CAPABILITIES; requestedUnwantedCapabilities &= ~MUTABLE_CAPABILITIES; } return ((providedCapabilities & requestedCapabilities) == requestedCapabilities) && ((requestedUnwantedCapabilities & providedCapabilities) == 0); }
Source:
public void setCapabilities(@NetCapability int[] capabilities) { mNetworkCapabilities = BitUtils.packBits(capabilities); // Remove given capabilities from unwanted list START mUnwantedNetworkCapabilities &= ~(mNetworkCapabilities & mUnwantedNetworkCapabilities); END } Why the double & ? Don't you just want mUnwantedNetworkCapabilities &= ~mNetworkCapabilities ? I mean, A & ~(B & A) = A & (~B | ~A) = (A & ~B) | (A & ~A) = A & ~B ...or am I missing something ?

Target:
public void setCapabilities(@NetCapability int[] capabilities) { mNetworkCapabilities = BitUtils.packBits(capabilities); // Remove given capabilities from unwanted list mUnwantedNetworkCapabilities &= ~mNetworkCapabilities; }
Source:
public void onProfileServiceStateChanged(ProfileService profile, int state) { if (state != BluetoothAdapter.STATE_ON && state != BluetoothAdapter.STATE_OFF) { Log.e(TAG, "onProfileServiceStateChanged: Unhandled " + BluetoothAdapter.nameForState( state)); START return; END } Message m = mHandler.obtainMessage(MESSAGE_PROFILE_SERVICE_STATE_CHANGED); m.obj = profile; m.arg1 = state; mHandler.sendMessage(m); } I think we should crash here by throwing IllegalArgumentException.

Target:
public void onProfileServiceStateChanged(ProfileService profile, int state) { if (state != BluetoothAdapter.STATE_ON && state != BluetoothAdapter.STATE_OFF) { throw new IllegalArgumentException(BluetoothAdapter.nameForState(state)); } Message m = mHandler.obtainMessage(MESSAGE_PROFILE_SERVICE_STATE_CHANGED); m.obj = profile; m.arg1 = state; mHandler.sendMessage(m); }
Source:
void stopProfileServices() { Class[] supportedProfileServices = Config.getSupportedProfiles(); if (mRunningProfiles.size() > 0) { setAllProfileServiceStates(supportedProfileServices, BluetoothAdapter.STATE_OFF); } START debugLog("stopProfileServices() - No profiles services to stop or already stopped."); END } The meaning of this log message changes after removing the return statements.

Target:
void stopProfileServices() { Class[] supportedProfileServices = Config.getSupportedProfiles(); if (mRunningProfiles.size() == 0) { debugLog("stopProfileServices() - No profiles services to stop or already stopped."); return; } setAllProfileServiceStates(supportedProfileServices, BluetoothAdapter.STATE_OFF); }
Source:
private void handleScreenTurnedOn() { final int count = mCallbacks.size(); for (int i = 0; i < count; i++) { KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); if (cb != null) { cb.onScreenTurnedOn(); } } START updateIrisListeningState(); END } Why is this necessary? This should probably use the generic updateBiometicListeningState(). I think you're doing this to turn on the iris scanner? If so, you should leave it authenticating state, like we do for fingerprint, and send another signal to go into high power mode to complete authentication. This is what we do in fingerprint.

Target:
private void handleScreenTurnedOn() { final int count = mCallbacks.size(); for (int i = 0; i < count; i++) { KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); if (cb != null) { cb.onScreenTurnedOn(); } } }
Source:
private void handleScreenTurnedOff() { mHardwareFingerprintUnavailableRetryCount = 0; mHardwareIrisUnavailableRetryCount = 0; final int count = mCallbacks.size(); for (int i = 0; i < count; i++) { KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); if (cb != null) { cb.onScreenTurnedOff(); } } START updateBiometricsListeningState(); END } Same question.

Target:
private void handleScreenTurnedOff() { mHardwareFingerprintUnavailableRetryCount = 0; mHardwareIrisUnavailableRetryCount = 0; final int count = mCallbacks.size(); for (int i = 0; i < count; i++) { KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); if (cb != null) { cb.onScreenTurnedOff(); } } }
Source:
private int parseIdFromInsertedUri(Uri uri) throws NumberFormatException { START int id = -1; if (uri != null) { id = Integer.parseInt(uri.getLastPathSegment()); } return id; END } Can be reduced to a single line: return (uri != null ? Integer.parseInt(uri.getLastPathSegment()) : -1)

Target:
private int parseIdFromInsertedUri(Uri uri) throws NumberFormatException { return (uri != null) ? Integer.parseInt(uri.getLastPathSegment()) : -1; }
Source:
public void removeAddress(LinkAddress address) START throws IOException { END try { mService.removeAddressFromTunnelInterface(mResourceId, address); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } Actually it would probably be better to throw something IOException than to throw a runtime exception. General guidance is a checked exception is for failures outside the programmer's control, and unchecked exceptions for programming errors. Doesn't need to be in this CL.

Target:
public void removeAddress(LinkAddress address) { try { mService.removeAddressFromTunnelInterface(mResourceId, address); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } }
Source:
public void ipSecConnectSocket(Integer socketFd, String addr, Integer port) { FileDescriptor fd = new FileDescriptor(); fd.setInt$(socketFd.intValue()); START try { InetAddress remoteAddr = NetworkUtils.numericToInetAddress(addr); Os.connect(fd, remoteAddr, port.intValue()); } catch (SocketException | ErrnoException e) { Log.e("IpSec: Failed to connect socket " + e.toString()); } } END this needs to at least return boolean success/failure

Target:
public Boolean ipSecConnectSocket(Integer socketFd, String addr, Integer port) { FileDescriptor fd = new FileDescriptor(); fd.setInt$(socketFd.intValue()); try { InetAddress remoteAddr = NetworkUtils.numericToInetAddress(addr); Os.connect(fd, remoteAddr, port.intValue()); return true; } catch (SocketException | ErrnoException e) { Log.e("IpSec: Failed to connect socket " + e.toString()); } return false; }
Source:
private void startListenForPhoneState() { if (!mListening) { int subId = SubscriptionManager.getDefaultSubscriptionId(); if (SubscriptionManager.isValidSubscriptionId(subId)) { mPhoneStateListener = new HeadsetPhoneStateListener(subId, mHeadsetService.getStateMachinesThreadLooper()); mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_SERVICE_STATE | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); mTelephonyManager.setRadioIndicationUpdateMode( START TelephonyManager.INDICATION_FILTER_FULL_NETWORK_STATE END | TelephonyManager.INDICATION_FILTER_SIGNAL_STRENGTH, TelephonyManager.INDICATION_UPDATE_MODE_IGNORE_SCREEN_OFF); mListening = true; } else { Log.w(TAG, "startListenForPhoneState, invalid subscription ID " + subId); } } } I think you probably don't need this. This is just for turning off insignificant network updates (e.g. cell tower info) when the screen is off.

Target:
private void startListenForPhoneState() { if (!mListening) { int subId = SubscriptionManager.getDefaultSubscriptionId(); if (SubscriptionManager.isValidSubscriptionId(subId)) { mPhoneStateListener = new HeadsetPhoneStateListener(subId, mHeadsetService.getStateMachinesThreadLooper()); mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_SERVICE_STATE | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); mTelephonyManager.setRadioIndicationUpdateMode( TelephonyManager.INDICATION_FILTER_SIGNAL_STRENGTH, TelephonyManager.INDICATION_UPDATE_MODE_IGNORE_SCREEN_OFF); mListening = true; } else { Log.w(TAG, "startListenForPhoneState, invalid subscription ID " + subId); } } }
Source:
protected void setUserUnlocked(int userId) { Log.i(TAG, "User unlocked, initializing the service"); if (!SystemProperties.getBoolean(AVRCP_ENABLE_PROPERTY, false)) { Log.w(TAG, "Skipping initialization of the new AVRCP Target Player List"); sInstance = null; return; } START mMediaPlayerList.init(new ListCallback()); END } This can happen on a conditional basis to avoid crash.

Target:
protected void setUserUnlocked(int userId) { Log.i(TAG, "User unlocked, initializing the service"); if (!SystemProperties.getBoolean(AVRCP_ENABLE_PROPERTY, false)) { Log.w(TAG, "Skipping initialization of the new AVRCP Target Player List"); sInstance = null; return; } if (mMediaPlayerList != null) { mMediaPlayerList.init(new ListCallback()); } }
Source:
private File getApnConfFile() { // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system". File confFile = new File(Environment.getRootDirectory(), PARTNER_APNS_PATH); File oemConfFile = new File(Environment.getOemDirectory(), OEM_APNS_PATH); File vendorConfFile = new File(Environment.getVendorDirectory(), PARTNER_APNS_PATH); File updatedConfFile = new File(Environment.getDataDirectory(), OTA_UPDATED_APNS_PATH); confFile = pickSecondIfExists(confFile, START vendorConfFile); END confFile = pickSecondIfExists(confFile, oemConfFile); confFile = pickSecondIfExists(confFile, updatedConfFile); return confFile; } you re-added this? maybe it should be a separate CL?

Target:
private File getApnConfFile() { // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system". File confFile = new File(Environment.getRootDirectory(), PARTNER_APNS_PATH); File oemConfFile = new File(Environment.getOemDirectory(), OEM_APNS_PATH); File updatedConfFile = new File(Environment.getDataDirectory(), OTA_UPDATED_APNS_PATH); confFile = pickSecondIfExists(confFile, oemConfFile); confFile = pickSecondIfExists(confFile, updatedConfFile); return confFile; }
Source:
private void START checkSerialVersionUID(long END expectedSUID, Class<?> clazz) { assertEquals(expectedSUID, ObjectStreamClass.lookup(clazz).getSerialVersionUID()); } static, and move to the bottom because it's an obviously named helper method.

Target:
private static void checkSerialVersionUID(long expectedSUID, Class<?> clazz) { assertEquals(expectedSUID, ObjectStreamClass.lookup(clazz).getSerialVersionUID()); }
Source:
public boolean isBootCompleted() throws DeviceNotAvailableException { return START getProp(SYSPROP_SYS_BOOT_COMPLETED) == "1" END && getProp(SYSPROP_DEV_BOOTCOMPLETE) == "1"; } use .equals()

Target:
public boolean isBootCompleted() throws DeviceNotAvailableException { return getProp(SYSPROP_SYS_BOOT_COMPLETED).equals("1") && getProp(SYSPROP_DEV_BOOTCOMPLETE).equals("1"); }
Source:
public boolean isTimeDetectionEnabled() { try { return Settings.Global.getInt(mContentResolver, START Settings.Global.AUTO_TIME) > 0; END } catch (Settings.SettingNotFoundException snfe) { return true; } } Technically these booleans are defined as != 0.

Target:
public boolean isTimeDetectionEnabled() { try { return Settings.Global.getInt(mContentResolver, Settings.Global.AUTO_TIME) != 0; } catch (Settings.SettingNotFoundException snfe) { return true; } }
Source:
private void startInvocation(IConfiguration config, IInvocationContext context, ITestInvocationListener listener) { START if (mInvocationStarted) { END return; } logStartInvocation(context, config); listener.invocationStarted(context); mInvocationStarted = true; } Is this to avoid the method being called more than once? If it is not an expected behavior, shouldn't we raise an exception?

Target:
private void startInvocation(IConfiguration config, IInvocationContext context, ITestInvocationListener listener) { logStartInvocation(context, config); listener.invocationStarted(context); }
Source:
public Collection<IRemoteTest> split(int shardCountHint) { if (shardCountHint <= 1 || mIsSharded) { START return null; END } Collection<IRemoteTest> tests = new ArrayList<>(); for (int i = 0; i < shardCountHint; i++) { tests.add(getTestShard(shardCountHint, i)); } return tests; } Add a log message here.

Target:
public Collection<IRemoteTest> split(int shardCountHint) { if (shardCountHint <= 1 || mIsSharded) { return null; } Collection<IRemoteTest> tests = new ArrayList<>(); for (int i = 0; i < shardCountHint; i++) { tests.add(getTestShard(shardCountHint, i)); } mIsSharded = true; return tests; }
Source:
public Collection<IRemoteTest> split(int shardCountHint) { if (shardCountHint <= 1 || mIsSharded) { return null; } Collection<IRemoteTest> tests = new ArrayList<>(); for (int i = 0; i < shardCountHint; i++) { tests.add(getTestShard(shardCountHint, i)); } START mIsSharded = true; END return tests; } Why do you need this var? Isn't this method idempotent? In general, it is better to avoid making object stateful.

Target:
public Collection<IRemoteTest> split(int shardCountHint) { if (shardCountHint <= 1) { return null; } Collection<IRemoteTest> tests = new ArrayList<>(); for (int i = 0; i < shardCountHint; i++) { tests.add(getTestShard(shardCountHint, i)); } return tests; }
Source:
public int computeCellInfoMinInterval() { // The screen is on and we're either on cellular or charging. Screen on + Charging is // a likely vehicular scenario, even if there is a nomadic AP. START if (mIsScreenOn && (!mIsWifiConnected || mIsCharging)) { END // TODO: should this be an automatic value or a fixed periodic value return CELL_INFO_INTERVAL_SHORT_MS; } // if the screen is off, or the screen is on and connected to wifi and not charging return CELL_INFO_INTERVAL_LONG_MS; } Could you maybe split this into two in blocks? if (mIsScreenOn && !mIsWifiConnected) { // Screen on + no wifi means the device is on the go return CELL_INFO_INTERVAL_SHORT_MS; } else if (mIsScreenOn && mIsCharging) { // Screen on + charging means the device is probably in a car or at home return CELL_INFO_INTERVAL_SHORT_MS; } else { return CELL_INFO_INTERVAL_LONG_MS; }

Target:
public int computeCellInfoMinInterval() { // The screen is on and we're either on cellular or charging. Screen on + Charging is // a likely vehicular scenario, even if there is a nomadic AP. if (mIsScreenOn && !mIsWifiConnected) { // Screen on without WiFi - We are in a high power likely mobile situation. return CELL_INFO_INTERVAL_SHORT_MS; } else if (mIsScreenOn && mIsCharging) { // Screen is on and we're charging, so we favor accuracy over power. return CELL_INFO_INTERVAL_SHORT_MS; } else { // If the screen is off, apps should not need cellular location at rapid intervals. // If the screen is on but we are on wifi and not charging then cellular location // accuracy is not crucial, so favor modem power saving over high accuracy. return CELL_INFO_INTERVAL_LONG_MS; } }
Source:
public boolean showMuteOverlayOnVideoCall() { if (carrierConfig == null) { START return false; END } return carrierConfig.getBoolean(CarrierConfigManager.KEY_VIDEO_CALL_MUTE_OVERLAY_VISIBLE_BOOL); } The carrierConfig sets showMuteOverlay to true by default: https://android-review.googlesource.com/c/platform/frameworks/base/+/731570/2/telephony/java/android/telephony/CarrierConfigManager.java I'm not sure whether this should be true/false. Any suggestions/thoughts on this?

Target:
public boolean showMuteOverlayOnVideoCall() { if (carrierConfig == null) { return true; } return carrierConfig.getBoolean(CarrierConfigManager.KEY_VIDEO_CALL_MUTE_OVERLAY_VISIBLE_BOOL); }
Source:
private void updateMutePreviewOverlayVisibility() { START boolean showMuteOverlay = getMuteOverlayConfig(); END // Normally the mute overlay shows on the bottom right of the preview bubble. In green screen // mode the preview is fullscreen so there's no where to anchor it. // However, it should be hidden if carrier config of mute overlay is disabled. mutePreviewOverlay.setVisibility( showMuteOverlay && muteButton.isChecked() && !isInGreenScreenMode ? View.VISIBLE : View.GONE); } Any reasons for creating a local parameter instead of using the method directly when setVisibility?

Target:
private void updateMutePreviewOverlayVisibility() { // Normally the mute overlay shows on the bottom right of the preview bubble. In green screen // mode the preview is fullscreen so there's no where to anchor it. // However, it should be hidden if carrier config of mute overlay is disabled. mutePreviewOverlay.setVisibility( getMuteOverlayConfig() && muteButton.isChecked() && !isInGreenScreenMode ? View.VISIBLE : View.GONE); }
Source:
public boolean showMuteOverlayOnVideoCall() { if (carrierConfig == null) { return true; } return START carrierConfig.getBoolean(CarrierConfigManager.KEY_VIDEO_CALL_MUTE_OVERLAY_VISIBLE_BOOL); END } This defaults to false. Since the key is new it will be missing on older platforms. Use getBoolean(String, boolean) instead.

Target:
public boolean showMuteOverlayOnVideoCall() { if (carrierConfig == null) { return true; } return carrierConfig.getBoolean( CarrierConfigManager.KEY_VIDEO_CALL_MUTE_OVERLAY_VISIBLE_BOOL, true); }
Source:
START protected DynamicRouteDescriptor() END { } package private? @SuppressWarnings("WeakerAccess") /* synthetic access */

Target:
DynamicRouteDescriptor() { }
Source:
public void onPause() { START super.onPause(); END SubscriptionManager.from(getActivity()).removeOnSubscriptionsChangedListener( mOnSubscriptionsChangeListener); } Call this at the end of the method

Target:
public void onPause() { SubscriptionManager.from(getActivity()).removeOnSubscriptionsChangedListener( mOnSubscriptionsChangeListener); super.onPause(); }
Source:
private String getApplicationLabel(ComponentName componentName) { final PackageManager pm = getPackageManager(); ApplicationInfo info = null; try { START info = pm.getApplicationInfo(componentName.getPackageName(), 0); END } catch (PackageManager.NameNotFoundException e) { Log.w(TAG, "Application info not found for packageName " + componentName .getPackageName()); } if (info == null) { return componentName.getPackageName(); } else { return info.loadLabel(pm).toString(); } } Should be able to just do: ApplicationInfo info = pm.getApplicationInfo(packageName, 0); return pm.getApplicationLabel(info);

Target:
private String getApplicationLabel(ComponentName componentName) { final PackageManager pm = getPackageManager(); try { ApplicationInfo info = pm.getApplicationInfo(componentName.getPackageName(), 0); return pm.getApplicationLabel(info).toString(); } catch (PackageManager.NameNotFoundException e) { Log.w(TAG, "Application info not found for packageName " + componentName .getPackageName()); } return componentName.getPackageName(); }
Source:
public boolean isDefaultCallScreeningApp(ComponentName componentName) { try { if (isServiceConnected()) { getTelecomService().isDefaultCallScreeningApp(componentName); } } catch (RemoteException e) { Log.e(TAG, "RemoteException calling ITelecomService#isDefaultCallScreeningApp.", e); } START return false; END } why always return false?

Target:
public boolean isDefaultCallScreeningApp(ComponentName componentName) { try { if (isServiceConnected()) { return getTelecomService().isDefaultCallScreeningApp(componentName); } } catch (RemoteException e) { Log.e(TAG, "RemoteException calling ITelecomService#isDefaultCallScreeningApp.", e); } return false; }
Source:
public void checkInterrupted() { Thread thread = Thread.currentThread(); String message; if (isInterruptable() && (message = mInterruptMessage.get(thread)) != null) { START thread.interrupt(); END throw new RunInterruptedException(message); } } Why do we need to interrupt the current thread? Wouldn't throwing RunInterruptedException be enough?

Target:
public void checkInterrupted() { Thread thread = Thread.currentThread(); if (isInterruptable()) { String message = mInterruptMessage.remove(thread); if (message != null) { thread.interrupt(); throw new RunInterruptedException(message); } } }
Source:
public void START testScrollBarViewShowAllWhenLimitedSpace() END { setLayoutRestrictions(/*allowScrollThumb=*/true, /*allowAlphaJump=*/true, /*bias=*/false); onView(withId(androidx.car.test.R.id.page_up)).check(matches(isDisplayed())); onView(withId(androidx.car.test.R.id.scrollbar_thumb)).check(matches(isDisplayed())); onView(withId(androidx.car.test.R.id.alpha_jump)).check(matches(isDisplayed())); } Enough

Target:
public void testScrollBarViewShowAllWhenLimitedSpace() { setLayoutRestrictions(/* allowScrollThumb= */true, /* allowAlphaJump= */true, /* bias= */false); onView(withId(R.id.page_up)).check(matches(isDisplayed())); onView(withId(R.id.scrollbar_thumb)).check(matches(isDisplayed())); onView(withId(R.id.alpha_jump)).check(matches(isDisplayed())); }
Source:
AlphaJumpTestAdapter() { for (int i = 0; i < START sSize; i++) END { mStrings[i] = "Dummy" + i; } } Use mStrings.length here

Target:
AlphaJumpTestAdapter() { for (int i = 0; i < mStrings.length; i++) { mStrings[i] = "Dummy" + i; } }
Source:
public void testSetBrightness() { final int mode = Settings.System.getInt(mContext.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_AUTOMATIC); START if(mode==1) { mDevicePolicyManager.setSystemSetting(ADMIN_RECEIVER_COMPONENT, Settings.System.SCREEN_BRIGHTNESS_MODE, "0"); testSetBrightnessWithValue(TEST_BRIGHTNESS_1); testSetBrightnessWithValue(TEST_BRIGHTNESS_2); mDevicePolicyManager.setSystemSetting(ADMIN_RECEIVER_COMPONENT, Settings.System.SCREEN_BRIGHTNESS_MODE, "1"); } else { testSetBrightnessWithValue(TEST_BRIGHTNESS_1); testSetBrightnessWithValue(TEST_BRIGHTNESS_2); } END } if (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC) { mDevicePolicyManager.setSystemSetting(ADMIN_RECEIVER_COMPONENT, Settings.System.SCREEN_BRIGHTNESS_MODE, "0"); } testSetBrightnessWithValue(TEST_BRIGHTNESS_1); testSetBrightnessWithValue(TEST_BRIGHTNESS_2); mDevicePolicyManager.setSystemSetting(ADMIN_RECEIVER_COMPONENT, Settings.System.SCREEN_BRIGHTNESS_MODE, mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC? "1" : "0");

Target:
public void testSetBrightness() { final int mode = Settings.System.getInt(mContext.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_AUTOMATIC); if(mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC) { mDevicePolicyManager.setSystemSetting(ADMIN_RECEIVER_COMPONENT, Settings.System.SCREEN_BRIGHTNESS_MODE, "0"); testSetBrightnessWithValue(TEST_BRIGHTNESS_1); testSetBrightnessWithValue(TEST_BRIGHTNESS_2); mDevicePolicyManager.setSystemSetting(ADMIN_RECEIVER_COMPONENT, Settings.System.SCREEN_BRIGHTNESS_MODE, mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC? "1" : "0"); } else { testSetBrightnessWithValue(TEST_BRIGHTNESS_1); testSetBrightnessWithValue(TEST_BRIGHTNESS_2); } }
Source:
public void testAuthorizedAPDUAID40() { if START (PropertyUtil.getFirstApiLevel() < Build.VERSION_CODES.P) { END return; } for (byte[] apdu : AUTHORIZED_APDU_AID_40) { testTransmitAPDU(AID_40, apdu); } } Done

Target:
public void testAuthorizedAPDUAID40() { for (byte[] apdu : AUTHORIZED_APDU_AID_40) { testTransmitAPDU(AID_40, apdu); } }
Source:
protected void accumulateConsecutiveDnsTimeoutCount(int code) { final DnsResult result = new DnsResult(code); // Keep only the last mSize events in the mDnsEvents. Remove the oldest one if its size // become larger than mSize. final int index = mResultIndices.add(); START if (index >= 0 && index < mSize) { END mDnsEvents[index] = result; } if (result.isTimeout()) { mConsecutiveTimeoutCount++; } else { // Keep the event in mDnsEvents without clearing it so that there are logs to do the // simulation and analysis. mConsecutiveTimeoutCount = 0; } } I suggest you simply say mDnsEvents[mResultIndices.add()];, as the RingBufferIndices class is defined to never return anything out of these bounds. It's contractual.

Target:
protected void accumulateConsecutiveDnsTimeoutCount(int code) { final DnsResult result = new DnsResult(code); mDnsEvents[mResultIndices.add()] = result; if (result.isTimeout()) { mConsecutiveTimeoutCount++; } else { // Keep the event in mDnsEvents without clearing it so that there are logs to do the // simulation and analysis. mConsecutiveTimeoutCount = 0; } }
Source:
public void setVpnProxy(@Nullable ProxyInfo proxyInfo) { synchronized (mProxyLock) { if (proxyInfo == null) { mVPNProxy = null; return; } START if (!TextUtils.isEmpty(proxyInfo.getHost()) && proxyInfo.getPort() != 0) { END // vpn proxy with empty blacklist mVPNProxy = proxyInfo; } } } So if there is a host, but the port is 0, we simply don't change the previous value ? That sounds counter-intuitive. Honestly I think this should simply read synchronized (mProxyLock) { mVPNProxy = proxyInfo; }

Target:
public void setVpnProxy(@Nullable ProxyInfo proxyInfo) { synchronized (mProxyLock) { mVPNProxy = proxyInfo; } }
Source:
public void setUp() { mAppStartupHelper = new AppStartupHelper(); // Make sure the apps are starting from the clean state. HelperTestUtility.clearApp(String.format(KILL_TEST_APP_CMD_TEMPLATE, CALENDAR_PKG_NAME)); START HelperTestUtility.clearApp(String.format(KILL_TEST_APP_CMD_TEMPLATE, SETTINGS_PKG_NAME)); END HelperTestUtility.clearApp(String.format(KILL_TEST_APP_CMD_TEMPLATE, SETTINGS_PKG_NAME)); // Make sure display is on and unlocked. HelperTestUtility.wakeUpAndUnlock(); } Can you remove this?

Target:
public void setUp() { mAppStartupHelper = new AppStartupHelper(); // Make sure the apps are starting from the clean state. HelperTestUtility.clearApp(String.format(KILL_TEST_APP_CMD_TEMPLATE, CALENDAR_PKG_NAME)); HelperTestUtility.clearApp(String.format(KILL_TEST_APP_CMD_TEMPLATE, SETTINGS_PKG_NAME)); // Make sure display is on and unlocked. HelperTestUtility.wakeUpAndUnlock(); }
Source:
private void addRepeatedAnnotationHandlers( Builder<String, AnnotationHandler> builder, String annotationName, String containerAnnotationName, AnnotationHandler handler) { builder.put(annotationName, handler); START builder.put(containerAnnotationName, new RepeatedAnnotationHandler(annotationName, handler)); END } line too long

Target:
private static Builder<String, AnnotationHandler> addRepeatedAnnotationHandlers( Builder<String, AnnotationHandler> builder, String annotationName, String containerAnnotationName, AnnotationHandler handler) { builder.put(annotationName, handler); builder.put(containerAnnotationName, new RepeatedAnnotationHandler(annotationName, handler)); return builder; }
Source:
public void testGetFirstRowItemCount_singleItemFullSpan() throws Throwable { int itemCount = 1; setUpPagedListView(itemCount); RecyclerView recyclerView = mPagedListView.getRecyclerView(); mActivityRule.runOnUiThread(() -> { START ((GridLayoutManager) recyclerView.getLayoutManager()).setSpanSizeLookup( END new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { return SPAN_COUNT; } }); }); // Wait for the UI to lay itself out. InstrumentationRegistry.getInstrumentation().waitForIdleSync(); assertEquals(itemCount, GridLayoutManagerUtils.getFirstRowItemCount(recyclerView)); } Could you somehow fold this into the setupPagedListView method? Maybe define a new method that sets the SpanSizeLookup. The reasoning is that we already wait for idle after the setupPagedListView() method. And then we'll wait again for this. Makes the test slower.

Target:
public void testGetFirstRowItemCount_singleItemFullSpan() throws Throwable { int itemCount = 1; setUpPagedListView(itemCount, new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { return SPAN_COUNT; } }); RecyclerView recyclerView = mPagedListView.getRecyclerView(); // Wait for the UI to lay itself out. InstrumentationRegistry.getInstrumentation().waitForIdleSync(); assertEquals(itemCount, GridLayoutManagerUtils.getFirstRowItemCount(recyclerView)); }
Source:
public static void START setLogger(Logger END logger) { sLogger = logger; } Synchronize this too.

Target:
public static synchronized void setLogger(Logger logger) { sLogger = logger; }
Source:
public void testRunTimedCmd_WithOutputRedirect() throws IOException { File outputRedirect = FileUtil.createTempFile("output_redirect", ".txt"); try { CommandResult result = RunUtil.getDefault() .runTimedCmd( SHORT_TIMEOUT_MS, new START FileOutputStream(outputRedirect), END /* stderr= */ null, "echo", "TEST_OUTPUT"); assertTrue(CommandStatus.SUCCESS.equals(result.getStatus())); assertEquals("TEST_OUTPUT\n", FileUtil.readStringFromFile(outputRedirect)); } finally { FileUtil.deleteFile(outputRedirect); } } nit: close the stream

Target:
public void testRunTimedCmd_WithOutputRedirect() throws IOException { File outputRedirect = FileUtil.createTempFile("output_redirect", ".txt"); FileOutputStream outputStream = new FileOutputStream(outputRedirect); try { CommandResult result = RunUtil.getDefault() .runTimedCmd( SHORT_TIMEOUT_MS, outputStream, /* stderr= */ null, "echo", "TEST_OUTPUT"); assertTrue(CommandStatus.SUCCESS.equals(result.getStatus())); assertEquals("TEST_OUTPUT\n", FileUtil.readStringFromFile(outputRedirect)); } finally { FileUtil.deleteFile(outputRedirect); outputStream.close(); } }
Source:
public void START setSwitchScale(float END scale) { mSwitchScale = scale; requestLayout(); } I think it's ok not to expose this as a public method yet. We can have a default scaling for the switches that doesn't change.

Target:
private void setSwitchScale(float scale) { mSwitchScale = scale; requestLayout(); }
Source:
private void START initCellularData() END { CellularData data = new CellularData(); data.ratType = DataStallEventProto.RADIO_TECHNOLOGY_UNKNOWN; data.networkMccmnc = ""; data.simMccmnc = ""; data.signalStrength = UNKNOWN_SIGNAL_STRENGTH; cellularInfo = MessageNano.toByteArray(data); } I think you could return a byte[] here to have cellularInfo final

Target:
private byte[] initCellularData() { CellularData data = new CellularData(); data.ratType = DataStallEventProto.RADIO_TECHNOLOGY_UNKNOWN; data.networkMccmnc = ""; data.simMccmnc = ""; data.signalStrength = UNKNOWN_SIGNAL_STRENGTH; return MessageNano.toByteArray(data); }
Source:
START private boolean areNetworksValid(QualifiedNetworks END networks) { if (networks.qualifiedNetworks == null) { return true; } for (int network : networks.qualifiedNetworks) { if (!ACCESS_NETWORK_TRANSPORT_TYPE_MAP.containsKey(network)) { return false; } } return true; } static ?

Target:
private static boolean areNetworksValid(QualifiedNetworks networks) { if (networks.qualifiedNetworks == null) { return false; } for (int network : networks.qualifiedNetworks) { if (!ACCESS_NETWORK_TRANSPORT_TYPE_MAP.containsKey(network)) { return false; } } return true; }
Source:
public void start() { if (mRunning) return; mRunning = true; new Thread() { START @Override public void run() { END while (mRunning) { listen(); } } }.start(); } nit: Can this be a lambda?

Target:
public void start() { if (mRunning) return; mRunning = true; new Thread(() -> { while (mRunning) { listen(); } }).start(); }
Source:
public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) { START enforceNetworkStackPackagePermission(); END mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, new Pair<>(mNai, networkMonitor))); } Why do we need these permission checks? I was assuming that since the callback is coming from the object that the system is explicitly bound to, that would be enough proof that the sender is authorized to perform the action. If we do need them here, then do we need them on all the other callbacks as well?

Target:
public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) { mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, new Pair<>(mNai, networkMonitor))); }
Source:
START private END boolean doesCellInfoCorrespondToKnownMccMnc(CellInfo ci, Set<String> knownMccMncs) { String mccMnc = ci.getCellIdentity().getMccString() + ci.getCellIdentity().getMncString(); return knownMccMncs.contains(mccMnc); } nit static?

Target:
private static boolean doesCellInfoCorrespondToKnownMccMnc(CellInfo ci, Set<String> knownMccMncs) { String mccMnc = ci.getCellIdentity().getMccString() + ci.getCellIdentity().getMncString(); return knownMccMncs.contains(mccMnc); }
Source:
START public Map<String, END Set<TestInfo>> getTestCollection() { return mTestCollection; } this doesn't look like it needs to be public

Target:
private Map<String, Set<TestInfo>> getTestCollection() { return mTestCollection; }
Source:
public boolean isDefaultOrEmptyAccessibilityDelegateCompat() { return (this.getClass().equals(AccessibilityDelegateCompat.class) START && mOriginalDelegate.getClass().equals(AccessibilityDelegate.class)) END || mOriginalDelegate == null; } Does platform set an accessibilityDelegate by default?

Target:
public boolean isDefaultOrEmptyAccessibilityDelegateCompat() { return mOriginalDelegate == null || (this.getClass().equals(AccessibilityDelegateCompat.class) && mOriginalDelegate.getClass().equals(AccessibilityDelegate.class)); }
Source:
static boolean isTransformSelectedFrom(Transform[] selected, Transform[] selectFrom) { // If the selected proposal has multiple transforms with the same type, the responder MUST // choose a single one. if ((selected.length > 1) || (selected.length == 0) != (selectFrom.length == 0)) { return false; } if (selected.length == 0) return true; START Transform chosenTransform = selected[0]; END return Arrays.asList(selectFrom).contains(chosenTransform); } Nit: Can probably just inline this if it's the only place it's used

Target:
static boolean isTransformSelectedFrom(Transform[] selected, Transform[] selectFrom) { // If the selected proposal has multiple transforms with the same type, the responder MUST // choose a single one. if ((selected.length > 1) || (selected.length == 0) != (selectFrom.length == 0)) { return false; } if (selected.length == 0) return true; return Arrays.asList(selectFrom).contains(selected[0]); }
Source:
public void setUp() throws InitializationError { START initMocks(this); mRunner = spy(new LongevityClassRunner(SampleTest.class)); END } It's not great to rely on this without knowing what it relies on. In particular, you replace it with failing test elsewhere, but it's not immediately obvious that this is running the "sample" test once I got to the bottom of the file.

Target:
public void setUp() { initMocks(this); }
Source:
START public void END registerDialogWatchers() { registerWatcher( AppIsNotRespondingWatcher.class.getSimpleName(), new AppIsNotRespondingWatcher(InstrumentationRegistry.getInstrumentation())); } nit: you also could leave these private without modifying the API, JFYI. Not sure if it's necessary at all. If not, I think it's worth making that change.

Target:
private void registerDialogWatchers() { registerWatcher( AppIsNotRespondingWatcher.class.getSimpleName(), new AppIsNotRespondingWatcher(InstrumentationRegistry.getInstrumentation())); }
Source:
public static void setDefaultNightMode(@NightMode int mode) { switch (mode) { case MODE_NIGHT_NO: case MODE_NIGHT_YES: case MODE_NIGHT_FOLLOW_SYSTEM: case MODE_NIGHT_AUTO_TIME: case MODE_NIGHT_AUTO_BATTERY: if (sDefaultNightMode != mode) { sDefaultNightMode = mode; START synchronized (sActiveDelegatesLock) { END applyDayNightToActiveDelegates(); } } break; default: Log.d(TAG, "setDefaultNightMode() called with an unknown mode"); break; } } Push synchronization block into method.

Target:
public static void setDefaultNightMode(@NightMode int mode) { switch (mode) { case MODE_NIGHT_NO: case MODE_NIGHT_YES: case MODE_NIGHT_FOLLOW_SYSTEM: case MODE_NIGHT_AUTO_TIME: case MODE_NIGHT_AUTO_BATTERY: if (sDefaultNightMode != mode) { sDefaultNightMode = mode; applyDayNightToActiveDelegates(); } break; default: Log.d(TAG, "setDefaultNightMode() called with an unknown mode"); break; } }
Source:
public LinkAddress getDestinationLinkAddress() { if START (mDestination == END null) return null; return new LinkAddress(mDestination.getAddress(), mDestination.getPrefixLength()); } Ditto, I think destination can never be null.

Target:
public LinkAddress getDestinationLinkAddress() { return new LinkAddress(mDestination.getAddress(), mDestination.getPrefixLength()); }
Source:
void release() { if (mSurface == null && mSurfaceTexture == null) { return; } Resource resource; synchronized (mLock) { resource = mResourceMap.get(mSurfaceTexture); } if (resource != null) { releaseResourceWhenDetached(resource); } mSurfaceTexture = null; mSurface = null; if START (!mSurfaceToReleaseList.isEmpty()) END { for (Surface surface : mSurfaceToReleaseList) { surface.release(); } mSurfaceToReleaseList.clear(); } } The if-check for empty list can be removed. The for-loop and clear call also work for empty list.

Target:
void release() { if (mSurface == null && mSurfaceTexture == null) { return; } Resource resource; synchronized (mLock) { resource = mResourceMap.get(mSurfaceTexture); } if (resource != null) { releaseResourceWhenDetached(resource); } mSurfaceTexture = null; mSurface = null; for (Surface surface : mSurfaceToReleaseList) { surface.release(); } mSurfaceToReleaseList.clear(); }
Source:
START public static END void switchToExistingOrCreateUserType(ITestDevice device) throws DeviceNotAvailableException, UserSwitchFailedException { try { UserUtil.switchToUserType(device, mUserToSwitchTo); } catch (UserUtil.SecondaryUserNotFoundException attemptCreate) { CLog.d("No secondary users exist, creating one."); UserUtil.createAndSwitchToSecondaryUser(device); } } this should remain private, right?

Target:
private void switchToExistingOrCreateUserType(ITestDevice device) throws DeviceNotAvailableException, UserSwitchFailedException { try { UserUtil.switchToUserType(device, mUserToSwitchTo); } catch (UserUtil.SecondaryUserNotFoundException attemptCreate) { CLog.d("No secondary users exist, creating one."); UserUtil.createAndSwitchToSecondaryUser(device); } }
Source:
START public List<CaptureConfig> onPresetSession() { END return new ArrayList<>(); } Is there a reason this is a list instead of just a CaptureConfig? From a usage perspective, it only makes sense to issue a single config.

Target:
public CaptureConfig onPresetSession() { return null; }
Source:
public void onlineUseCase() { START Assume.assumeTrue(mCameraId != null); END mCamera.open(); mCamera.addOnlineUseCase(Collections.<UseCase>singletonList(mFakeUseCase)); verify(mMockOnImageAvailableListener, never()).onImageAvailable(any(ImageReader.class)); mCamera.release(); } Rather than put this in every test, you can just put it once in the setup() method.

Target:
public void onlineUseCase() { mCamera.open(); mCamera.addOnlineUseCase(Collections.<UseCase>singletonList(mFakeUseCase)); verify(mMockOnImageAvailableListener, never()).onImageAvailable(any(ImageReader.class)); mCamera.release(); }
Source:
private void validateTsPayloads(List<IkePayload> reqPayloads, List<IkePayload> respPayloads) throws TsUnacceptableException { for (int tsType : START new int[] { IkePayload.PAYLOAD_TYPE_TS_INITIATOR, IkePayload.PAYLOAD_TYPE_TS_RESPONDER }) { END IkeTsPayload reqPayload = IkePayload.getPayloadForTypeInProvidedList( tsType, IkeTsPayload.class, reqPayloads); IkeTsPayload respPayload = IkePayload.getPayloadForTypeInProvidedList( tsType, IkeTsPayload.class, respPayloads); if (!reqPayload.contains(respPayload)) { throw new TsUnacceptableException(); } } } Nit: Suggest move to a separate line, just so it's more readable.

Target:
private void validateTsPayloads(List<IkePayload> reqPayloads, List<IkePayload> respPayloads) throws TsUnacceptableException { for (int tsType : new int[] {PAYLOAD_TYPE_TS_INITIATOR, PAYLOAD_TYPE_TS_RESPONDER}) { IkeTsPayload reqPayload = IkePayload.getPayloadForTypeInProvidedList( tsType, IkeTsPayload.class, reqPayloads); IkeTsPayload respPayload = IkePayload.getPayloadForTypeInProvidedList( tsType, IkeTsPayload.class, respPayloads); if (!reqPayload.contains(respPayload)) { throw new TsUnacceptableException(); } } }
Source:
private boolean hasActualVideo() { if (mVideoTrackCount > 0) { return true; } VideoSize videoSize = mPlayer.getVideoSize(); if (videoSize.getHeight() > 0 && videoSize.getWidth() > 0) { Log.w(TAG, "video track count is zero, but it renders video. size: " + START videoSize.getWidth() + "/" + videoSize.getHeight()); END return true; } return false; } How about just videoSize?

Target:
private boolean hasActualVideo() { if (mVideoTrackCount > 0) { return true; } VideoSize videoSize = mPlayer.getVideoSize(); if (videoSize.getHeight() > 0 && videoSize.getWidth() > 0) { Log.w(TAG, "video track count is zero, but it renders video. size: " + videoSize); return true; } return false; }
Source:
public START CustomTabsSession newSession(@Nullable END final CustomTabsCallback callback) { return newSessionInternal(callback, null); } @Nullable?

Target:
public @Nullable CustomTabsSession newSession(@Nullable final CustomTabsCallback callback) { return newSessionInternal(callback, null); }
Source:
public NetworkStats getNetworkStatsDetail() { mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); try { return START mStatsFactory.readNetworkStatsDetail(UID_ALL, null, TAG_ALL); END } catch (IOException e) { throw new IllegalStateException(e); } } nit: can be replaced with readNetworkStatsDetail()

Target:
public NetworkStats getNetworkStatsDetail() { mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); try { return mStatsFactory.readNetworkStatsDetail(); } catch (IOException e) { throw new IllegalStateException(e); } }
Source:
void waitForLoadCompletion() { waitForCriteria(LOAD_TIMEOUT, START () -> { return isLoaded(); END }); clearLoad(); } simplify to () -> isLoaded()? Can it just be this::isLoaded? I'm not sure what the interchangeability of bound method references and lambdas is like.

Target:
void waitForLoadCompletion() { waitForCriteria(LOAD_TIMEOUT, () -> isLoaded()); clearLoad(); }
Source:
private ChildSessionStateMachine buildChildSession(ChildSessionOptions childOptions) { boolean isNatDetected = mIsLocalBehindNat || mIsRemoteBehindNat; ChildSessionStateMachine childSession = ChildSessionStateMachineFactory.makeChildSessionStateMachine( START "ChildSessionStateMachine", END getHandler().getLooper(), mContext, childOptions, new ChildSessionSmCallback(), mLocalAddress, mRemoteAddress, (isNatDetected ? mIkeSessionOptions.getUdpEncapsulationSocket() : null), mIkePrf, mCurrentIkeSaRecord.getSkD()); return childSession; } Do we need to pass this in if it's always the same?

Target:
private ChildSessionStateMachine buildChildSession(ChildSessionOptions childOptions) { boolean isNatDetected = mIsLocalBehindNat || mIsRemoteBehindNat; ChildSessionStateMachine childSession = ChildSessionStateMachineFactory.makeChildSessionStateMachine( getHandler().getLooper(), mContext, childOptions, new ChildSessionSmCallback(), mLocalAddress, mRemoteAddress, (isNatDetected ? mIkeSessionOptions.getUdpEncapsulationSocket() : null), mIkePrf, mCurrentIkeSaRecord.getSkD()); return childSession; }
Source:
protected String getLocalAddressString(SSLSocket socket) { START InetAddress addr END = socket.getLocalAddress(); return String.format( (addr instanceof Inet6Address ? "[%s]:%d" : "%s:%d"), addr.getHostAddress(), socket.getLocalPort()); } final

Target:
protected String getLocalAddressString(SSLSocket socket) { final InetAddress addr = socket.getLocalAddress(); return String.format( (addr instanceof Inet6Address ? "[%s]:%d" : "%s:%d"), addr.getHostAddress(), socket.getLocalPort()); }
Source:
private void prepareDnsTlsMeasurement(String hostname, InetAddress target) { // Since we iterate LinkProperties.getDnsServers() before PrivateDnsCfg.ips, if the entry // of |target| is found in the DnsTlsChecks map, then 1) the entry must have been created // when we iterated LinkProperties.getDnsServers() 2) we are iterating PrivateDnsCfg.ips // now. Thus, overwrite the entry in order to set SNI. START if (!mDnsTlsChecks.containsKey(target) END || !TextUtils.isEmpty(hostname)) { Measurement measurement = new Measurement(); measurement.thread = new Thread(new DnsTlsCheck(hostname, target, measurement)); mDnsTlsChecks.put(target, measurement); } } Style : we prefer to write our code in a return-fast style. if (mDnsTlsChecks.containsKey(target) && TextUtils.isEmpty(hostname)) return; Note that in this case it's much clearer with the reversed check that it's really a bizarre thing to test. You want to overwrite, except if the hostname is empty ? Why ?

Target:
private void prepareDnsTlsMeasurement(String hostname, InetAddress target) { // If |hostname| is not empty, |target| must be a private DNS server address resolved by // |hostname|. Allow to overwrite the entry in such case in order to carry SNI during SSL // handshake. if (mDnsTlsChecks.containsKey(target) && TextUtils.isEmpty(hostname)) return; Measurement measurement = new Measurement(); measurement.thread = new Thread(new DnsTlsCheck(hostname, target, measurement)); mDnsTlsChecks.put(target, measurement); }
Source:
public List<TrackInfo> getTrackInfo() { return START isConnected() ? getImpl().getTracks() : null; END } How about getTracks()?

Target:
public List<TrackInfo> getTrackInfo() { return getTracks(); }
Source:
public List<TrackInfo> getTracks() { return isConnected() ? getImpl().getTracks() : START null; END } I think we need to return empty list with @NonNull.

Target:
public List<TrackInfo> getTracks() { return isConnected() ? getImpl().getTracks() : new ArrayList<>(); }
Source:
private void loadPage(String data) { mWebViewOnUiThread.loadDataWithBaseURLAndWaitForCompletion( BASE_URI, data, "text/html", START "UTF-8", null); END } encoding must be null

Target:
private void loadPage(String data) { mWebViewOnUiThread.loadDataWithBaseURLAndWaitForCompletion( BASE_URI, data, "text/html", null, null); }