auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public List<TrackInfo> getTrackInfo() { return isConnected() ? getImpl().getTracks() : null; }

Target:
How about getTracks()?
Source:
public List<TrackInfo> getTracks() { return isConnected() ? getImpl().getTracks() : null; }

Target:
I think we need to return empty list with @NonNull.
Source:
private void loadPage(String data) { mWebViewOnUiThread.loadDataWithBaseURLAndWaitForCompletion( BASE_URI, data, "text/html", "UTF-8", null); }

Target:
encoding must be null
Source:
public static @NonNull JsReplyProxyImpl forInvocationHandler( @NonNull /* JsReplyProxy */ InvocationHandler invocationHandler) { final JsReplyProxyBoundaryInterface boundaryInterface = BoundaryInterfaceReflectionUtil.castToSuppLibClass( JsReplyProxyBoundaryInterface.class, invocationHandler); return (JsReplyProxyImpl) boundaryInterface.getOrCreatePeer( () -> new JsReplyProxyImpl(boundaryInterface)); }

Target:
nit: annotations usually go on the line above, like with @Override
Source:
public void testAssetLoaderInternalStorageActivity() { mRule.getActivity(); 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!"))); }

Target:
this is a noop, please delete
Source:
public ListenableFuture<Void> release() { try { checkNotReleased(); } catch (IllegalStateException e) { return Futures.immediateFailedFuture(e); } if (mState == State.OPEN) { close(); } mState = State.RELEASED; mObservableState.postValue(State.RELEASED); return Futures.immediateFuture(null); }

Target:
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.
Source:
public @Gutter int getGutter() { return mGutter; }

Target:
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.
Source:
DnsHeader(int id, int flags, int rcode, @NonNull int[] recordCount) { this.id = id; this.flags = flags; this.rcode = rcode; mRecordCount = recordCount; }

Target:
I think you can actually make this private. The compiler will generate a synthetic accessor that other classes have no (legal) way to call.
Source:
public void unregister() { enforceNetworkStackPermission(); if (DBG) log("Unregistering NetworkFactory"); if (mMessenger != null) { ConnectivityManager.from(mContext).unregisterNetworkFactory(mMessenger); mMessenger = null; } }

Target:
Let's use the new NETWORK_FACTORY permission that Paul is building in aosp/1099096
Source:
public int getSerialNumber() { enforceNetworkStackPermission(); return mSerialNumber; }

Target:
protected if possible
Source:
public void reevaluateAllRequests() { post(() -> { evalRequests(); }); }

Target:
I think this should stay protected. Non-subclasses have no business calling this.
Source:
public void dump(PrintWriter pw) { // dump is thread-safe on SharedLog mLog.dump(null, pw, null); // dump connectivity module connector logs. ConnectivityModuleConnector.getInstance().dump(pw); pw.println(); }

Target:
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
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(); assertEquals(a.getIconCompat().getResId(), aCopy.getIconCompat().getResId()); }

Target:
It would be clearer to use R.drawable.notification_action_background here too (it also guards against bugs like getResId always returning 0).
Source:
public int isMicMuted() { try { return mIm.isMicMuted(); } catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); } }

Target:
boolean
Source:
public void testLinkPropertiesWithWakeOnLanForActiveNetwork() throws Exception { mWiFiNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_WIFI); 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()); reset(mStatsService); }

Target:
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 ?
Source:
private void update(String key, int value) { mWorkDatabase.beginTransaction(); try { mWorkDatabase.preferenceDao().insertPreference(new Preference(key, value)); mWorkDatabase.setTransactionSuccessful(); } finally { mWorkDatabase.endTransaction(); } }

Target:
No need to make this a transaction, its a single insert statement.
Source:
public void setLastCancelAllTimeMillis(final long timeMillis) { mWorkDatabase.beginTransaction(); try { Preference preference = new Preference(KEY_LAST_CANCEL_ALL_TIME_MS, timeMillis); mWorkDatabase.preferenceDao().insertPreference(preference); mWorkDatabase.setTransactionSuccessful(); } finally { mWorkDatabase.endTransaction(); } }

Target:
Single statements don't need a transaction.
Source:
public void setNeedsReschedule(boolean needsReschedule) { mWorkDatabase.beginTransaction(); try { Preference preference = new Preference(KEY_RESCHEDULE_NEEDED, needsReschedule); mWorkDatabase.preferenceDao().insertPreference(preference); mWorkDatabase.setTransactionSuccessful(); } finally { mWorkDatabase.endTransaction(); } }

