auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean isAdAggregatorIdValid(Bond bond, HostInterfaceLineModel lineModel) { String bondAdAggregatorId = Objects.toString(bond.getAdAggregatorId(), ""); for (HostInterface nic : lineModel.getInterfaces()) { String nicAggregatorId = Objects.toString(nic.getInterface().getAdAggregatorId(), ""); if (!bondAdAggregatorId.equals(nicAggregatorId)) { return false; } } return true; }

Target:
I do not understand why the empty string, instead of "null" or null, is required here, but never mind.
Source:
public Cluster() { migrateOnError = MigrateOnErrorOptions.YES; name = ""; virtService = true; optimizationType = OptimizationType.NONE; additionalRngSources = new HashSet<>(); fencingPolicy = new FencingPolicy(); addtionalFeaturesSupported = new HashSet<>(); ksmMergeAcrossNumaNodes = true; migrationBandwidthLimitType = MigrationBandwidthLimitType.DEFAULT; requiredSwitchTypeForCluster = SwitchType.LEGACY; logMaxMemoryUsedThresholdType = LogMaxMemoryUsedThresholdType.PERCENTAGE; description = ""; comment = ""; cpuName = ""; vncEncryptionEnabled = true; maintenanceReasonRequired = true; optionalReasonRequired = true; }

Target:
Can't we remove above variable completely?
Source:
public static BackupPhase map(org.ovirt.engine.core.common.businessentities.VmBackupPhase action) { switch (action) { case Initializing: return BackupPhase.INITIALIZING; case Starting: return BackupPhase.STARTING; case Ready: return BackupPhase.READY; case Finalizing: return BackupPhase.FINALIZING; default: return null; } }

Target:
please make this upper case
Source:
public ClusterValidator( ClusterDao clusterDao, StoragePoolDao dataCenterDao, Cluster cluster, CpuFlagsManagerHandler cpuFlagsManagerHandler) { this(clusterDao, dataCenterDao, cluster, cpuFlagsManagerHandler, null, null, null, null, null, null); }

Target:
can we inject the dao's into this class, this does not look nice, so many nulls
Source:
private ValidationResult validateWithHostSetupNetworksValidator(VDS host) { NetworkAttachment networkAttachment = selectNetworkAttachmentForValidatation(); HostSetupNetworksValidator validator = new HostSetupNetworksValidator(host, getParameters(), getExistingNics(), getExistingAttachments(), networkAttachment, getNetworkBusinessEntityMap(), networkClusterDao, networkDao, vdsDao, findActiveVmsUsingNetwork, hostSetupNetworksValidatorHelper, networkExclusivenessValidatorResolver, networkAttachmentIpConfigurationValidator, unmanagedNetworkValidator, backend); return validator.validate(); }

Target:
the variable is not required
Source:
public static boolean areSameId(NetworkAttachment a, NetworkAttachment b) { return a != null && b != null && a.getId() != null && a.getId().equals(b.getId()); }

Target:
private
Source:
static boolean areSameId(NetworkAttachment a, NetworkAttachment b) { return a != null && b != null && a.getId() != null && a.getId().equals(b.getId()); }

Target:
Why not private?
Source:
public BackendClusterNetworkResource(String id, BackendClusterNetworksResource parent) { super(id, parent, ActionType.DetachNetworkToCluster); clusterId = ((BackendClusterNetworksResource)parent).clusterId; }

Target:
Why is this cast needed? I see it's casting to same type.
Source:
private static String prependZeroes(String twoBytes) { StringBuilder builder = new StringBuilder(); int zeroLen = 4 - twoBytes.length(); for (int i = 0; i < zeroLen; i++) { builder.append(ZERO_STRING); } builder.append(twoBytes); return builder.toString(); }

Target:
why static?
Source:
private void adjustKVMDataForBlockSD() { // This is a workaround until bz 1332019 will be merged // since KVM is currently the only source for which we use Libvirt streaming API. // Libvirt currently reports the actual disk size and the virtual one, // when using preallocated qcow2 on block domain the size that the Libvirt stream emits // can be larger then the actual size. // Separately, setting the Volume Type to Preallocated avoids Sparseness when the // Destination is a Block SD if (getVm().getOrigin() == OriginType.KVM && getActionState() == CommandActionState.EXECUTE && getStorageDomain() != null && getStorageDomain().getStorageType().isBlockDomain()) { getVm().getImages().forEach(image -> image.setActualSizeInBytes(image.getSize())); getVm().getImages().forEach(image -> image.setVolumeType(VolumeType.Preallocated)); } }

Target:
since it's the same forEach, why don't you call both function at the same time?
Source:
protected boolean checkIfCpusSameManufacture(Cluster group) { if (!cpuFlagsManagerHandler.checkIfCpusExist(group.getCpuName(), getParameters().getCluster().getCompatibilityVersion())) { return true; } return cpuFlagsManagerHandler.checkIfCpusSameManufacture(group.getCpuName(), getCluster().getCpuName(), getCluster().getCompatibilityVersion()); }

Target:
shouldn't it check the getCluster().getCpuName() too?
Source:
protected void updateOSValue(final Integer selectedOsId) { Cluster cluster = getModel().getSelectedCluster(); if (cluster != null) { List<Integer> vmOsValues = AsyncDataProvider.getInstance().getOsIds(cluster.getArchitecture()); if (selectedOsId == null || !vmOsValues.contains(selectedOsId)) { updateOSValues(); return; } getModel().getOSType().setSelectedItem(selectedOsId); } }

Target:
Please, change this statement to the early return form. That's the standard we use throughout the code. That's the only objection I have currently. If you fix it now, I'll be able to merge the code before branching 4.3.
Source:
private void addMaintenanceFailedReason(List<String> failedMessages) { Guid rootCommandGuid = commandsRepository.getCommandEntity(getCommandId()).getRootCommandId(); CommandBase<T> rootCommand = commandCoordinatorUtil.retrieveCommand(rootCommandGuid); String messageToDisplay = failedMessages.get(0); rootCommand.addCustomValue("Message", messageToDisplay); auditLogDirector.log(rootCommand, AuditLogType.VDS_MAINTENANCE_FAILED_REASON, messageToDisplay); }

Target:
Why not do something similar to MigrateVmCommand private void addMaintenanceFailedReason() { addCustomValue("Message",backend.getErrorsTranslator().translateErrorText(getReturnValue().getValidationMessages())); auditLogDirector.log(this,AuditLogType.VDS_MAINTENANCE_FAILED_REASON); }
Source:
public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> hostSubjects = vdsIds.stream() .map(vdsId -> new PermissionSubject(vdsId, VdcObjectType.VDS, getActionType().getActionGroup())) .collect(Collectors.toList()); hostSubjects.add(new PermissionSubject(getClusterId(), VdcObjectType.Cluster, ActionGroup.CONFIGURE_HOST_NETWORK)); return hostSubjects; }

