auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static START @NonNull JsReplyProxyImpl END forInvocationHandler( @NonNull /* JsReplyProxy */ InvocationHandler invocationHandler) { final JsReplyProxyBoundaryInterface boundaryInterface = BoundaryInterfaceReflectionUtil.castToSuppLibClass( JsReplyProxyBoundaryInterface.class, invocationHandler); return (JsReplyProxyImpl) boundaryInterface.getOrCreatePeer( () -> new JsReplyProxyImpl(boundaryInterface)); } nit: annotations usually go on the line above, like with @Override

Target:
public static JsReplyProxyImpl forInvocationHandler( @NonNull /* JsReplyProxy */ InvocationHandler invocationHandler) { final JsReplyProxyBoundaryInterface boundaryInterface = BoundaryInterfaceReflectionUtil.castToSuppLibClass( JsReplyProxyBoundaryInterface.class, invocationHandler); return (JsReplyProxyImpl) boundaryInterface.getOrCreatePeer( () -> new JsReplyProxyImpl(boundaryInterface)); }
Source:
public void testAssetLoaderInternalStorageActivity() { START mRule.getActivity(); END mRule.openByActivityTitle(R.string.asset_loader_internal_storage_activity_title); onWebView() .withElement(findElement(Locator.TAG_NAME, "h3")) .check(webMatches(getText(), containsString("Successfully loaded html from app files dir!"))); } this is a noop, please delete

Target:
public void testAssetLoaderInternalStorageActivity() { mRule.openByActivityTitle(R.string.asset_loader_internal_storage_activity_title); onWebView() .withElement(findElement(Locator.TAG_NAME, "h3")) .check(webMatches(getText(), containsString("Successfully loaded html from app files dir!"))); }
Source:
public ListenableFuture<Void> release() { START try { checkNotReleased(); } catch (IllegalStateException e) { return Futures.immediateFailedFuture(e); } END if (mState == State.OPEN) { close(); } mState = State.RELEASED; mObservableState.postValue(State.RELEASED); return Futures.immediateFuture(null); } Actually I think we should just get rid of the checkNotReleased(). Calling release() multiple times should be allowed for Camera. If it is already released then it should return a successful future.

Target:
public ListenableFuture<Void> release() { if (mState == State.OPEN) { close(); } if (mState != State.RELEASED) { mState = State.RELEASED; mObservableState.postValue(State.RELEASED); } return Futures.immediateFuture(null); }
Source:
public START @Gutter int END getGutter() { return mGutter; } This should go above the method. Is the auto-formatter making it this way? If so, then it's fine, though it does make the code inconsistent.

Target:
public int getGutter() { return mGutter; }
Source:
START DnsHeader(int END id, int flags, int rcode, @NonNull int[] recordCount) { this.id = id; this.flags = flags; this.rcode = rcode; mRecordCount = recordCount; } I think you can actually make this private. The compiler will generate a synthetic accessor that other classes have no (legal) way to call.

Target:
private DnsHeader(int id, int flags, int rcode, @NonNull int[] recordCount) { this.id = id; this.flags = flags; this.rcode = rcode; mRecordCount = recordCount; }
Source:
public void unregister() { START enforceNetworkStackPermission(); END if (DBG) log("Unregistering NetworkFactory"); if (mMessenger != null) { ConnectivityManager.from(mContext).unregisterNetworkFactory(mMessenger); mMessenger = null; } } Let's use the new NETWORK_FACTORY permission that Paul is building in aosp/1099096

Target:
public void unregister() { if (DBG) log("Unregistering NetworkFactory"); if (mMessenger != null) { ConnectivityManager.from(mContext).unregisterNetworkFactory(mMessenger); mMessenger = null; } }
Source:
START public int END getSerialNumber() { enforceNetworkStackPermission(); return mSerialNumber; } protected if possible

Target:
public int getSerialNumber() { return mSerialNumber; }
Source:
START public void END reevaluateAllRequests() { post(() -> { evalRequests(); }); } I think this should stay protected. Non-subclasses have no business calling this.

Target:
protected void reevaluateAllRequests() { post(() -> { evalRequests(); }); }
Source:
public void dump(PrintWriter pw) { // dump is thread-safe on SharedLog mLog.dump(null, pw, null); // dump connectivity module connector logs. START ConnectivityModuleConnector.getInstance().dump(pw); END pw.println(); } NetworkStackClient alreay dump ConnectivityModuleConnector. Do we really need to dump it again? https://cs.corp.google.com/aosp-master/frameworks/base/services/net/java/android/net/NetworkStackClient.java?type=cs&q="ConnectivityModuleConnector.getInstance().dump"&sq=package:aosp-master&g=0&l=331

Target:
public void dump(PrintWriter pw) { // dump is thread-safe on SharedLog mLog.dump(null, pw, null); pw.println(); }
Source:
public void testNotificationActionBuilder_copiesIcon() { NotificationCompat.Action a = new NotificationCompat.Action.Builder( R.drawable.notification_action_background, "title", null).build(); NotificationCompat.Action aCopy = new NotificationCompat.Action.Builder(a).build(); START assertEquals(a.getIconCompat().getResId(), aCopy.getIconCompat().getResId()); END } It would be clearer to use R.drawable.notification_action_background here too (it also guards against bugs like getResId always returning 0).

Target:
public void testNotificationActionBuilder_copiesIcon() { NotificationCompat.Action a = new NotificationCompat.Action.Builder( R.drawable.notification_action_background, "title", null).build(); assertEquals(R.drawable.notification_action_background, a.getIconCompat().getResId()); NotificationCompat.Action aCopy = new NotificationCompat.Action.Builder(a).build(); assertEquals(R.drawable.notification_action_background, aCopy.getIconCompat().getResId()); }
Source:
public START int isMicMuted() END { try { return mIm.isMicMuted(); } catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); } } boolean