Target:
Same here, no need a transaction
Source:
public AdbQrcodeScannerFragment() { super(); mIntentFilter = new IntentFilter(AdbManager.WIRELESS_DEBUG_PAIRING_RESULT_ACTION); }

Target:
Can you initialize it in onCreate() ?
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( mContext.getDrawable(com.android.internal.R.drawable.ic_bt_laptop)); mEntityHeaderController.setLabel(mPairedDevice.getDeviceName()); mEntityHeaderController.done(mFragment.getActivity(), true); }

Target:
mEntityHeaderController .setIcon(xxxx) .setLabel(xxxx) .done(xxxx)
Source:
public int getAudioStreamType() { if (!mProto.hasAudioTrackIndex() && mProto.getAudioTrackIndex() == -1) { return INVALID_STREAMTYPE; } return mProto.getAudioStreamTypes(mProto.getAudioTrackIndex()).getNumber(); }

Target:
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.
Source:
static boolean isValidNlMsg(@NonNull ByteBuffer bytes) { return bytes.position() < bytes.limit() && bytes.remaining() >= StructNlMsgHdr.STRUCT_SIZE; }

Target:
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.
Source:
private void sendTcpPollingEvent() { if (isValidationRequired()) { sendMessageDelayed(EVENT_POLL_TCPINFO, getTcpPollingInterval()); } }

Target:
Do you want to consider the data stall of VPN?
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 > app.requestedPermissionsFlags.length) return false; return (app.requestedPermissionsFlags[index] & REQUESTED_PERMISSION_GRANTED) != 0; }

Target:
Shouldn't this be >= instead of > ? Otherwise if app.requestedPermissions.length == 4, index == 3, and app.requesterPermissionsFlags.length == 3, the code will crash.
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 mApps.containsKey(uid); }

Target:
This should be guarded. You may need to synchronized this
Source:
private static PackageInfo buildPackageInfo(boolean hasSystemPermission, int uid) { final PackageInfo packageInfo = new PackageInfo(); if (hasSystemPermission) { packageInfo.requestedPermissions = new String[] { CHANGE_NETWORK_STATE, NETWORK_STACK, 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; }

Target:
Remove NETWORK_STACK, since apps don't have it.
Source:
private void exitLocked() { final ConnectivityManager cm = ConnectivityManager.from(mContext); cm.unregisterNetworkCallback(mNetworkCallback); agentDisconnect(); resetIkeStateLocked(); mActiveNetwork = null; updateState(DetailedState.DISCONNECTED, "Platform VPN exit"); }

Target:
agentDisconnect also sets this state.
Source:
static Collection<RouteInfo> getRoutesFromTrafficSelectors( List<IkeTrafficSelector> trafficSelectors) { final HashSet<IpPrefix> prefixes = new HashSet<>(); 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; }

Target:
seems unused?
Source:
public void addAllIncludeFilters(Set<String> filters) { for (String filter : filters) { mIncludeFilters.add(filter); } }

Target:
nit: use 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; }}

Target:
Please separate them into two lines.
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); if (hasWifi()) { assertTrue(mWifiManager.isWifiEnabled()); } }

Target:
since no Wifi would omit the whole function, this if could be removed.
Source:
public void addOnSubscriptionsChangedListener(OnSubscriptionsChangedListener listener) { 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); } }

Target:
Avoid duplicate code. Just call addOnSubscriptionsChangedListener(listener, listener.mExecutor).
Source:
void clearNotification(@NotificationId final int id) { mNotificationManager.cancel(null /* tag */, id); }

Target:
Patchset 10 has this visible (and annotated), it's fine but contradicts your answer – is this what you intended ?
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. if (mWrapper.getTetheredIfaces().length != 0) { mWrapper.untetherAll(); } // TODO(b/148139325): send tetheringSupported on restriction change }