Target:
Is this backward compatible?
Source:
private boolean isConsoleEnabled() { boolean isConsoleEnabled; if (getParameters().isConsoleEnabled() != null) { isConsoleEnabled = getParameters().isConsoleEnabled(); } else { isConsoleEnabled = getVmDeviceUtils().hasConsoleDevice(getVmId()); } return isConsoleEnabled; }

Target:
You can simply return here, the variable is not needed.
Source:
protected void executeQueryCommand() { VM vm = getVm(); if (vm == null) { return; } VM nextRunVm = vmHandler.getNextRunVmConfiguration(getParameters().getId(), getUserID(), getParameters().isFiltered()); if (nextRunVm != null) { vm.setCustomCompatibilityVersion(nextRunVm.getCustomCompatibilityVersion()); } updateVMDetails(vm); getQueryReturnValue().setReturnValue(vm); }

Target:
customCompatibilityVersion is the only thing we use here from the whole NEXT_RUN configuration. Now VmHandler#getNextRunVmConfiguration() will load disks, network interfaces etc. Maybe pass an additional parameter that will flag not to load all this information?
Source:
public PersistentHostSetupNetworksParameters(Guid hostId) { super(hostId); }

Target:
Do you consider this(hostId, 1, 1); nicer here?
Source:
public void testGetAllOfTypeWithUnrepresentedType() { List<VDS> result = dao.getAllOfType(VDSType.forValue(-1)); assertIncorrectGetResult(result); }

Target:
Sorry, null would be better: List<VDS> result = dao.getAllOfType(null);
Source:
public AuditLogType getAuditLogTypeValue() { if (EXECUTE.equals(getActionState()) && getSucceeded()){ return outOfSyncHostsExist() ? CLUSTER_SYNC_ALL_NETWORKS_STARTED : CLUSTER_SYNC_NOTHING_TO_DO; } else if (EXECUTE.equals(getActionState()) && !getSucceeded()) { return CLUSTER_SYNC_ALL_NETWORKS_START_ERROR; } else if (END_SUCCESS.equals(getActionState())) { return CLUSTER_SYNC_ALL_NETWORKS_FINISHED; } return CLUSTER_SYNC_ALL_NETWORKS_FAILED; }

Target:
I think now it is more easy to read if we would use the common code structure like: switch (getActionState()) { case EXECUTE: return getSucceeded() ? ...
Source:
private void setParentOverflow(Element e, Style.Overflow visible) { if (e != null && e != asWidget().getElement()) { e.getParentElement().getStyle().setOverflow(visible); setParentOverflow(e.getParentElement(), visible); } }

Target:
Is it safe to do such a reference comparison instead of i.e., "equals" or using their IDs?
Source:
private boolean architecturesMatch() { return getCluster().getArchitecture() != ArchitectureType.undefined && getCluster().getArchitecture() == getMaxServerCpu().getArchitecture(); }

Target:
Previously, this condition was: getCluster().getArchitecture() == ArchitectureType.undefined || getCluster().getArchitecture() == getMaxServerCpu().getArchitecture()
Source:
public synchronized Map<Guid, AsyncTaskStatus> pollTasks(Set<Guid> taskIds) { if (taskIds == null) { return Collections.emptyMap(); } return taskIds.stream().collect(Collectors.toMap(Function.identity(), this::getTaskStatus)); }

Target:
is this needed?
Source:
public VmTemplate getVmTemplate() { if (vmTemplateFromConfiguration == null) { initUnregisteredTemplate(); } return vmTemplateFromConfiguration; }

Target:
This is called in the init method. Why is it needed again here?
Source:
public boolean isUnregisteredTemplate() { Template unregisteredTemplate; try { unregisteredTemplate = performGet(QueryType.GetUnregisteredVmTemplate, new GetUnregisteredEntityQueryParameters(parent.storageDomainId, guid)); } catch (WebApplicationException e) { if (e.getResponse().getStatus() == Response.Status.NOT_FOUND.getStatusCode()) { return false; } throw e; } return unregisteredTemplate != null; }

Target:
probably private
Source:
private Guid determineSourceImageGroup(DiskImage image) { if (Guid.Empty.equals(image.getParentId())) { return Guid.Empty; } else { if (!getParameters().getDestImages().isEmpty()) { return getParameters().getDestImageGroupId(); } } return image.getImageTemplateId().equals(image.getParentId()) ? imageDao.get(image.getImageTemplateId()).getDiskId() : getParameters().getImageGroupID(); }

Target:
I think either "else if" or totally removing "else" is more readable. Also 1 less indent.
Source:
public RemoveUnregisteredEntityParameters() { this.setEntityId(Guid.Empty); this.setStorageDomainId(Guid.Empty); this.setStoragePoolId(Guid.Empty); }

Target:
1) Better move the no-arg C'tor to be the first C'tor. 2) It can be nice if it will call the 3-arg C'tor: this(Guid.Empty, Guid.Empty, Guid.Empty);
Source:
protected void endRemoveEntity() { setCommandShouldBeLogged(false); setSucceeded(true); }