Target:
public boolean isMicMuted() { try { return mIm.isMicMuted(); } catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); } }
Source:
public void testLinkPropertiesWithWakeOnLanForActiveNetwork() throws Exception { mWiFiNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_WIFI); START LinkProperties wifiLp = new LinkProperties(); wifiLp.setInterfaceName(WIFI_WOL_IFNAME); wifiLp.setWakeOnLanEnabled(true); // Default network switch should update ifaces. mWiFiNetworkAgent.connect(false); mWiFiNetworkAgent.sendLinkProperties(wifiLp); waitForIdle(); assertEquals(wifiLp, mService.getActiveLinkProperties()); END reset(mStatsService); } Not sure how that tests your new code. updateLinkProperties() is supposed to manage the new property and to overwrite it. Shouldn't you instead make sure that a LP with the WIFI_WOL_IFNAME interface gets this new property set, and that one with some other interface name gets it cleared, regardless of what was sent through sendLinkProperties ?

Target:
public void testLinkPropertiesWithWakeOnLanForActiveNetwork() throws Exception { mWiFiNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_WIFI); LinkProperties wifiLp = new LinkProperties(); wifiLp.setInterfaceName(WIFI_WOL_IFNAME); wifiLp.setWakeOnLanEnabled(false); // Default network switch should update ifaces. mWiFiNetworkAgent.connect(false); mWiFiNetworkAgent.sendLinkProperties(wifiLp); waitForIdle(); // ConnectivityService should have changed the wakeOnLanEnabled to true wifiLp.setWakeOnLanEnabled(true); assertEquals(wifiLp, mService.getActiveLinkProperties()); }
Source:
private void update(String key, int value) { START mWorkDatabase.beginTransaction(); END try { mWorkDatabase.preferenceDao().insertPreference(new Preference(key, value)); mWorkDatabase.setTransactionSuccessful(); } finally { mWorkDatabase.endTransaction(); } } No need to make this a transaction, its a single insert statement.

Target:
private void update(String key, int value) { mWorkDatabase.preferenceDao().insertPreference(new Preference(key, value)); }
Source:
public void setLastCancelAllTimeMillis(final long timeMillis) { START mWorkDatabase.beginTransaction(); END try { Preference preference = new Preference(KEY_LAST_CANCEL_ALL_TIME_MS, timeMillis); mWorkDatabase.preferenceDao().insertPreference(preference); mWorkDatabase.setTransactionSuccessful(); } finally { mWorkDatabase.endTransaction(); } } Single statements don't need a transaction.

Target:
public void setLastCancelAllTimeMillis(final long timeMillis) { Preference preference = new Preference(KEY_LAST_CANCEL_ALL_TIME_MS, timeMillis); mWorkDatabase.preferenceDao().insertPreference(preference); }
Source:
public void setNeedsReschedule(boolean needsReschedule) { START mWorkDatabase.beginTransaction(); END try { Preference preference = new Preference(KEY_RESCHEDULE_NEEDED, needsReschedule); mWorkDatabase.preferenceDao().insertPreference(preference); mWorkDatabase.setTransactionSuccessful(); } finally { mWorkDatabase.endTransaction(); } } Same here, no need a transaction

Target:
public void setNeedsReschedule(boolean needsReschedule) { Preference preference = new Preference(KEY_RESCHEDULE_NEEDED, needsReschedule); mWorkDatabase.preferenceDao().insertPreference(preference); mWorkDatabase.setTransactionSuccessful(); }
Source:
public AdbQrcodeScannerFragment() { super(); START mIntentFilter = new IntentFilter(AdbManager.WIRELESS_DEBUG_PAIRING_RESULT_ACTION); END } Can you initialize it in onCreate() ?

Target:
public AdbQrcodeScannerFragment() { super(); }
Source:
private void setupEntityHeader(PreferenceScreen screen) { LayoutPreference headerPref = (LayoutPreference) screen.findPreference(KEY_HEADER); mEntityHeaderController = EntityHeaderController.newInstance( mFragment.getActivity(), mFragment, headerPref.findViewById(R.id.entity_header)); mEntityHeaderController.setIcon( START mContext.getDrawable(com.android.internal.R.drawable.ic_bt_laptop)); END mEntityHeaderController.setLabel(mPairedDevice.getDeviceName()); mEntityHeaderController.done(mFragment.getActivity(), true); } mEntityHeaderController .setIcon(xxxx) .setLabel(xxxx) .done(xxxx)

Target:
private void setupEntityHeader(PreferenceScreen screen) { LayoutPreference headerPref = (LayoutPreference) screen.findPreference(KEY_HEADER); mEntityHeaderController = EntityHeaderController.newInstance( mFragment.getActivity(), mFragment, headerPref.findViewById(R.id.entity_header)); mEntityHeaderController .setIcon(mContext.getDrawable(com.android.internal.R.drawable.ic_bt_laptop)) .setLabel(mPairedDevice.getDeviceName()) .done(mFragment.getActivity(), true); }
Source:
public int getAudioStreamType() { if START (!mProto.hasAudioTrackIndex() && END mProto.getAudioTrackIndex() == -1) { return INVALID_STREAMTYPE; } return mProto.getAudioStreamTypes(mProto.getAudioTrackIndex()).getNumber(); } I don't think this is the right fix. If we can show the "hasAudioTrackIndex" is incorrect. I need to file bug on against nanoproto My read is this if will never be true. I suspect a this is letting unset audioTrackIndex return the default value of 0. Why did you think "hasAudioTrackIndex" is wrong.

Target:
public int getAudioStreamType() { if (mProto.getAudioTrackIndex() == -1) { return INVALID_STREAMTYPE; } return mProto.getAudioStreamTypes(mProto.getAudioTrackIndex()).getNumber(); }
Source:
static boolean isValidNlMsg(@NonNull ByteBuffer bytes) { return START bytes.position() < bytes.limit() && bytes.remaining() >= StructNlMsgHdr.STRUCT_SIZE; END } This kind of tests for the same thing, because bytes.remaining is defined as bytes.limit() - bytes.position(). So assuming STRUCT_SIZE > 0, bytes.remaining() >= STRUCT_SIZE implies bytes.position() < bytes.limit(), making the first test useless.