Target:
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.
Source:
private void updateNotification() { final boolean tetheringInactive = mDownstreamTypesMask <= DOWNSTREAM_NONE; synchronized (mUpdateLock) { if (mTetheringRestricted) { setupRestrictedNotification(); } else if (tetheringInactive) { clearNotification(); } else { if (setupNotification()) { return; } // Tethering is active but no need shows notification. clearNotification(); } } }

Target:
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?
Source:
public void setPriority(int priority) { int new_nice = NICE_VALUES[priority - 1]; Process.setThreadPriority(new_nice); }

Target:
Don't you need to check whether priority-1 is between 0 and NICE_VALUES.length - 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 Log.w("WebViewTestActivity", "Failed to dismiss keyguard"); } }

Target:
Perhaps add the exception as the third param?
Source:
public int getAvbPublicKey(AvbPublicKey dst) { try { return mService.getAvbPublicKey(dst); } catch (RemoteException e) { throw new RuntimeException(e.toString()); } }

Target:
I tend to use a boolean as the return value for consistency,
Source:
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; }

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

Target:
Suggest unindenting for clarity: if (!Objects.equals(mIfaceName, route.getInterface) { return false; } int i = ...; if (i == -1) { return false; } mRoutes.remove(i); return true;
Source:
private void cancelSurfaceCompleters() { for (Map.Entry<CallbackToFutureAdapter.Completer<Surface>, ListenableFuture<Void>> entry : mCompleterMap.entrySet()) { entry.getKey().setCancelled(); } }

Target:
Is it thread safe to access the mCompleterMap here?
Source:
public void onViewAttachedToWindow(@NonNull ViewHolder holder) { super.onViewAttachedToWindow(holder); mController.onViewAttachedToWindow(holder); }

Target:
Like, super.onFailedToRecycleView, this doesn't seem to do anything. Why call one super and not the other? Ditto for below?
Source:
private boolean autoConnectA2dp(BluetoothDevice 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; } }

Target:
return value looks unused?
Source:
public void setUp(String testOutputDir, String... processNames) { mProcessNames = processNames; mTestOutputDir = testOutputDir; mDropCacheOption = 0; mUiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); mGarbageCollectionHelper.setUp(processNames); }

Target:
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.
Source:
public void testGetNetworkSelectionMode() { if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) { return; } int networkMode = ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager, (tm) -> tm.getNetworkSelectionMode()); assertEquals(2, networkMode); }

Target:
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.
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 if (mLifecycleOwner != null) { 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; }

Target:
Why do we need to check mLifecycleOwner ? This seems unrelated to getAvailableCameraLensFacing.
Source:
private void setUsernamePasswordVisibility(int type) { if (requiresUsernamePassword(type)) { mView.findViewById(R.id.userpass).setVisibility(View.VISIBLE); } else { mView.findViewById(R.id.userpass).setVisibility(View.GONE); } }

Target:
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
Source:
public static boolean isFeatureEnabled(@NonNull Context context, @NonNull String namespace, @NonNull String name) { final int propertyVersion = getDeviceConfigPropertyInt(namespace, name, 0 /* default value */); return isFeatureVersionEnabled(context, propertyVersion); }

Target:
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.
Source:
private static boolean checkAndNoteChangeNetworkStateOperation(@NonNull Context context, int uid, @NonNull String callingPackage, @Nullable String callingAttributionTag, boolean throwException) { return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage, throwException); }

Target:
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.
Source:
boolean isAePrecaptureRequired(TakePictureState state) { if (isCamera2LegacyDevice()) { // 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()); }

Target:
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.
Source:
public static boolean isTestModeEnabled(Context context, Network network) { ConnectivityManager connectManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkCapabilities networkCapabilities = connectManager.getNetworkCapabilities(network); return networkCapabilities.hasCapability(NETWORK_CAPABILITY_TRANSPORT_TEST); }

Target:
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?
Source:
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); }

Target:
This could be simplified to: return networkCapabilities != null && networkCapabilities.hasCapability(...)
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))); assertEquals(request.canBeSatisfiedBy(new NetworkCapabilities()), TEST_CAPABILITIES.satisfiedByNetworkCapabilities(new NetworkCapabilities())); }

Target:
nit: Maybe it's better to test the case which the return value is true.
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/"; final String version = "general"; setKeyAndValidate(certificateFileNameKey, certificateFileNameNewValue, version); // Restoring original value and making sure it was restored successfully restoreOriginalValue(certificateFileNameKey, originalAuthenticationMethod); }

Target:
remove this local var . It is not needed realy. In the next line just write "general"
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); } return (returnString == null) ? null : returnString.toString(); }

Target:
Why not write: "return returnString" ?
Source:
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()); task.getaction_parameters(); addValue("action_parameters", serializeParameters(task.getaction_parameters())); addValue("action_params_class",task.getaction_parameters().getClass().getName()); }