Target:
I think that this one is used only here. Can you consider changing it to private?
Source:
private void initUnregisteredEntity(Guid entityId, Guid storageDomainId) { if (!isUnregisteredEntityExists()) { List<OvfEntityData> ovfEntityList = unregisteredOVFDataDao.getByEntityIdAndStorageDomain(entityId, storageDomainId); if (!ovfEntityList.isEmpty()) { // We should get only one entity, since we fetched the entity with a specific Storage Domain ovfEntityData = ovfEntityList.get(0); try { setUnregisteredEntityAndImages(); } catch (OvfReaderException e) { log.error("Failed to parse a given ovf configuration: {}:\n{}", e.getMessage(), ovfEntityData.getOvfData()); log.debug("Exception: ", e); } } } }

Target:
maybe convert it to an early return with log, just to make it a bit clearer.
Source:
protected void initUnregisteredEntity(Guid entityId, Guid storageDomainId) { if (!isUnregisteredEntityExists()) { List<OvfEntityData> ovfEntityList = unregisteredOVFDataDao.getByEntityIdAndStorageDomain(entityId, storageDomainId); if (!ovfEntityList.isEmpty()) { // We should get only one entity, since we fetched the entity with a specific Storage Domain ovfEntityData = ovfEntityList.get(0); try { setUnregisteredEntityAndImages(); } catch (OvfReaderException e) { log.error("Failed to parse a given ovf configuration: {}:\n{}", e.getMessage(), ovfEntityData.getOvfData()); log.debug("Exception: ", e); } } } }

Target:
private?
Source:
public void setUpQueryEntitiesNotFound() { // Mock the Daos when(unregisteredOVFDataDaoMock.getByEntityIdAndStorageDomain(entityId, storageDomainId)).thenReturn( new ArrayList<>()); }

Target:
Can be private
Source:
public void executeCommand(UICommand command) { super.executeCommand(command); if (command == getImportCommand()) { restore(); } else if (command == getRemoveCommand()) { remove(); } else if ("OnRemove".equals(command.getName())) { //$NON-NLS-1$) onRemove(); } else if (command.getName().equals("Cancel")) { //$NON-NLS-1$ cancel(); } }

Target:
Consider changing it to "command.getName().equals("OnRemove")" so it will fit the 'else if'
Source:
protected void updateDetailsAvailability() { if (getSelectedItem() != null) { Disk disk = getSelectedItem(); vmListModel.setIsAvailable(disk.getVmEntityType() == null || !disk.getVmEntityType().isTemplateType()); templateListModel.setIsAvailable(isTemplateDisk(disk)); storageListModel.setIsAvailable(disk.getDiskStorageType() == DiskStorageType.IMAGE || disk.getDiskStorageType() == DiskStorageType.CINDER); } }

Target:
I think this section is exactly: "!isTemplateDisk(disk)"
Source:
public static Stream<MockConfigDescriptor<?>> mockConfiguration() { return Stream.of( MockConfigDescriptor.of(ConfigValues.OrganizationName, "oVirt"), MockConfigDescriptor.of(ConfigValues.SetupNetworksWaitTimeoutSeconds, 5000) ); }

Target:
you can remove this (API no longer accesses configuration so no need to mock) and instead of this please change in testActivate() and similar tests to expect the new Parameters sub-class that you have added
Source:
public static void getAdditionalDeviceImageList(AsyncQuery<List<String>> aQuery, Guid storagePoolId, int osId, Version clusterVersion) { AsyncDataProvider.isFloppySupported(new AsyncQuery<>(isFloppySupported -> { if (isFloppySupported) { getIrsImageList(aQuery, storagePoolId, false, ImageFileType.Floppy, new RepoImageToImageFileNameAsyncConverter()); } }), osId, clusterVersion); }

Target:
Can you move this call to the calling method RunOnceModel::updateFloppyImages ? Here it seems strange that a method called 'get' something never calls the callback if the floppy is not supported.
Source:
public HostRestartConfirmationModel() { super(); setForceToMaintenance(new EntityModel<>()); getForceToMaintenance().setEntity(false); getForceToMaintenance().setIsAvailable(true); }

Target:
It should be available by default, no need to set it.
Source:
private void saveCommonStorageProperties(StorageModel model) { storageDomain.setStorageName(model.getName().getEntity()); saveDefaultedStorageProperties(model, storageDomain); }

Target:
This one is already done on line 816. Do we need it again here?
Source:
public Disk update(Disk incoming) { // If the QCOW version is specified, then perform the update: if (incoming.isSetQcowVersion()) { return performUpdate( incoming, new QueryIdResolver<>(QueryType.GetDiskByDiskId, IdQueryParameters.class), ActionType.AmendImageGroupVolumes, new UpdateParametersProvider()); } return performUpdate(incoming, new DiskResolver(), ActionType.UpdateVmDisk, new BackendDiskResource.UpdateParametersProvider()); }

Target:
What about updating QCOW and other parameters in the same call?
Source:
public void setItems(Collection<T> value, T selectedItem) { List<T> items = new ArrayList<>(value); if (items.get(0) != null) { items.add(0, null); } super.setItems(items, selectedItem); }

Target:
this will fail if the "value" is an empty collection.
Source:
private void updateArbiterAvailability() { getArbiterVolume().setIsAvailable(getTypeList().getSelectedItem().isReplicatedType() && getCluster().getSelectedItem() != null); }

Target:
Doesn't the former condition mean that the Arbiter volume is available only for version 4.1 and lower? In that case removing the version check changes the logic and makes it available for other versions. The Arbiter volume should be probably removed completely.
Source:
public ValidationResult validateOpenStackImageConstraints() { if (ProviderType.OPENSTACK_IMAGE != provider.getType()) { return ValidationResult.VALID; } List<Provider<?>> existingProviders = Injector.get(ProviderDao.class).getAllByTypes(ProviderType.OPENSTACK_IMAGE); if (OpenStackTokenProviderFactory.isApiV3(provider)) { return openStackImageV3Constraints(existingProviders); } else { return openStackImageV2Constraints(existingProviders); } }

Target:
Consider using ? : syntax - return ... ? x : y
Source:
private boolean validateCanAmendDisk() { DiskImage disk = (DiskImage) getNewDisk(); setStoragePoolId(disk.getStoragePoolId()); if (!validate(new StoragePoolValidator(getStoragePool()).existsAndUp())) { return false; } DiskImagesValidator diskImagesValidator = new DiskImagesValidator(Collections.singletonList(disk)); return validate(diskImagesValidator.diskImagesNotIllegal()); }

Target:
Consider using new Java 11 List.of()
Source:
private AuditLogable createAuditLogable(AnsibleCommandConfig command, String taskName) { return AuditLogableImpl.createHostEvent( command.hosts().get(0), command.correlationId(), new HashMap<>() { { put("Message", taskName); put("PlayAction", command.playAction()); } } ); }

Target:
I think it should be safe now with java > 9 to use Map.of("key1","value1", "key2", "value2");
Source:
public AuditLogType getAuditLogTypeValue() { addCustomValue("UserName", String.format("%s", getUserName())); return getSucceeded() ? AuditLogType.USER_REBOOT_VM : AuditLogType.USER_FAILED_REBOOT_VM; }

Target:
This line should not be needed. 'UserName' will be automatically replaced by calling getUserName().
Source:
protected void analyze() { if (isVmStoppedBeingReported()) { proceedDisappearedVm(); return; } if (isExternalOrUnmanagedHostedEngineVm()) { processUnmanagedVm(); return; } if (isVmDown()) { proceedDownVm(); return; } if (isVmRebooting()) { proceedRebootingVm(); } if (!isVmRunningInDatabaseOnMonitoredHost()) { proceedVmReportedOnOtherHost(); return; } proceedVmReportedOnExpectedHost(); }

Target:
Please move this call to proceedVmReportedOnExpectedHost() method. That method contains multiple similar statements, to check VM state and add audit log line.
Source:
public HostNetworkQos selectQos(NetworkAttachment networkAttachment, HostNetworkQos daoHostNetworkQos) { return networkAttachment != null && networkAttachment.isQosOverridden() ? HostNetworkQos.fromAnonymousHostNetworkQos(networkAttachment.getHostNetworkQos()) : daoHostNetworkQos; }

Target:
public seems not required, only used inside vdsbroker
Source:
public HostNetworkQos getHostNetworkQosFromNetwork(Network network) { return network != null ? hostNetworkQosDao.get(network.getQosId()) : null; }

Target:
public seems not required
Source:
public List<HostNetworkQos> getAll() { return hostNetworkQosDao.getAll(); }

Target:
public not required
Source:
private void setDiskImageActiveBySnapshotType(Map<Guid, DiskImage> diskImageMap, Snapshot snapshot) { DiskImage diskImage = diskImageMap.get(snapshot.getId()); if (diskImage == null) { return; } if (snapshot.getType() == SnapshotType.ACTIVE || snapshot.getType() == SnapshotType.PREVIEW) { diskImage.setActive(true); } else { diskImage.setActive(false); } }

Target:
It's possible to make this even shorter: diskImage.setActive(snapshot.getType == ... || ...);
Source:
private void updateDiskSize(DiskImage diskImage) { getSizeExtend().validateEntity(new IValidation[] { new NotEmptyValidation(), new NonNegativeLongNumberValidation(), }); if (getSizeExtend().getIsValid()) { long sizeToAddInGigabytes = Long.parseLong(getSizeExtend().getEntity()); if (sizeToAddInGigabytes > 0) { diskImage.setSizeInGigabytes(diskImage.getSizeInGigabytes() + sizeToAddInGigabytes); } } }

Target:
please move to 'validate' method, so this method could handle only size updating.
Source:
private void updateDiskSize(DiskImage diskImage) { try { long sizeToAddInGigabytes = Long.parseLong(getSizeExtend().getEntity()); if (sizeToAddInGigabytes > 0) { diskImage.setSizeInGigabytes(diskImage.getSizeInGigabytes() + sizeToAddInGigabytes); } } catch (NumberFormatException ignored) { } }

Target:
Suggest to surround just this parsing with the try-catch. This is is the line that has a potential to throw.
Source:
public int setTabIndexes(int nextTabIndex) { certificateAuthority.setTabIndex(++nextTabIndex); prometheusUrl.setTabIndex(++nextTabIndex); prometheusCertificateAuthority.setTabIndex(++nextTabIndex); return nextTabIndex; }

Target:
Please change incrementing the index to (nextTabIndex++) instead of (++nextTabIndex) for all 3 lines, since otherwise you'll need to click tab twice on each field to get to the next one.
Source:
protected void executeCommand() { Cluster cluster = clusterDao.get(getParameters().getClusterId()); if (cluster.supportsGlusterService()) { try { glusterSyncJob.refreshSelfHealData(cluster); } catch (Exception e) { log.error("Error while refreshing Gluster self heal data of cluster '{}': {}", cluster.getName(), e.getMessage()); log.debug("Exception", e); } setSucceeded(true); } }

Target:
setSucceeded(false) and raise error here?
Source:
private VM mockVm(VMStatus vmStatus) { vm.setStatus(vmStatus); vm.setId(vmId); vm.setRunOnVds(Guid.newGuid()); when(vmDao.get(command.getParameters().getVmId())).thenReturn(vm); return vm; }

Target:
If I'm not wrong, the method can return void, as other mockXYZ methods. The return value is never used.
Source:
public static int findInColumnSortList(ColumnSortList sortList, AbstractTextColumn<?> column) { if (sortList == null || column == null) { return -1; } for (int i = 0; i < sortList.size(); i++) { ColumnSortList.ColumnSortInfo sortInfo = sortList.get(i); if (column == sortInfo.getColumn()) { return i; } } return -1; }

Target:
Smells like a bug. Are you sure it should not be equals?
Source:
public Guid getHostForExecution(Guid poolId, Collection<Guid> hostsToFilter) { return getHostForExecution(poolId, vds -> !hostsToFilter.contains(vds)); }

Target:
check for VDS in collection of Guids probably vds.getId()
Source:
public boolean isLeafVolType(Guid storagePoolId, Guid storageDomainId, Guid imageGroupId, Guid imageId) { DiskImage dbImage = getSnapshotLeaf(imageGroupId); DiskImage vdsmImage = getVolumeInfoFromVdsm(storagePoolId, storageDomainId, imageGroupId, imageId); return dbImage.getId().equals(vdsmImage.getId()) ? VolType.LEAF == vdsmImage.getVolType() : true; }

Target:
This one can be simplified: return !dbImage.getId().equals(vdsmImage.getId()) || VolType.LEAF == vdsmImage.getVolType();
Source:
public boolean hasCorrectVolType(Guid storagePoolId, Guid storageDomainId, Guid imageGroupId, Guid imageId) { DiskImage dbImage = getSnapshotLeaf(imageGroupId); DiskImage vdsmImage = getVolumeInfoFromVdsm(storagePoolId, storageDomainId, imageGroupId, imageId); if (dbImage.getId().equals(vdsmImage.getId())) { return VolType.LEAF == vdsmImage.getVolType(); } return true; }

Target:
can be replaced with: return dbImage.getId().equals(vdsmImage.getId()) ? VolType.LEAF == vdsmImage.getVolType() : true; But it is not a must, just a matter of style.
Source:
private String readContent(HttpResponse response) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); } catch (IOException e) { e.printStackTrace(); } return reader.lines().collect(Collectors.joining()); }

Target:
This can fail with null pointer exception, hide errors reading the response, and log 2 errors for same issue (e..g first print stack trace when reading fails, then return empty string and fail when parsing the json). Lets this code raise the IOException and handle it in the caller - we already wrap all the calls in try/catch block.
Source:
private ImageioClient getImageioClient() { if (imageioClient == null) { imageioClient = new ImageioClient(getImageioUnixSocketPath().toString()); } return imageioClient; }

Target:
Since the client does not provide reliable persistent connection, I would not keep an instance in the command and create a new client for each request instead. Adding more state to the command does not help and we avoid the need to create client lazily.
Source:
public void scheduleWithFixedDelay(Object instance, String methodName, Class<?>[] inputTypes, Object[] inputParams, long initialDelay, long taskDelay, TimeUnit timeUnit) { executor.scheduleWithFixedDelay(getRunnable(instance, methodName), initialDelay, taskDelay, TimeUnit.SECONDS); }

Target:
isn't this implementing scheduleWithFixedDelay of the SchedulerUtil interface? why's the return type changed?
Source:
public void close() throws IOException { httpClient.close(); }

Target:
there is no case in which httpClient become null, right ?
Source:
public void afterRefreshTreatment() { try { prometheusClient.close(); } catch (IOException e) { // ignore } }

Target:
pls verify that prometheusClient is not null.
Source:
public void stopMonitoring() { super.stopMonitoring(); try { prometheusClient.close(); } catch (IOException e) { // ignore } }

Target:
pls check that prometheusClient isn't null
Source:
public boolean performNextOperation(int completedChildCount) { restoreCommandState(); switch (getParameters().getVmBackup().getPhase()) { case STARTING: if (runVmBackup()) { updateVmBackupPhase(VmBackupPhase.READY); } else { setCommandStatus(CommandStatus.FAILED); } log.info("Ready to start image transfers using backup URLs"); break; case READY: return true; case FINALIZING: finalizeVmBackup(); setCommandStatus(CommandStatus.SUCCEEDED); break; } persistCommandIfNeeded(); return true; }

Target:
IMHO can be inserted into "runVmBackup()". "setCommandStatus(CommandStatus.FAILED);" instead of "return false;". "updateVmBackupPhase(VmBackupPhase.READY);" instead of "return true;".
Source:
private static Cluster createClusterWithNoCpuName() { Cluster group = new Cluster(); group.setName("Default"); group.setCpuName(""); group.setId(DEFAULT_CLUSTER_ID); group.setCompatibilityVersion(VERSION_1_1); group.setStoragePoolId(DC_ID1); group.setArchitecture(ArchitectureType.undefined); group.setClusterPolicyId(Guid.newGuid()); group.setMaxVdsMemoryOverCommit(100); group.setBiosType(BiosType.CLUSTER_DEFAULT); return group; }

Target:
that's invalid anyway, isn't it? what's the meaning of CLUSTER_DEFAULT on cluster, you can never set it. autodetect==null, and then only concrete values are allowed
Source:
public VmBackupInfo(Map<String, Object> innerMap) { super(innerMap); disks = (Map<String, Object>) innerMap.get(VdsProperties.vm_disks); Object tempObj = innerMap.get(VdsProperties.CHECKPOINT); if (tempObj != null) { checkpoint = (String) innerMap.get(VdsProperties.CHECKPOINT); } }

Target:
Why? Just case tempObj
Source:
private String buildMessage(int from, int to, int total) { if (total > 0) { return messages.fromIndexToIndexOfTotalCount(from, to, total); } else { return messages.fromIndexToIndex(from, to); } }

Target:
Can be removed
Source:
private void resetVmAttributes(VmDynamic vm) { vm.setMigratingToVds(null); vm.getGraphicsInfos().clear(); vm.setGuestCurrentUserName(null); vm.setConsoleCurrentUserName(null); vm.setConsoleUserId(null); vm.setClientIp(""); vm.setIp(null); vm.setFqdn(null); vm.setCpuName(null); vm.setEmulatedMachine(null); vm.setVolatileRun(false); vm.setGuestAgentNicsHash(0); }

Target:
Good, if there are no other places where it may be set to null. But I would rather fix the comparison.
Source:
private boolean addImageTicketToProxy(Guid imagedTicketId, String hostUri) { // Create image ticket String imagePath = String.format( // ToDo: move formatting to an helper for reuse in ImageTransfer "%s%s/%s", hostUri, IMAGES_PATH, imagedTicketId); ImageTicket imageTicket = buildImageTicket(imagedTicketId, imagePath); log.info("Adding image ticket to ovirt-imageio-proxy, id {}", imagedTicketId); try { getProxyClient().putTicket(imageTicket); } catch (RuntimeException e) { log.error("Failed to add image ticket to ovirt-imageio-proxy: {}", e.getMessage(), e); return false; } return true; }

Target:
This is a URL (.e.g "file:///path/to/image" or "nbd:unix:/path/to/socket:exportname=vda"). String url = ...
Source:
public static TransferDiskImageParameters createInitParams(DiskImage diskImage) { TransferDiskImageParameters parameters = new TransferDiskImageParameters(); parameters.setTransferType(TransferType.Download); parameters.setImageGroupID(diskImage.getId()); String fileExtension = diskImage.getVolumeFormat() == VolumeFormat.COW ? ".qcow2" : ".raw"; //$NON-NLS-1$ //$NON-NLS-2$ parameters.setDownloadFilename(diskImage.getDiskAlias() + fileExtension); //$NON-NLS-1$ parameters.setTransferSize(diskImage.getActualSizeInBytes()); parameters.setTransferringViaBrowser(true); return parameters; }

Target:
Not sure whether worth doing, but since the only usage is "DownloadImageManager" (that is in the same package), it is possible to remove "public".
Source:
public TransferDiskImageParameters createInitParams(DiskImage diskImage) { TransferDiskImageParameters parameters = new TransferDiskImageParameters(); parameters.setTransferType(TransferType.Download); parameters.setImageGroupID(diskImage.getId()); String fileExtension = diskImage.getVolumeFormat() == VolumeFormat.COW ? ".qcow2" : ".raw"; //$NON-NLS-1$ //$NON-NLS-2$ parameters.setDownloadFilename(diskImage.getDiskAlias() + fileExtension); //$NON-NLS-1$ parameters.setTransferSize(diskImage.getActualSizeInBytes()); parameters.setTransferringViaBrowser(true); return parameters; }

Target:
can be static to avoid to avoid redundant object creation on startDownload
Source:
private boolean isAssignQuotaAllowed() { List<Disk> disks = getSelectedItems(); return disks != null && disks.size() != 0; }

Target:
can be !disks.isEmpty()
Source:
private List performVmCheckpointsOperation(VDSCommandType vdsCommandType, VdsAndVmIDVDSParametersBase params) { VDSReturnValue vdsRetVal; try { vdsRetVal = runVdsCommand(vdsCommandType, params); if (!vdsRetVal.getSucceeded()) { EngineException engineException = new EngineException(); engineException.setVdsError(vdsRetVal.getVdsError()); throw engineException; } } catch (EngineException e) { log.error("Failed to execute '{}': {}", vdsCommandType, e); throw e; } return (List) vdsRetVal.getReturnValue(); }

Target:
Can it be a List of specific objects, not just "List"?
Source:
private boolean shouldUpdateVmsAndTemplates() { return isVersionChanged() || isBiosTypeChanged() || isCpuNameChanged() || oldCluster.getArchitecture() == getArchitecture(); }

Target:
The condition was inverted, wasn't it?
Source:
protected boolean validate() { if (!(getSourceVmFromDb().getStatus() == VMStatus.Suspended || getSourceVmFromDb().isDown())) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_VM_IS_NOT_DOWN); } DiskImagesValidator diskImagesValidator = new DiskImagesValidator(diskImagesFromConfiguration); validate(diskImagesValidator.diskImagesNotIllegal()); return super.validate(); }

Target:
no need for `if (!validate(diskImagesValidator.diskImagesNotIllegal()) { ... }` ?
Source:
public boolean isIpv4InSubnet(String networkAddress, String mask, String candidateAddress) { String netmask = IPv4MaskValidator.getInstance().getOctetNetmask(mask); Ipv4NetworkRange ipv4NetworkRange = ipAddressConverter.createIpv4NetworkRange(networkAddress, netmask); BigInteger ipToTestInt = ipAddressConverter.convertIpAddressToBigInt(candidateAddress); return ipv4NetworkRange.isInRange(ipToTestInt); }

Target:
Please handle that candidateAddress might be null.
Source:
protected void createCommentEditor(final int suggestRow, final int column, final int line, final short file) { createCommentEditor(suggestRow, column, line, file, ""); }

Target:
But existing rows use null not "" for the parentUuid.
Source:
private static List<String> optionalList(final Config config, final String name) { String s[] = config.getStringList("ldap", null, name); if(s == null || s.length == 0) { return null; } final List<String> vlist = new ArrayList<String>(); for(int i = 0; i < s.length; i++) { vlist.add(s[i]); } return vlist; }

Target:
IIRC getStringList returns String[0] when there are no elements, thus you will never get null here.
Source:
SshKeyCacheEntry(final AccountSshKey.Id i, final PublicKey k) { id = i; publicKey = k; lastUsed = null; }

Target:
Hmm, our caller should be invoking us with a full AccountSshKey object in hand. They should pass down the last used time from the database column to initialize this field, rather than always assume it is null.
Source:
public void addChangeListener(ChangeListener listener, IdentifiedUser user) { ChangeListenerHolder holder = new ChangeListenerHolder(listener, user); listeners.put(listener, holder); }

Target:
Style-nit: The code would be shorter if you remove the holder variable: listeners.put(listener, new ChangeListenerHolder(listener, user));
Source:
private boolean isVisibleTo(Change change, IdentifiedUser user) { final ProjectState pe = projectCache.get(change.getProject()); final ProjectControl pc = pe.controlFor(user); final RefControl rc = pc.controlForRef(change.getDest().get()); return rc.isVisible(); }

Target:
This can return null if the project suddenly were to disappear. I think we should guard against that by testing for null and skipping the rest of the method: if (pe == null) { return false; }
Source:
public InheritedRefRight(){ }

Target:
Make this protected, it exists only for the JSON serialization library.
Source:
protected ListBranchesResult() { this(new ArrayList<Branch>(), false); }

Target:
Since this constructor exists only for the JSON encoding, which will recursively process and populate the fields, there's no need to call this(). Just accept the default initialization of false/null for the fields and let the JSON decoder finish building the object.
Source:
public int allowedValueForRef(Set<AccountGroup.Id> groups) { int val = Integer.MIN_VALUE; for (RefRight right : rights) { if (groups.contains(right.getAccountGroupId())) { if ((val < 0 && right.getMaxValue() > 0)) { // If one of the user's groups had denied them access, but // this group grants them access, prefer the grant over // the denial. We have to break the tie somehow and we // prefer being "more open" to being "more closed". // val = Math.max(right.getMaxValue(), val); } } } return val; }

Target:
Drop this if entirely. The if-else block right here can just be simplified down to the val = Math.max(...) expression.
Source:
ProjectQoSFilter(final Provider<CurrentUser> userProvider, QueueProvider queue, final ServletContext context, @GerritServerConfig final Config cfg) { this.userProvider = userProvider; this.executor = queue.getInteractiveQueue(); this.context = context; this.maxWait = getTimeUnit(cfg, "httpd", null, "maxwait", 5, MINUTES); }

Target:
No, you really need to do this selection dynamically based on the current user. Batch jobs coming in over the http:// interface for fetch should get degraded service just like when they come in over ssh://.
Source:
public static String invertSortKey(String sk) { if (sk.equalsIgnoreCase("z")) { return "/"; // The character before '0' } StringBuilder inv = new StringBuilder(16); inv.setLength(16); formatHexLong(inv, -1l - parseUnsignedHex(sk)); return inv.toString(); }

Target:
For completeness should we also invert '/' to 'z' ?
Source:
public void testCreateSchema_DefaultAccess_AnonymousUsers() throws OrmException { db.create(); final SystemConfig config = db.getSystemConfig(); assertDefaultRight(RefRight.REGEX_SYMBOL+"refs/*", config.anonymousGroupId, ApprovalCategory.READ, 1, 1); }

Target:
Style-nit: Spaces around operators like +.
Source:
public SessionCacheCleaner( SchemaFactory<ReviewDb> reviewDbFactory, @Named(WebSession.CACHE_NAME) final Cache<ActiveSession.Key, ActiveSession> cache) throws OrmException { this.activeSessionAccess = reviewDbFactory.open().activeSessions(); this.cache = cache; }

Target:
Please don't hold onto the database connection for 12 hours, open and close it during the run method each time you execute. These are borrowed from a small pool, and keeping it tied up for hours with no use isn't friendly to the other threads in the JVM.
Source:
public AccountDiffPreference getAccountDiffPreference() { AccountDiffPreference diffPref = null; try { diffPref = dbProvider.get().accountDiffPreferences().get(getAccountId()); if (diffPref == null) { return AccountDiffPreference.createDefault(getAccountId()); } } catch (OrmException e) { log.warn("Cannot query account diff preferences", e); } return diffPref; }

Target:
Please don't initialize a local variable to null. Instead leave it uninitialized so the compiler can prove we have correctly populated it before use. Right now this is hiding a bug here where the diffPref can be null if the database threw an exception. That would probably crash the JSON encoder in HostPageServlet. If the database fails, we should return a default preference after logging the warning here.
Source:
void onUpdate(ClickEvent event) { update(); if (Gerrit.isSignedIn()) { persistDiffPreferences(); } }

Target:
This should be in the update() method below, ensuring that we save preferences even if we were invoked by the key binding to "Enter", setup in our constructor.
Source:
private void deactivate() { if (activePatchSetId != -1) { PatchSetComplexDisclosurePanel patchSetPanel = patchSetPanels.get(activePatchSetId); if (patchSetPanel != null) { patchSetPanel.setActive(false); } activePatchSetId = -1; } }

Target:
I can't seem to reproduce this failure. Can you update the commit message to better explain under what condition we don't have a panel, but think we should?
Source:
public SshKeyCacheEntryIterable(Iterable<SshKeyCacheEntry> sshKeyIter) { this.sshKeyIter = sshKeyIter; }

Target:
This doesn't have to be public. Just use default package access since only thee cache impl in this package has to see it.
Source:
public Iterable<SshKeyCacheEntry> getSshKeyCacheEntries() { return sshKeyIter; }

Target:
This doesn't have to be public. Just use default package access since only thee cache impl in this package has to see it.
Source:
public static BaseEdit fromEdit(Edit e) { BaseEdit goe = new BaseEdit(e.getBeginA(), e.getEndA(), e.getBeginB(), e.getEndB()); if (e instanceof ReplaceEdit) { ReplaceEdit re = (ReplaceEdit) e; List<BaseEdit> intlEdits = BaseEdit.fromEditList(re.getInternalEdits()); goe = new com.google.gerrit.prettify.common.ReplaceEdit(goe, intlEdits); } return goe; }

Target:
We should just remove ReplaceEdit. Its our own private hacked class.
Source:
public static List<BaseEdit> fromEditList(List<Edit> edits) { ArrayList<BaseEdit> gwtOrmEdits = new ArrayList<BaseEdit>(edits.size()); for (Edit e : edits) { gwtOrmEdits.add(fromEdit(e)); } return Collections.unmodifiableList(gwtOrmEdits); }

Target:
The name "gwtOrmEdits" doesn't mean much here. Maybe "res", "result", "out", "r" would be better?
Source:
public SerializableProtobuf(T object, ProtobufCodec<T> codec) { buf = new byte[codec.sizeof(object)]; codec.encode(object, buf); this.object = object; this.codec = codec; hash = object.hashCode(); }

Target:
Probably doesn't need to be public.
Source:
public T toObject(ProtobufCodec<T> codec, Provider<T> provider) { if (object == null) { this.codec = codec; if (provider == null) { object = codec.decode(buf); } else { object = provider.get(); try { codec.mergeFrom(CodedInputStream.newInstance(buf), object); } catch (IOException e) { throw new RuntimeException("Cannot decode message", e); } } // Free the memory being taken up by the buffer. buf = null; } return object; }

Target:
Probably doesn't need to be public.
Source:
private void send(final List<RemoteRefUpdate> cmds, final RefSpec spec) throws IOException { final String src = spec.getSource(); String dst = spec.getDestination(); if (dst == null) dst = src; final boolean force = spec.isForceUpdate(); cmds.add(new RemoteRefUpdate(db, src, dst, force, null, null)); }

Target:
Style-nit: Put curly braces around the then statement.
Source:
public PrefetchableAndPredicate( Collection<? extends Predicate<ChangeData>> that) { super(that); }

Target:
Doesn't need to be public.
Source:
public PrefetchableAndPredicate(Predicate<ChangeData>... that) { super(that); }

Target:
Doesn't need to be public.
Source:
private void addSuggestion(Map map, Account account, AccountInfo info, Boolean active) { if(active != null) { if(active.booleanValue() != account.isActive()) { return; } } map.put(account.getId(), info); }

Target:
Style-nit: Space after if. But I think you can write the code more cleanly: if (active == null || active == account.isActive()) { map.put(account.getId(), info); }
Source:
public void run() { try { final ReviewDb db = schema.open(); try { for (final Project project : db.projects().all()) { if (!project.getNameKey().equals(wildProject.getNameKey())) { replication.scheduleFullSync(project.getNameKey(), urlMatch); } } } finally { db.close(); } } catch (OrmException e) { log.error("Cannot enumerate known projects", e); } }

Target:
Why not compare Project.Ids?
Source:
private Collection<RefRight> getWildProjectRights() { final ProjectState s = projectCache.get(wildProject.getNameKey()); return s != null ? s.getLocalRights() : Collections.<RefRight> emptyList(); }

Target:
Use getId() instead?
Source:
private void initCreateButton() { createButton = new Button(Util.C.buttonCreateProject()); createButton.setEnabled(false); createButton.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { enableForm(false); doCreateProject(); } }); }

Target:
I think it is confusing to put this above instead of in doCreateProject (right before the RPC call). If there ends up being another way to trigger the create (via keyboard...), it will be missed, or have to be duplicated.
Source:
public String getProjectName() { return projectName; }

Target:
[optional] maybe better to return Project.NameKey here
Source:
private void onTextBoxBase(final TextBoxBase tb) { // The text appears to not get updated until the handlers complete. DeferredCommand.add(new Command() { public void execute() { String orig = strings.get(tb); orig = orig == null ? "" : orig; if (! orig.equals(tb.getText())) { widget.setEnabled(true); } } }); }

Target:
This is easier to read: if (orig == null) orig = "";
Source:
private void setSubmitType(final Project.SubmitType newSubmitType) { if (submitType != null) { for (int i = 0; i < submitType.getItemCount(); i++) { if (newSubmitType.name().equals(submitType.getValue(i))) { submitType.setSelectedIndex(i); return; } } submitType.setSelectedIndex(-1); setEnabledForUseContentMerge(); } }

Target:
We also need to setEnabledForUseContentMerge(); here.
Source:
public void setProjectName(final Project.NameKey projectName) { suggestBox.setText(projectName.get()); }

Target:
Passing in a null here should probably be allowed as a way to clear this box.
Source:
private void updateParentProject(final ProjectConfig config) throws UpdateParentsFailedException, NoSuchProjectException { final Project parentProject; if (parentProjectName != null) { final ProjectState parentState = projectCache.get(parentProjectName); if (parentState == null) { throw new NoSuchProjectException(parentProjectName); } parentProject = parentState.getProject(); } else { parentProject = null; } updateParentsFactory.create(Collections.singleton(config.getProject()), parentProject).validateParentUpdate(); config.getProject().setParentName(parentProjectName); }

Target:
This could just be done on line 247 avoiding the need for an else.
Source:
private void service() throws IOException, Failure { project = projectControl.getProjectState().getProject(); try { repo = repoManager.openRepository(project.getNameKey()); } catch (RepositoryNotFoundException e) { final String name = project.getName(); throw new Failure(1, "fatal: '" + name + "': not a git archive", e); } try { runImpl(); } finally { repo.close(); } }

Target:
The name is only used in the next statement, could be inlined.
Source:
public Set<AccountGroup.Id> getEffectiveGroups() { if (effectiveGroups == null) { Set<AccountGroup.Id> seedGroups = new HashSet<AccountGroup.Id> (); if (authConfig.isIdentityTrustable(state().getExternalIds())) { seedGroups = realm.groups(state()); } else { seedGroups = authConfig.getRegisteredGroups(); } effectiveGroups = getIncludedGroups(seedGroups); } return effectiveGroups; }

Target:
There is no need to initialize the variable here, both branch directions below assign to the variable and discard this HashSet.
Source:
public void setTopView(TopView tv) { topPanel.remove(0); switch(tv) { case MAIN: topPanel.add(new FlowPanel()); break; case COMMIT: topPanel.add(commitMessageBlock); break; case PREFERENCES: topPanel.add(settingsPanel); break; case PATCH_SETS: topPanel.add(historyTable); break; case FILES: topPanel.add(fileList); break; } }

Target:
maybe better: topPanel.clear()
Source:
private String getSortValue() { if (accountInfo != null) { if (accountInfo.getPreferredEmail() != null) { return accountInfo.getPreferredEmail(); } else { return accountInfo.getFullName().toString(); } } else { return groupReference.getName(); } }

Target:
My Pref: unneeded else.
Source:
public static boolean isLegalReviewerGroup(final AccountGroup.UUID groupUUID) { if (AccountGroup.ANONYMOUS_USERS.equals(groupUUID) || AccountGroup.REGISTERED_USERS.equals(groupUUID)) { return false; } return true; }

Target:
My Nit Pref: eliminate if, just return the boolean evaluation.
Source:
public MyWalker() { super(ProjectState.this.wildProject, ProjectState.this.projectCache); }

Target:
Declare package access.
Source:
public boolean isOwnerOf(AccessSection section) { return RefUtil.isAnySuperSet(getOwnerOf(), section.getRefPattern()); }

Target:
I'm not really sure this much accuracy is necessary on the web UI side. We just need to know if the user is an owner of a local section in order to let them edit.
Source:
protected ObjectId commit(final Merger m, final CommitBuilder mergeCommit) throws IOException, UnsupportedEncodingException { ObjectInserter oi = m.getObjectInserter(); try { ObjectId id = oi.insert(mergeCommit); oi.flush(); return id; } finally { oi.release(); } }

Target:
Should subclasses be allowed to override this method?
Source:
public PrologJar (Config config, SitePaths site, Repository git) { this.git = git; String s = config.getString("cache", null, "directory"); cacheDir = site.resolve(config.getString("cache", null, "directory")); }

Target:
This line is unused.
Source:
PRED_change_branch_1(Term a1, Operation n) { arg1 = a1; cont = n; }

Target:
Should be public.
Source:
PRED_commit_author_3(Term a1, Term a2, Term a3, Operation n) { super(a1, a2, a3, n); }

Target:
Should be public.
Source:
PRED_commit_delta_4(Term a1, Term a2, Term a3, Term a4, Operation n) { arg1 = a1; arg2 = a2; arg3 = a3; arg4 = a4; cont = n; }

Target:
Should be public.
Source:
public void setCleanup(List<Runnable> cleanup) { this.cleanup = cleanup; }

Target:
If your old cleanup list is non-empty, should we copy the elements into the new cleanup list, or simply discard them and let them leak?
Source:
public static String toLongString(final Change.Status status) { if (status == null) { return ""; } switch (status) { case NEW: return C.statusLongNew(); case SUBMITTED: return C.statusLongSubmitted(); case MERGED: return C.statusLongMerged(); case ABANDONED: return C.statusLongAbandoned(); case DRAFT: return C.statusLongDraft(); default: return status.name(); } }

Target:
Nit: seems like this should go above NEW?
Source:
public List<PatchLineComment> comments(Provider<ReviewDb> db) throws OrmException { if (comments == null) { comments = db.get().patchComments().byChange(legacyId).toList(); } return comments; }

Target:
Wrong place. :) These are unordered during retrieval. Try line 216.
Source:
private boolean verify(HttpServletRequest req, HttpServletResponseWrapper rsp) throws IOException { if (!authConfig.isTrustContainerAuth()) return true; final String username = req.getRemoteUser(); final AccountState who = accountCache.getByUsername(username); if (who == null || ! who.getAccount().isActive()) { rsp.sendError(SC_UNAUTHORIZED); return false; } session.get().setUserAccountId(who.getAccount().getId()); return true; }

Target:
Style nit: use brackets even for single statement ifs.