Target:
static boolean isValidNlMsg(@NonNull ByteBuffer bytes) { return bytes.remaining() >= StructNlMsgHdr.STRUCT_SIZE; }
Source:
private void sendTcpPollingEvent() { if START (isValidationRequired()) { END sendMessageDelayed(EVENT_POLL_TCPINFO, getTcpPollingInterval()); } } Do you want to consider the data stall of VPN?

Target:
void sendTcpPollingEvent() { if (isValidationRequired()) { sendMessageDelayed(EVENT_POLL_TCPINFO, getTcpPollingInterval()); } }
Source:
boolean hasPermission(@NonNull final PackageInfo app, @NonNull final String permission) { if (app.requestedPermissions == null || app.requestedPermissionsFlags == null) { return false; } final int index = ArrayUtils.indexOf(app.requestedPermissions, permission); if (index < 0 || index START > app.requestedPermissionsFlags.length) END return false; return (app.requestedPermissionsFlags[index] & REQUESTED_PERMISSION_GRANTED) != 0; } Shouldn't this be >= instead of > ? Otherwise if app.requestedPermissions.length == 4, index == 3, and app.requesterPermissionsFlags.length == 3, the code will crash.

Target:
boolean hasPermission(@NonNull final PackageInfo app, @NonNull final String permission) { if (app.requestedPermissions == null || app.requestedPermissionsFlags == null) { return false; } final int index = ArrayUtils.indexOf(app.requestedPermissions, permission); if (index < 0 || index >= app.requestedPermissionsFlags.length) return false; return (app.requestedPermissionsFlags[index] & REQUESTED_PERMISSION_GRANTED) != 0; }
Source:
public boolean hasUseBackgroundNetworksPermission(int uid) { // mApps already checked both network and using restricted network permissions. If uid is in // the mApps list that means uid has one of permission at least. return START mApps.containsKey(uid); END } This should be guarded. You may need to synchronized this

Target:
public synchronized boolean hasUseBackgroundNetworksPermission(int uid) { // mApps already checked both network and using restricted network permissions. If uid is in // the mApps list that means uid has one of permission at least. return mApps.containsKey(uid); }
Source:
private static PackageInfo buildPackageInfo(boolean hasSystemPermission, int uid) { final PackageInfo packageInfo = new PackageInfo(); if (hasSystemPermission) { packageInfo.requestedPermissions = new String[] { START CHANGE_NETWORK_STATE, NETWORK_STACK, END CONNECTIVITY_USE_RESTRICTED_NETWORKS }; } else { packageInfo.requestedPermissions = new String[0]; } packageInfo.applicationInfo = new ApplicationInfo(); packageInfo.applicationInfo.privateFlags = 0; packageInfo.applicationInfo.uid = UserHandle.getUid(UserHandle.USER_SYSTEM, UserHandle.getAppId(uid)); return packageInfo; } Remove NETWORK_STACK, since apps don't have it.

Target:
private static PackageInfo buildPackageInfo(boolean hasSystemPermission, int uid) { final PackageInfo packageInfo = new PackageInfo(); if (hasSystemPermission) { packageInfo.requestedPermissions = new String[] { CHANGE_NETWORK_STATE, CONNECTIVITY_USE_RESTRICTED_NETWORKS }; } else { packageInfo.requestedPermissions = new String[0]; } packageInfo.applicationInfo = new ApplicationInfo(); packageInfo.applicationInfo.privateFlags = 0; packageInfo.applicationInfo.uid = UserHandle.getUid(UserHandle.USER_SYSTEM, UserHandle.getAppId(uid)); return packageInfo; }
Source:
private void exitLocked() { final ConnectivityManager cm = ConnectivityManager.from(mContext); cm.unregisterNetworkCallback(mNetworkCallback); agentDisconnect(); resetIkeStateLocked(); mActiveNetwork = null; START updateState(DetailedState.DISCONNECTED, "Platform VPN exit"); END } agentDisconnect also sets this state.

Target:
private void exitLocked() { final ConnectivityManager cm = ConnectivityManager.from(mContext); cm.unregisterNetworkCallback(mNetworkCallback); agentDisconnect(); resetIkeStateLocked(); mActiveNetwork = null; }
Source:
static Collection<RouteInfo> getRoutesFromTrafficSelectors( List<IkeTrafficSelector> trafficSelectors) { START final HashSet<IpPrefix> prefixes = new HashSet<>(); END final HashSet<RouteInfo> routes = new HashSet<>(); for (final IkeTrafficSelector selector : trafficSelectors) { for (final IpPrefix prefix : new IpRange(selector.startingAddress, selector.endingAddress).asIpPrefixes()) { routes.add(new RouteInfo(prefix, null)); } } return routes; } seems unused?

Target:
static Collection<RouteInfo> getRoutesFromTrafficSelectors( List<IkeTrafficSelector> trafficSelectors) { final HashSet<RouteInfo> routes = new HashSet<>(); for (final IkeTrafficSelector selector : trafficSelectors) { for (final IpPrefix prefix : new IpRange(selector.startingAddress, selector.endingAddress).asIpPrefixes()) { routes.add(new RouteInfo(prefix, null)); } } return routes; }
Source:
public void addAllIncludeFilters(Set<String> filters) { START for (String filter : filters) { mIncludeFilters.add(filter); } END } nit: use mIncludeFilters.addAll(filters)

Target:
public void addAllIncludeFilters(Set<String> filters) { mIncludeFilters.addAll(filters); }
Source:
Bundle toBundle() { Bundle bundle = new Bundle(); bundle.putString(KEY_SENDER_CONTACT_ID, senderContactId); bundle.putString(KEY_CONVERSATION_ID, conversId); bundle.putLong(KEY_TIMESTAMP, timestamp); bundle.putString(KEY_MESSAGE, message); bundle.putBundle(KEY_EXTRAS, bundle); return bundle; START }} END Please separate them into two lines.

Target:
Bundle toBundle() { Bundle bundle = new Bundle(); bundle.putString(KEY_SENDER_CONTACT_ID, senderContactId); bundle.putString(KEY_CONVERSATION_ID, conversId); bundle.putLong(KEY_TIMESTAMP, timestamp); bundle.putString(KEY_MESSAGE, message); bundle.putBundle(KEY_EXTRAS, bundle); return bundle; }
Source:
protected void setUp() throws Exception { super.setUp(); if(!hasWifi()) { return; } mWifiManager = (WifiManager) mContext .getSystemService(Context.WIFI_SERVICE); assertNotNull(mWifiManager); SystemUtil.runShellCommand("svc wifi enable"); Thread.sleep(ENABLE_DELAY); START if (hasWifi()) { END assertTrue(mWifiManager.isWifiEnabled()); } } since no Wifi would omit the whole function, this if could be removed.

Target:
protected void setUp() throws Exception { super.setUp(); if(!hasWifi()) { return; } mWifiManager = (WifiManager) mContext .getSystemService(Context.WIFI_SERVICE); assertNotNull(mWifiManager); SystemUtil.runShellCommand("svc wifi enable"); Thread.sleep(ENABLE_DELAY); assertTrue(mWifiManager.isWifiEnabled()); }
Source:
public void addOnSubscriptionsChangedListener(OnSubscriptionsChangedListener listener) { START if (listener == null) return; String pkgName = mContext != null ? mContext.getOpPackageName() : "<unknown>"; if (DBG) { logd("register OnSubscriptionsChangedListener pkgName=" + pkgName + " listener=" + listener); } // We use the TelephonyRegistry as it runs in the system and thus is always // available. Where as SubscriptionController could crash and not be available TelephonyRegistryManager telephonyRegistryManager = (TelephonyRegistryManager) mContext.getSystemService(Context.TELEPHONY_REGISTRY_SERVICE); if (telephonyRegistryManager != null) { telephonyRegistryManager.addOnSubscriptionsChangedListener(listener, listener.mExecutor); } END } Avoid duplicate code. Just call addOnSubscriptionsChangedListener(listener, listener.mExecutor).

Target:
public void addOnSubscriptionsChangedListener(OnSubscriptionsChangedListener listener) { if (listener == null) return; addOnSubscriptionsChangedListener(listener, listener.mExecutor); }
Source:
START void clearNotification(@NotificationId END final int id) { mNotificationManager.cancel(null /* tag */, id); } Patchset 10 has this visible (and annotated), it's fine but contradicts your answer – is this what you intended ?

Target:
private void clearNotification(@NotificationId final int id) { mNotificationManager.cancel(null /* tag */, id); }
Source:
public void onUserRestrictionsChanged() { // getUserRestrictions gets restriction for this process' user, which is the primary // user. This is fine because DISALLOW_CONFIG_TETHERING can only be set on the primary // user. See UserManager.DISALLOW_CONFIG_TETHERING. final Bundle restrictions = mUserManager.getUserRestrictions(); final boolean newlyDisallowed = restrictions.getBoolean(UserManager.DISALLOW_CONFIG_TETHERING); final boolean prevDisallowed = mDisallowTethering; mDisallowTethering = newlyDisallowed; final boolean tetheringDisallowedChanged = (newlyDisallowed != prevDisallowed); if (!tetheringDisallowedChanged) { return; } if (!newlyDisallowed) { // Clear the restricted notification when user is allowed to have tethering // function. mNotificationUpdater.tetheringRestrictionLifted(); return; } // Restricted notification is shown when tethering function is disallowed on // user's device. mNotificationUpdater.notifyTetheringDisabledByRestriction(); // Untether from all downstreams since tethering is disallowed. START if (mWrapper.getTetheredIfaces().length != 0) { END mWrapper.untetherAll(); } // TODO(b/148139325): send tetheringSupported on restriction change } This is reaching pretty deep into an implementation detail of the "wrapper". Isn't untetherAll() idempotent ? If it is, you can just call it always.

Target:
public void onUserRestrictionsChanged() { // getUserRestrictions gets restriction for this process' user, which is the primary // user. This is fine because DISALLOW_CONFIG_TETHERING can only be set on the primary // user. See UserManager.DISALLOW_CONFIG_TETHERING. final Bundle restrictions = mUserManager.getUserRestrictions(); final boolean newlyDisallowed = restrictions.getBoolean(UserManager.DISALLOW_CONFIG_TETHERING); final boolean prevDisallowed = mDisallowTethering; mDisallowTethering = newlyDisallowed; final boolean tetheringDisallowedChanged = (newlyDisallowed != prevDisallowed); if (!tetheringDisallowedChanged) { return; } if (!newlyDisallowed) { // Clear the restricted notification when user is allowed to have tethering // function. mNotificationUpdater.tetheringRestrictionLifted(); return; } // Restricted notification is shown when tethering function is disallowed on // user's device. mNotificationUpdater.notifyTetheringDisabledByRestriction(); // Untether from all downstreams since tethering is disallowed. mWrapper.untetherAll(); // TODO(b/148139325): send tetheringSupported on restriction change }
Source:
private void updateNotification() { final boolean tetheringInactive = mDownstreamTypesMask <= DOWNSTREAM_NONE; synchronized (mUpdateLock) { START if (mTetheringRestricted) { setupRestrictedNotification(); } else if (tetheringInactive) { END clearNotification(); } else { if (setupNotification()) { return; } // Tethering is active but no need shows notification. clearNotification(); } } } Is that possible that tethering inactive but tethering restricted is updated to restrict? If yes, the logic here may be not correct? Another question is that when tethering is inactive, should we still show notification? Is that wired that there is tethering restricted notification when I do not even enable tethering if I understand it correctly?

Target:
private void updateNotification() { synchronized (mUpdateLock) { final boolean tetheringInactive = mDownstreamTypesMask <= DOWNSTREAM_NONE; if (tetheringInactive) { clearNotification(); } else { if (setupNotification()) { return; } // Tethering is active but no need shows notification. clearNotification(); } } }
Source:
public void setPriority(int priority) { int new_nice = START NICE_VALUES[priority - 1]; END Process.setThreadPriority(new_nice); } Don't you need to check whether priority-1 is between 0 and NICE_VALUES.length - 1?

Target:
public void setPriority(int priority) { //priority should range from 1 to 10 if (priority < 1) { priority = 1; } else if (priority > 10) { priority = 10; } Process.setThreadPriority(NICE_VALUES[priority - 1]); }
Source:
private void dismissKeyguard() { final ResolvableFuture<Void> future = ResolvableFuture.create(); KeyguardManager keyguardManager = getSystemService(KeyguardManager.class); keyguardManager.requestDismissKeyguard(this, new KeyguardManager.KeyguardDismissCallback() { @Override public void onDismissSucceeded() { future.set(null); } }); try { future.get(500, TimeUnit.MILLISECONDS); } catch (ExecutionException | InterruptedException | TimeoutException e) { // If this fails, then either it's unimportant for the test, or the test will // fail later START Log.w("WebViewTestActivity", "Failed to dismiss keyguard"); END } } Perhaps add the exception as the third param?

Target:
private void dismissKeyguard() { final ResolvableFuture<Void> future = ResolvableFuture.create(); KeyguardManager keyguardManager = getSystemService(KeyguardManager.class); keyguardManager.requestDismissKeyguard(this, new KeyguardManager.KeyguardDismissCallback() { @Override public void onDismissSucceeded() { future.set(null); } }); try { future.get(500, TimeUnit.MILLISECONDS); } catch (ExecutionException | InterruptedException | TimeoutException e) { // If this fails, then either it's unimportant for the test, or the test will // fail later Log.w("WebViewTestActivity", "Failed to dismiss keyguard", e); } }
Source:
START public int getAvbPublicKey(AvbPublicKey dst) { END try { return mService.getAvbPublicKey(dst); } catch (RemoteException e) { throw new RuntimeException(e.toString()); } } I tend to use a boolean as the return value for consistency,

Target:
public boolean getAvbPublicKey(AvbPublicKey dst) { try { return mService.getAvbPublicKey(dst); } catch (RemoteException e) { throw new RuntimeException(e.toString()); } }
Source:
public boolean removeRoute(@NonNull RouteInfo route) { if START (Objects.equals(mIfaceName, END route.getInterface())) { return false; } int i = findRouteIndexByDestination(route); if (i == -1) { return false; } mRoutes.remove(i); return true; } !Objects.equals(

Target:
public boolean removeRoute(@NonNull RouteInfo route) { if (!Objects.equals(mIfaceName, route.getInterface())) { return false; } int i = findRouteIndexByDestination(route); if (i == -1) { return false; } mRoutes.remove(i); return true; }
Source:
public boolean removeRoute(@NonNull RouteInfo route) { START if (Objects.equals(mIfaceName, route.getInterface())) { END int i = findRouteIndexByDestination(route); if (i >= 0) { mRoutes.remove(i); return true; } } return false; } Suggest unindenting for clarity: if (!Objects.equals(mIfaceName, route.getInterface) { return false; } int i = ...; if (i == -1) { return false; } mRoutes.remove(i); return true;

Target:
public boolean removeRoute(@NonNull RouteInfo route) { if (Objects.equals(mIfaceName, route.getInterface())) { return false; } int i = findRouteIndexByDestination(route); if (i == -1) { return false; } mRoutes.remove(i); return true; }
Source:
private void cancelSurfaceCompleters() { START for (Map.Entry<CallbackToFutureAdapter.Completer<Surface>, ListenableFuture<Void>> entry END : mCompleterMap.entrySet()) { entry.getKey().setCancelled(); } } Is it thread safe to access the mCompleterMap here?

Target:
private synchronized void cancelSurfaceCompleters() { for (Map.Entry<CallbackToFutureAdapter.Completer<Surface>, ListenableFuture<Void>> entry : mCompleterMap.entrySet()) { entry.getKey().setCancelled(); } }
Source:
public void onViewAttachedToWindow(@NonNull ViewHolder holder) { START super.onViewAttachedToWindow(holder); END mController.onViewAttachedToWindow(holder); } Like, super.onFailedToRecycleView, this doesn't seem to do anything. Why call one super and not the other? Ditto for below?

Target:
public void onViewAttachedToWindow(@NonNull ViewHolder holder) { mController.onViewAttachedToWindow(holder); }
Source:
private START boolean autoConnectA2dp(BluetoothDevice END device) { final A2dpService a2dpService = mFactory.getA2dpService(); if (a2dpService == null) { warnLog("autoConnectA2dp: service is null, failed to connect to " + device); return false; } int a2dpConnectionPolicy = a2dpService.getConnectionPolicy(device); if (a2dpConnectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { debugLog("autoConnectA2dp: connecting A2DP with " + device); return a2dpService.connect(device); } else { debugLog("autoConnectA2dp: skipped auto-connect A2DP with device " + device + " connectionPolicy " + a2dpConnectionPolicy); return false; } } return value looks unused?

Target:
private void autoConnectA2dp(BluetoothDevice device) { final A2dpService a2dpService = mFactory.getA2dpService(); if (a2dpService == null) { warnLog("autoConnectA2dp: service is null, failed to connect to " + device); return; } int a2dpConnectionPolicy = a2dpService.getConnectionPolicy(device); if (a2dpConnectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { debugLog("autoConnectA2dp: connecting A2DP with " + device); a2dpService.connect(device); } else { debugLog("autoConnectA2dp: skipped auto-connect A2DP with device " + device + " connectionPolicy " + a2dpConnectionPolicy); } }
Source:
public void setUp(String testOutputDir, String... processNames) { mProcessNames = processNames; mTestOutputDir = testOutputDir; mDropCacheOption = 0; mUiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); START mGarbageCollectionHelper.setUp(processNames); END } In the current setup we are collecting rss for all the processes running in the system. In that case user supplied processNames will be null. We dynamically query all the available process using PS -A.Can you inititlaize initialize the garbage collection helper in getMetrics() method below where we query for all the available process names.

Target:
public void setUp(String testOutputDir, String... processNames) { mProcessNames = processNames; mTestOutputDir = testOutputDir; mDropCacheOption = 0; mUiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); }
Source:
public void testGetNetworkSelectionMode() { if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) { return; } int networkMode = START ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager, END (tm) -> tm.getNetworkSelectionMode()); assertEquals(2, networkMode); } We shouldn't need this in order to getNetworkSelectionMode(). I did check and I think we can safely give READ_PRECISE_PHONE_STATE to this package.

Target:
public void testGetNetworkSelectionMode() { if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) { return; } int networkMode = mTelephonyManager.getNetworkSelectionMode(); assertEquals(0, networkMode); }
Source:
private Set<Integer> getAvailableCameraLensFacing() { // Start with all camera directions Set<Integer> available = new LinkedHashSet<>(Arrays.asList(LensFacingConverter.values())); // If we're bound to a lifecycle, remove unavailable cameras START if (mLifecycleOwner != null) { END if (!hasCameraWithLensFacing(CameraSelector.LENS_FACING_BACK)) { available.remove(CameraSelector.LENS_FACING_BACK); } if (!hasCameraWithLensFacing(CameraSelector.LENS_FACING_FRONT)) { available.remove(CameraSelector.LENS_FACING_FRONT); } } return available; } Why do we need to check mLifecycleOwner ? This seems unrelated to getAvailableCameraLensFacing.

Target:
private Set<Integer> getAvailableCameraLensFacing() { // Start with all camera directions Set<Integer> available = new LinkedHashSet<>(Arrays.asList(LensFacingConverter.values())); if (!hasCameraWithLensFacing(CameraSelector.LENS_FACING_BACK)) { available.remove(CameraSelector.LENS_FACING_BACK); } if (!hasCameraWithLensFacing(CameraSelector.LENS_FACING_FRONT)) { available.remove(CameraSelector.LENS_FACING_FRONT); } return available; }
Source:
private void setUsernamePasswordVisibility(int type) { START if (requiresUsernamePassword(type)) { mView.findViewById(R.id.userpass).setVisibility(View.VISIBLE); } else { mView.findViewById(R.id.userpass).setVisibility(View.GONE); } END } Nit : suggest having a local visibility int like you're doing in other places, or a ternary to inline, so you don't duplicate this code

Target:
private void setUsernamePasswordVisibility(int type) { mView.findViewById(R.id.userpass).setVisibility( requiresUsernamePassword(type) ? View.VISIBLE : View.GONE); }
Source:
public static boolean isFeatureEnabled(@NonNull Context context, @NonNull String namespace, @NonNull String name) { START final int propertyVersion = getDeviceConfigPropertyInt(namespace, name, 0 /* default value */); return isFeatureVersionEnabled(context, propertyVersion); END } This could just be: return isFeatureEnabled(context, namespace, name, false); which makes it clearer that the 2 methods do the same thing with just a potential difference in the default.

Target:
public static boolean isFeatureEnabled(@NonNull Context context, @NonNull String namespace, @NonNull String name) { final int propertyVersion = getDeviceConfigPropertyInt(namespace, name, 0 /* default value */); return isFeatureEnabled(context, namespace, name, false); }
Source:
private static boolean checkAndNoteChangeNetworkStateOperation(@NonNull Context context, int uid, @NonNull String callingPackage, @Nullable String callingAttributionTag, boolean throwException) { START return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage, throwException); END } What happened to this code in Settings.checkAndNoteChangeNetworkStateOperation? if (context.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE) == PackageManager.PERMISSION_GRANTED) { return true; } An app with the CHANGE_NETWORK_STATE permission must be able to call requestNetwork without having WRITE_SETTINGS.

Target:
private static boolean checkAndNoteChangeNetworkStateOperation(@NonNull Context context, int uid, @NonNull String callingPackage, @Nullable String callingAttributionTag, boolean throwException) { return Settings.checkAndNoteChangeNetworkStateOperation(context, uid, callingPackage, throwException); }
Source:
boolean isAePrecaptureRequired(TakePictureState state) { START if (isCamera2LegacyDevice()) { END // AE Precapture is not supported on LEGACY devices. Capturing a high-resolution // JPEG image will automatically trigger a precapture sequence before the // high-resolution capture. return false; } switch (getFlashMode()) { case FLASH_MODE_ON: return true; case FLASH_MODE_AUTO: return state.mPreCaptureState.getAeState() == AeState.FLASH_REQUIRED; case FLASH_MODE_OFF: return false; } throw new AssertionError(getFlashMode()); } We should probably move this into a camera2 implementation, because we are leaking camera2 implementation details here. As a thought a ImagePrecapture interface which by default uses flash mode, but in the ImageCaptureProvider if the device is legacy it would provide an implementation that would just return saying that precapture is not needed.

Target:
boolean isAePrecaptureRequired(TakePictureState state) { switch (getFlashMode()) { case FLASH_MODE_ON: return true; case FLASH_MODE_AUTO: return state.mPreCaptureState.getAeState() == AeState.FLASH_REQUIRED; case FLASH_MODE_OFF: return false; } throw new AssertionError(getFlashMode()); }
Source:
public static boolean isTestModeEnabled(Context context, Network network) { ConnectivityManager connectManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkCapabilities START networkCapabilities = END connectManager.getNetworkCapabilities(network); return networkCapabilities.hasCapability(NETWORK_CAPABILITY_TRANSPORT_TEST); } Can this ever be null? If so, we'll end up throwing an exception here. Or maybe it doesn't matter since something else will crash eventually? eg binding a socket to network?

Target:
public static boolean isTestModeEnabled(Context context, Network network) { ConnectivityManager connectManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkCapabilities networkCapabilities = connectManager.getNetworkCapabilities(network); if (networkCapabilities == null) { // Invalid network. Caller should be responsible for handling this error return false; } return networkCapabilities.hasCapability(NETWORK_CAPABILITY_TRANSPORT_TEST); }
Source:
public static boolean isTestModeEnabled(Context context, Network network) { ConnectivityManager connectManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkCapabilities networkCapabilities = connectManager.getNetworkCapabilities(network); START if (networkCapabilities == null) { // Invalid network. Caller should be responsible for handling this error return false; } return networkCapabilities.hasCapability(NETWORK_CAPABILITY_TRANSPORT_TEST); END } This could be simplified to: return networkCapabilities != null && networkCapabilities.hasCapability(...)

Target:
public static boolean isTestModeEnabled(Context context, Network network) { ConnectivityManager connectManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkCapabilities networkCapabilities = connectManager.getNetworkCapabilities(network); return networkCapabilities != null && networkCapabilities.hasCapability(NETWORK_CAPABILITY_TRANSPORT_TEST); }
Source:
public void testCanBeSatisfiedBy() { final NetworkRequest request = new NetworkRequest.Builder() .setCapabilities(TEST_CAPABILITIES) .build(); assertFalse(request.canBeSatisfiedBy(null)); assertFalse(request.canBeSatisfiedBy(new NetworkCapabilities())); assertTrue(request.canBeSatisfiedBy(TEST_CAPABILITIES.addCapability(NET_CAPABILITY_MMS))); START assertEquals(request.canBeSatisfiedBy(new NetworkCapabilities()), TEST_CAPABILITIES.satisfiedByNetworkCapabilities(new NetworkCapabilities())); END } nit: Maybe it's better to test the case which the return value is true.

Target:
public void testCanBeSatisfiedBy() { final NetworkRequest request = new NetworkRequest.Builder() .setCapabilities(TEST_CAPABILITIES) .build(); assertFalse(request.canBeSatisfiedBy(null)); assertFalse(request.canBeSatisfiedBy(new NetworkCapabilities())); assertTrue(request.canBeSatisfiedBy(TEST_CAPABILITIES.addCapability(NET_CAPABILITY_MMS))); assertEquals(request.canBeSatisfiedBy(TEST_CAPABILITIES), TEST_CAPABILITIES.satisfiedByNetworkCapabilities(TEST_CAPABILITIES)); }
Source:
public void setStringValueFromFlag() throws Exception { final String certificateFileNameKey = "CertificateFileName"; // Backing up current CertificateFileName ConfigKey originalAuthenticationMethod = config.getEngineConfigLogic().fetchConfigKey(certificateFileNameKey, "general"); final String certificateFileNameNewValue = "/certs/"; START final String version = "general"; END setKeyAndValidate(certificateFileNameKey, certificateFileNameNewValue, version); // Restoring original value and making sure it was restored successfully restoreOriginalValue(certificateFileNameKey, originalAuthenticationMethod); } remove this local var . It is not needed realy. In the next line just write "general"

Target:
public void setStringValueFromFlag() throws Exception { final String certificateFileNameKey = "CertificateFileName"; // Backing up current CertificateFileName ConfigKey originalAuthenticationMethod = config.getEngineConfigLogic().fetchConfigKey(certificateFileNameKey, "general"); final String certificateFileNameNewValue = "/certs/"; setKeyAndValidate(certificateFileNameKey, certificateFileNameNewValue, "general"); // Restoring original value and making sure it was restored successfully restoreOriginalValue(certificateFileNameKey, originalAuthenticationMethod); }
Source:
private String readAllLines(BufferedReader bufferedReader) { String tempString; String returnString = null; try { while ((tempString = bufferedReader.readLine()) != null) { returnString += tempString + '\n'; } } catch (IOException e) { log.error("IOException while trying to read from buffer", e); } START return (returnString == null) ? null : returnString.toString(); END } Why not write: "return returnString" ?

Target:
private String readAllLines(BufferedReader bufferedReader) { String tempString; StringBuilder returnString = new StringBuilder(); try { while ((tempString = bufferedReader.readLine()) != null) { returnString.append(tempString).append('\n'); } } catch (IOException e) { log.error("IOException while trying to read from buffer", e); } return returnString.toString(); }
Source:
public AsyncTaskParameterSource(DbEngineDialect dialect,async_tasks task) { START super(dialect); END addValue("action_type", task.getaction_type()); addValue("result", task.getresult()); addValue("status", task.getstatus()); addValue("task_id", task.gettask_id()); task.getaction_parameters(); addValue("action_parameters", serializeParameters(task.getaction_parameters())); addValue("action_params_class",task.getaction_parameters().getClass().getName()); } there is a repetition on parameters field names, perhaps it is worth extracting those into constants?

Target:
public AsyncTaskParameterSource(DbEngineDialect dialect,async_tasks task) { super(dialect); addValue("action_type", task.getaction_type()); addValue("result", task.getresult()); addValue("status", task.getstatus()); addValue("task_id", task.gettask_id()); addValue("action_parameters", serializeParameters(task.getaction_parameters())); addValue("action_params_class",task.getaction_parameters().getClass().getName()); }
Source:
private StorageDomainStatus getStorageDomainStatus() { START StorageDomainStatus status = null; END if (getStorageDomain() != null && getStorageDomain().getstatus() != null) { status = getStorageDomain().getstatus(); } return status; } You don't need to use getStorageDomain().getstatus() != null condition

Target:
private StorageDomainStatus getStorageDomainStatus() { StorageDomainStatus status = null; if (getStorageDomain() != null) { status = getStorageDomain().getstatus(); } return status; }
Source:
protected static <T> List<T> merge(List<T> list, List<T> items) { START List<T> returnValue = list; END if (list != null) { if (items != null) { for (T item : items) { if (!returnValue.contains(item)) { returnValue.add(item); } } } } else { returnValue = items; } return returnValue; } This assignment is redundant.

Target:
protected static <T> List<T> merge(List<T> list, List<T> items) { if (list != null) { if (items != null) { for (T item : items) { if (!list.contains(item)) { list.add(item); } } } } else { return items; } return list; }
Source:
public static void execute(Runnable command) { try { es.submit(new InternalWrapperRunnable(command, ThreadLocalParamsContainer.getVdcUser(), ThreadLocalParamsContainer.getHttpSessionId())); } catch (RejectedExecutionException e) { log.error("The thread pool is out of limit. A submitted task was rejected"); throw e; START } END } The message should be warnning level not error.

Target:
public static void execute(Runnable command) { try { es.submit(new InternalWrapperRunnable(command, ThreadLocalParamsContainer.getVdcUser(), ThreadLocalParamsContainer.getHttpSessionId())); } catch (RejectedExecutionException e) { log.warn("The thread pool is out of limit. A submitted task was rejected"); throw e; } }
Source:
public VmBase() { START mOs = VmOsType.Unassigned; END } You can also remove the initializing from the c'tor as it is being done on declaration statement: private VmOsType mOs = VmOsType.Unassigned;

Target:
public VmBase() { }
Source:
public Step addStep(Step step) { START lastUpdateTime = new Date(); END step.setJobId(id); step.setStepNumber(steps.size()); // TODO: populate step name by bundle if (step.getDescription() == null) { step.setDescription(step.getStepName()); } step.setCorrelationId(correlationId); steps.add(step); return step; } why not use long and System current time?

Target:
public Step addStep(Step step) { lastUpdateTime = new Date(); step.setJobId(id); step.setStepNumber(steps.size()); step.setCorrelationId(correlationId); steps.add(step); return step; }
Source:
public Step addStep(Step step) { lastUpdateTime = new Date(); step.setJobId(id); step.setStepNumber(steps.size()); step.setJobRepository(jobRepository); // TODO: populate step name by bundle if (step.getDescription() == null) { step.setDescription(step.getStepName()); } step.setCorrelationId(correlationId); START END steps.add(step); jobRepository.saveStep(step); jobRepository.updateJobLastUpdateTime(id, lastUpdateTime); return step; } The following three lines of code causes for three updates on DB. First of all it is not clear, but second you open a 2 transaction, but updates are related, as I understand they should be committed together.

Target:
public Step addStep(Step step) { lastUpdateTime = new Date(); step.setJobId(id); step.setStepNumber(steps.size()); // TODO: populate step name by bundle if (step.getDescription() == null) { step.setDescription(step.getStepName()); } step.setCorrelationId(correlationId); steps.add(step); return step; }
Source:
public static void endTaskStep(NGuid stepId, ExecutionStatus exitStatus) { try { if (stepId != null) { Step step = JobRepositoryFactory.getJobRepository().getStep(stepId.getValue()); if (step != null) { step.markStepEnded(exitStatus); } START JobRepositoryFactory.getJobRepository().updateStep(step); END } } catch (Exception e) { log.errorFormat("Failed to terminate step {0} with status {1}", stepId, exitStatus, e); } } Maybe its better to also put this code line as part of the condition scope above (step != null) Also adding error logs when getting null values, for stepId or step entity, could be much helpful.

Target:
public static void endTaskStep(NGuid stepId, ExecutionStatus exitStatus) { try { if (stepId != null) { Step step = JobRepositoryFactory.getJobRepository().getStep(stepId.getValue()); if (step != null) { step.markStepEnded(exitStatus); JobRepositoryFactory.getJobRepository().updateStep(step); } } } catch (Exception e) { log.errorFormat("Failed to terminate step {0} with status {1}", stepId, exitStatus, e); } }
Source:
private JobRepositoryCleanupManager() { succeededJobTime = Config.<Integer> GetValue(ConfigValues.SucceededJobCleanupTimeInMinutes).intValue() * -1; failedJobTime = Config.<Integer> GetValue(ConfigValues.FailedJobCleanupTimeInMinutes).intValue() * -1; START Integer cleanupFrequency = Config.<Integer> GetValue(ConfigValues.JobCleanupRateInMinutes); END SchedulerUtilQuartzImpl.getInstance().scheduleAFixedDelayJob(this, "completed_jobs_cleanup", new Class[] {}, new Object[] {}, cleanupFrequency, cleanupFrequency, TimeUnit.MINUTES); } also we have this in a lot places, but it is ugly, the class still is not initialized, but we passed it to some other place

Target:
private JobRepositoryCleanupManager() { }
Source:
protected boolean canDoAction() { if (getParameters() != null) { if (!QuotaHelper.getInstance().checkQuotaValidationForAddEdit(getParameters().getQuota(), getReturnValue().getCanDoActionMessages())) { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__RUN.toString()); START addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM.toString()); END return false; } } return true; } run vm?

Target:
protected boolean canDoAction() { if (getParameters() == null) { return false; } else if (!QuotaHelper.getInstance().checkQuotaValidationForAddEdit(getParameters().getQuota(), getReturnValue().getCanDoActionMessages())) { return false; } return true; }
Source:
protected boolean canDoAction() { if (getParameters() != null) { if (QuotaHelper.getInstance().checkQuotaValidationForAddEdit(getParameters().getQuota(), getReturnValue().getCanDoActionMessages())) { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__RUN.toString()); START addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM.toString()); END } } return true; } so if its true: run vm!!! and what happens if this method fails?

Target:
protected boolean canDoAction() { if (getParameters() == null) { return false; } else if (!QuotaHelper.getInstance().checkQuotaValidationForAddEdit(getParameters().getQuota(), getReturnValue().getCanDoActionMessages())) { return false; } return true; }
Source:
START protected void executeCommand() { END QuotaDAO dao = DbFacade.getInstance().getQuotaDAO(); dao.remove(getParameters().getQuotaId()); } make call inline DbFacade.getInstance().getQuotaDAO().remove()....

Target:
protected void executeCommand() { getQuotaDAO().remove(getParameters().getQuotaId()); }
Source:
public String getinternal_drive_mapping() { int mapping = disk.getInternalDriveMapping(); START return (mapping != 0) ? Integer.toString(mapping) : null; END } Why change to this?

Target:
public String getinternal_drive_mapping() { return Integer.toString(disk.getInternalDriveMapping()); }
Source:
protected DiskImage getDiskImage() { if (_diskImage == null) { DiskImage tmpImage = getImage(); START _diskImage = (tmpImage == null || tmpImage.getVmEntityType() == VmEntityType.TEMPLATE)?(null):(tmpImage); END } return _diskImage; } I'm not sure this logic is correct, since DiskImage is linked to template either way and is in fact a DiskImage instance. Either way, since you don't use IImage anymore then this call should probably be removed and the duplicate field (_diskImage) with it..

Target:
protected DiskImage getDiskImage() { if (_diskImage == null) { _diskImage = getImage(); } return _diskImage; }