Target:
there is a repetition on parameters field names, perhaps it is worth extracting those into constants?
Source:
private StorageDomainStatus getStorageDomainStatus() { StorageDomainStatus status = null; if (getStorageDomain() != null && getStorageDomain().getstatus() != null) { status = getStorageDomain().getstatus(); } return status; }

Target:
You don't need to use getStorageDomain().getstatus() != null condition
Source:
protected static <T> List<T> merge(List<T> list, List<T> items) { List<T> returnValue = list; if (list != null) { if (items != null) { for (T item : items) { if (!returnValue.contains(item)) { returnValue.add(item); } } } } else { returnValue = items; } return returnValue; }

Target:
This assignment is redundant.
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; } }

Target:
The message should be warnning level not error.
Source:
public VmBase() { mOs = VmOsType.Unassigned; }

Target:
You can also remove the initializing from the c'tor as it is being done on declaration statement: private VmOsType mOs = VmOsType.Unassigned;
Source:
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; }

Target:
why not use long and System current time?
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); steps.add(step); jobRepository.saveStep(step); jobRepository.updateJobLastUpdateTime(id, lastUpdateTime); return step; }

Target:
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.
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); } JobRepositoryFactory.getJobRepository().updateStep(step); } } catch (Exception e) { log.errorFormat("Failed to terminate step {0} with status {1}", stepId, exitStatus, e); } }

Target:
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.
Source:
private JobRepositoryCleanupManager() { succeededJobTime = Config.<Integer> GetValue(ConfigValues.SucceededJobCleanupTimeInMinutes).intValue() * -1; failedJobTime = Config.<Integer> GetValue(ConfigValues.FailedJobCleanupTimeInMinutes).intValue() * -1; Integer cleanupFrequency = Config.<Integer> GetValue(ConfigValues.JobCleanupRateInMinutes); SchedulerUtilQuartzImpl.getInstance().scheduleAFixedDelayJob(this, "completed_jobs_cleanup", new Class[] {}, new Object[] {}, cleanupFrequency, cleanupFrequency, TimeUnit.MINUTES); }

Target:
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
Source:
protected boolean canDoAction() { if (getParameters() != null) { if (!QuotaHelper.getInstance().checkQuotaValidationForAddEdit(getParameters().getQuota(), getReturnValue().getCanDoActionMessages())) { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__RUN.toString()); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM.toString()); return false; } } return true; }

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

Target:
so if its true: run vm!!! and what happens if this method fails?
Source:
protected void executeCommand() { QuotaDAO dao = DbFacade.getInstance().getQuotaDAO(); dao.remove(getParameters().getQuotaId()); }

Target:
make call inline DbFacade.getInstance().getQuotaDAO().remove()....
Source:
public String getinternal_drive_mapping() { int mapping = disk.getInternalDriveMapping(); return (mapping != 0) ? Integer.toString(mapping) : null; }

Target:
Why change to this?
Source:
protected DiskImage getDiskImage() { if (_diskImage == null) { DiskImage tmpImage = getImage(); _diskImage = (tmpImage == null || tmpImage.getVmEntityType() == VmEntityType.TEMPLATE)?(null):(tmpImage); } return _diskImage; }

Target:
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..
Source:
protected void executeCommand() { VmTemplateHandler.lockVmTemplateInTransaction(diskImage.getit_guid(), getCompensationContext()); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { VdcReturnValueBase retVal = Backend.getInstance().runInternalAction(VdcActionType .MoveOrCopyImageGroup, createMoveorCopyImageGroupParams()); handleResult(retVal); updateDatabase(); return null; } }); VmTemplateHandler.UnLockVmTemplate(diskImage.getit_guid()); }

Target:
You don't need a transaction here
Source:
protected void EndWithFailure() { // we are setting 'Vm' since VmId is overriden and 'Vm' is null // (since 'Vm' is dependant on 'mVmId', which is not set here). setVm(DbFacade.getInstance().getVmDAO().getById(getVmId())); // next line is for retrieving the VmPool (and Vm, implicitly) from // the DB so we won't get a log-deadlock because of the transaction. vm_pools vmPool = getVmPool(); setSucceeded(Backend.getInstance().endAction(VdcActionType.RunVm, getParameters().getImagesParameters().get(0), getCompensationContext()).getSucceeded()); if (!getSucceeded()) { log.warn("AttachUserToVmFromPoolAndRunCommand::EndWitFailure: EndAction of RunVm Failed"); } detachUserFromVmFromPool(); }

Target:
why endAction of RunVm will not be called automatically ?
Source:
protected static boolean CanAttachNonPrestartedVmToUser(Guid vm_guid) { java.util.ArrayList<String> messages = new java.util.ArrayList<String>(); return IsVmFree(vm_guid, messages); }

Target:
During rebase, just pass a new ArrayList() to IsVmfree no need for variable
Source:
public void testGetAllForTemplateWithPermissionsForUnprivilegedUser() { List<VmNetworkInterface> result = dao.getAllForTemplate(TEMPLATE_ID, UNPRIVILEGED_USER_ID, true); assertNotNull(result); assertTrue(result.size() == 0); }

Target:
Why not check isEmpty()?
Source:
private ReportInit() { AsyncDataProvider.GetRedirectServletReportsPage(new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { setReportBaseUrl((String) returnValue); } })); }

Target:
please move this tot he init() method
Source:
protected boolean canDoAction() { return (!QuotaHelper.getInstance().checkQuotaValidationForAddEdit(getParameters().getQuota(), getReturnValue().getCanDoActionMessages())); }

Target:
why you return not of the check? IIRC it will return true if quota is valid, and then you should return true for the CDA
Source:
public AddQuotaCommand(T parameters) { super(parameters); setStoragePoolId(parameters.getStoragePoolId()); }

Target:
the storage pool should be set from the quota object, i don't see a reason to send it separately, apply also for update and remove
Source:
protected boolean canDoAction() { if (getParameters() == null) { return false; } else if (!QuotaHelper.getInstance().checkQuotaValidationForAddEdit(getParameters().getQuota(), getReturnValue().getCanDoActionMessages())) { return false; } return true; }

Target:
i think this check is not needed, don't think the factory will create the command with null params, and if you decide to keep this check, you have to add error message.
Source:
public GetVmConfigurationBySnapshotQueryParams(Guid snapshotSourceId) { super(); this.snapshotSourceId = snapshotSourceId; }

Target:
ain't the super call redundant ?
Source:
protected void executeQueryCommand() { String configuration = getConfigurationFromDb(getParameters().getSnapshotSourceId()); VM result = new VM(); if (configuration != null) { new SnapshotsManager().updateVmFromConfiguration(result,configuration); } getQueryReturnValue().setReturnValue(result); }

Target:
looking at SnapshotsManager seems quite stateless, so perhaps worth "singletonize" it
Source:
private GetVmConfigurationBySnapshotQuery<GetVmConfigurationBySnapshotQueryParams> setupQueryBySnapshotId(Guid snapshotId) { GetVmConfigurationBySnapshotQueryParams queryParams = getQueryParameters(); when(queryParams.getSnapshotId()).thenReturn(snapshotId); GetVmConfigurationBySnapshotQuery<GetVmConfigurationBySnapshotQueryParams> executeQuery = getQuery(); return executeQuery; }

Target:
Why call executeQuery?
Source:
protected void removeVmRelatedEntitiesFromDb() { RemoveVmUsers(); RemoveVmNetwork(); new SnapshotsManager().removeSnapshots(getVmId()); // It is the responsibility of this command to erase the images , as it is also creates them removeVmImages(); RemoveVmStatic(); }

Target:
Why copy & paste instead of calling super.remove in the end (after images remove)?
Source:
public void setVmId(Guid value) { privateVmId = value; }

Target:
Why did you change to public?
Source:
protected VdcReturnValueBase checkAndPerformRollbackUsingCommand(VdcActionType commandType, VdcActionParametersBase params, CommandContext context) { VdcReturnValueBase result = new VdcReturnValueBase(); if (canPerformRollbackUsingCommand(commandType, params)) { result = runInternalCommandOnRollback(commandType, params, context); } else { result.setSucceeded(false); } return result; }

Target:
No need to instantiate a variable when a line under you might override it. Move the instantiate to the 'else' clause.
Source:
protected VdcReturnValueBase attemptRollback(VdcActionType commandType, VdcActionParametersBase params, CommandContext context) { if (canPerformRollbackUsingCommand(commandType, params)) { params.setExecutionReason(CommandExecutionReason.ROLLBACK_FLOW); return Backend.getInstance().runInternalAction(commandType, params); } return new VdcReturnValueBase(); }

Target:
Shouldn't you do something with the context?
Source:
public static ServicePolicyInterface getServicePolicyForVds(VDS vds) { ServicePolicyInterface retVal = null; Guid vdsGroupId = vds.getvds_group_id(); VDSGroup vdsGroup = vdsGroupDao.get(vdsGroupId); if (vdsGroup != null) { // In here we will test if the cluster is a gluster cluster, or a virt one, and create the policy accordingly retVal = virtServicePolicy; } return retVal; }

Target:
I don't think a Cluster can be removed while the Host is during monitor, therefore the cluster should be not Null.
Source:
public String getSpecParams() { this.specParams = VmDeviceCommonUtils.appendDeviceIdToSpecParams(this.getId().getDeviceId(), this.specParams); return this.specParams; }

Target:
"this." is redundant here .
Source:
private VmInfoBuilderBase createBuilder() { if (VmDeviceCommonUtils.isOldClusterVersion(vm.getvds_group_compatibility_version())) // backward compatibility for 3.0 return new VmOldInfoBuilder(vm, createInfo); else return new VmInfoBuilder(vm, createInfo); }

Target:
please wrap the if-else block with brackets {}.
Source:
private XmlRpcStruct[] getVmInfo(List<String> vmsToUpdate) { return (XmlRpcStruct[]) (new FullListVdsCommand<VdsIdAndVdsVDSCommandParametersBase>( new FullListVDSCommandParameters(_vds.getId(), vmsToUpdate)).ExecuteWithReturnValue()); }

Target:
you should wrap this call, since a specific failure will cause all of the refresh to fail.
Source:
public VM(VmStatic vmStatic, VmDynamic vmDynamic, VmStatistics vmStatistics) { mDiskMap = new java.util.HashMap<String, DiskImage>(); mCdPath = ""; mFloppyPath = ""; mRunAndPause = false; _diskSize = 0; mVmStatic = vmStatic; mVmDynamic = vmDynamic; mVmStatistics = vmStatistics; if (mVmStatic != null) { mVmStatic.setImages(new java.util.ArrayList<DiskImage>()); mVmStatic.setInterfaces(new java.util.ArrayList<VmNetworkInterface>()); } }

Target:
please omit the java.util. prefix. The ArrayList is already imported (from both lines)
Source:
protected void executeCommand() { updateDefaultQuota(); getStoragePoolDAO().updatePartial(getStoragePool()); if (getStoragePool().getstatus() == StoragePoolStatus.Up) { if (!StringHelper.EqOp(_oldStoragePool.getname(), getStoragePool().getname())) { runVdsCommand(VDSCommandType.SetStoragePoolDescription, new SetStoragePoolDescriptionVDSCommandParameters(getStoragePool().getId(), getStoragePool().getname())); } } updateStoragePoolFormatType(); setSucceeded(true); }

Target:
Perform update only at case of vdsm call successes, also use only one time updatePartia() . Also change updatePartial() , can also update storage pool format type
Source:
protected boolean isOsSupported(VM vm) { String[] oses = Config.<String> GetValue(ConfigValues.HotPlugSupportedOsList).split(","); for (String os : oses) { if (os.equalsIgnoreCase(vm.getguest_os())) { return true; } } addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GUEST_OS_VERSION_IS_NOT_SUPPORTED); return false; }

Target:
why not to have it static ? the list is not expected to change during run, so no need to parse it for each command.
Source:
public boolean canMoveToMaintenance(VDS vds) { // In this case, if all the services can move the VDS to maintenance then we return true boolean retVal = true; for ( MonitoringStrategy monitoringStrategy : strategies ) { retVal = retVal && monitoringStrategy.canMoveToMaintenance(vds); if (retVal) { break; } } return retVal; }

Target:
shouldn't braek if retVal is false? actually (and this is just my opinion) i think it would be easier to understand if you return false once one is false: for ( MonitoringStrategy monitoringStrategy : strategies ) { if (!monitoringStrategy.canMoveToMaintenance(vds)) return false; } return true;
Source:
public boolean isMonitoringNeeded(VDS vds) { // In this case, if one of the services needs monitoring then we return true boolean retVal = false; for ( MonitoringStrategy monitoringStrategy : strategies ) { retVal = retVal || monitoringStrategy.isMonitoringNeeded(vds); if (retVal) { break; } } return retVal; }

Target:
same opinion here :) (though break logic here seems correct)
Source:
protected DiskImage createImage() { final DiskImage diskImage = new DiskImage(); diskImage.setimage_group_id(Guid.NewGuid()); diskImage.setstorage_ids(new ArrayList<Guid>(Arrays.asList(new Guid()))); return diskImage; }

Target:
minor: This can be private method
Source:
protected VmDevice createDiskVmDevice(final DiskImage diskImage) { final VmDevice vmDevice = new VmDevice(); vmDevice.setIsPlugged(true); vmDevice.setId(new VmDeviceId(diskImage.getimage_group_id(), Guid.NewGuid())); return vmDevice; }

Target:
minor: This can be private method
Source:
private boolean checkVmIsDown() { return Config.<Boolean> GetValue( ConfigValues.LiveSnapshotEnabled, getStoragePool().getcompatibility_version().getValue()); }

Target:
shouldnt it return !(getConfig)?
Source:
public List<PermissionSubject> getPermissionCheckSubjects() { if (disk != null) { if (disk.getVmEntityType() == VmEntityType.VM) { return Collections.singletonList(new PermissionSubject(getParameters().getStorageDomainId(), VdcObjectType.Storage, ActionGroup.CONFIGURE_VM_STORAGE)); } if (disk.getVmEntityType() == VmEntityType.TEMPLATE) { return Collections.singletonList(new PermissionSubject(disk.getvm_guid(), VdcObjectType.VmTemplate, ActionGroup.DELETE_TEMPLATE)); } } return null; }

Target:
permission should be on vm and not storage
Source:
protected void executeQueryCommand() { String suggestedDiskName = null; if (getParameters().getVmId() == null) { getQueryReturnValue().setReturnValue(suggestedDiskName); } else { VM vm = DbFacade.getInstance().getVmDAO().getById(getParameters().getVmId()); suggestedDiskName = ImagesHandler.getDefaultDiskAlias(vm.getvm_name(), VmHandler.getCorrectDriveForDisk(vm)); } getQueryReturnValue().setReturnValue(suggestedDiskName); }

Target:
you need to check that vm != null as well.
Source:
protected boolean canDoAction() { if (getGlusterVolume().isOnline()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_ALREADY_STARTED); return false; } return super.canDoAction(); }

Target:
maybe add a check that getGlusterVolume exists (not null)
Source:
public StatusOnlyReturnForXmlRpc glusterVolumeStart(String volumeName, Boolean force) { try { return new StatusOnlyReturnForXmlRpc(vdsServer.glusterVolumeStart(volumeName, force.toString())); } catch (UndeclaredThrowableException ute) { throw new XmlRpcRunTimeException(ute); } }

Target:
I think the "force" variable should be passed to the vdsServer method as it is, instead of converting to string.
Source:
public StopGlusterVolumeCommand(GlusterVolumeActionParameters params) { super(params); setGlusterVolumeId(getParameters().getVolumeId()); }

Target:
i think that the gluster volume id is already set in the super constructor.
Source:
public void testRemove() { assertEquals(dao.remove(existingAsyncTask.gettask_id()), 1); async_tasks result = dao.get(existingAsyncTask.gettask_id()); assertNull(result); assertEquals(dao.remove(existingAsyncTask.gettask_id()), 0); }

Target:
consider testing with get()!=null too, so your test isn't completely dependent on remove()
Source:
public static Guid getGuidValue(NGuid id) { if (id == null) { return null; } return id.getValue(); }

Target:
you could do this in a single line
Source:
public List<PermissionSubject> getPermissionCheckSubjects() { if (listPermissionSubjects == null) { listPermissionSubjects = super.getPermissionCheckSubjects(); Guid diskId = _oldDisk == null ? null : _oldDisk.getimage_group_id(); listPermissionSubjects.add(new PermissionSubject(diskId, VdcObjectType.Disk, ActionGroup.EDIT_DISK_PROPERTIES)); listPermissionSubjects = QuotaHelper.getInstance().addQuotaPermissionSubject(listPermissionSubjects, getStoragePool(), getQuotaId()); } return listPermissionSubjects; }

Target:
should require permission on disk only, calling super will add requirement for vm as well
Source:
private Quota generateQuotaForNewStoragePool() { boolean isDefaultQuota = (getStoragePool().getQuotaEnforcementType() == QuotaEnforcementTypeEnum.DISABLED); Quota defaultStoragePoolQuota = getQuotaHelper().getUnlimitedQuota(getStoragePool(), isDefaultQuota); return defaultStoragePoolQuota; }

Target:
I think this boolean should be removed now, We should add a default quota every time we create a DC, and keep its flag all the time until someone edit it. So the creation of the quota should be all the time with defaultQuota = true
Source:
protected VMs mapCollection(List<org.ovirt.engine.core.common.businessentities.VM> entities) { VMs collection = new VMs(); for (org.ovirt.engine.core.common.businessentities.VM entity : entities) { VM vm = map(entity); collection.getVMs().add(addLinks(populate(vm, entity))); setPayload(vm); } return collection; }

Target:
Better to put the call 'setPayload(vm)' inside the method populate(). That's what this method is for - it adds any information you want to the collection objects after they have been mapped.
Source:
public static ArrayList<Guid> getStorageIdList(String storageIds) { ArrayList<String> storageStringList = splitStringList(storageIds); ArrayList<Guid> storageGuidsList = new ArrayList<Guid>(); if (!(storageStringList == null || storageStringList.isEmpty())) { for (String storageGuidString : storageStringList) { storageGuidsList.add(Guid.createGuidFromString(storageGuidString)); } } // If list is empty return empty guid. if (storageGuidsList.isEmpty()) { storageGuidsList.add(Guid.Empty); } return storageGuidsList; }

Target:
no need check for storageStringList.isEmpty()
Source:
public Guid getId() { return clusterId; }

Target:
Should'nt the getter name be getClusteId if the field name is clusterId?
Source:
public String toString() { return String.format("%s, ticket=%s, validTime=%s,m userName=%s, userId=%s", super.toString(), getTicket(), getValidTime(), getUserName(), getUserId().toString()); }

Target:
no need to explicit call toString on getUserId() here, this way its null safe
Source:
public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = super.getPermissionCheckSubjects(); if (getParameters().getInterface().isPromisc()) { permissionList.add(new PermissionSubject(getVm().getstorage_pool_id(), VdcObjectType.StoragePool, ActionGroup.PROMISC)); } return permissionList; }

Target:
same answer
Source:
private static void assertCorrectSnapshots(DiskImage disk) { for (int i = 0; i < NUM_DISKS_OF_EACH_KIND; ++i) { assertEquals("Wrong snapshot " + i + " for disk ", disk.getId(), disk.getSnapshots().get(i).getImageId()); } }

Target:
You compare disk id to image id, which is not the same thing.
Source:
protected boolean matchEntity(DiskImage entity, Guid id) { return id != null && (id.equals(entity.getId()) || id.equals(entity.getImageId()) || id.equals(entity.getvm_snapshot_id())); }

Target:
Now that the disk identifier is it's ID, I think it's better not to compare to imageId anymore
Source:
public boolean getTaskGroupSuccess() { boolean childrenTasksSuccess = taskGroupSuccess; for (VdcActionParametersBase childParameters : getImagesParameters()) { childrenTasksSuccess &= childParameters.getTaskGroupSuccess(); } return childrenTasksSuccess; }

Target:
you can break this loop once reached a failed childParameters.getTaskGroupSuccess()
Source:
private static void updateOption(VdcOption option) { Map<String, Object> values = _vdcOptionCache.get(option.getoption_name()); if (values != null) { values.put(option.getversion(), GetValue(option)); } else { values = new HashMap<String, Object>(); values.put(option.getversion(), GetValue(option)); _vdcOptionCache.put(option.getoption_name(), values); } }

Target:
I would consider rewriting as: if (values == null) { values = new HashMap<String, Object>(); _vdcOptionCache.put(option.getoption_name(), values); } values.put(option.getversion(), GetValue(option));
Source:
private static boolean isReloadable(String optionName) throws SecurityException, NoSuchFieldException { return ConfigValues.class.getField(optionName).isAnnotationPresent(Reloadable.class); }

Target:
Why specify SecurityException? It is unchekced..
Source:
protected VDSGroup lookupClusterById(String id) { GetVdsGroupByIdParameters params = new GetVdsGroupByIdParameters(Guid.createGuidFromString(id)); params.setFiltered(SessionUtils.isFiltered()); return getEntity(VDSGroup.class, VdcQueryType.GetVdsGroupById, params, id); }

Target:
why this is not in getEntity()? it would solve this in generic way...
Source:
public Roles list() { MultilevelAdministrationByAdElementIdParameters params = new MultilevelAdministrationByAdElementIdParameters(principalId); params.setFiltered(SessionUtils.isFiltered()); return mapCollection(getBackendCollection(VdcQueryType.GetPermissionsByAdElementId, params)); }

Target:
why this is not in getBackendCollection()? it would solve this in generic way...