auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static PmProxyType fromValue(String v) { try { if (v==null) { return null; } if (v.equals("cluster")) { return CLUSTER; } else if (v.equals("dc")) { return DC; } else { return valueOf(v.toUpperCase()); } } catch (IllegalArgumentException e) { return null; } }

Target:
if 'v' is not a member of enum why return it in upper case?
Source:
public void validateEnums(Host host) { if (host.isSetPowerManagement()) { if (host.getPowerManagement().isSetPmProxies()) { for (PmProxy proxy : host.getPowerManagement().getPmProxies().getPmProxy()) { validateEnum(PmProxyType.class, proxy.getPropietary(), true); } } } }

Target:
iiuc "propietary" is a string and enum that you have added is PmProxyType, so you should be adding it to <pm_proxy> and validating it here.
Source:
public void getFCStorageTypeForLun() throws Exception { LUNs lun = new LUNs(); ArrayList<storage_server_connections> connections = new ArrayList<storage_server_connections>(); lun.setLunConnections(connections); StorageType storageType = command.getLUNStorageType(lun); assertEquals("Lun disk should be of FC storage type since it does not had connections", storageType, storageType.FCP); }

Target:
please switch between the assert values, expected value should be second.. /s/disk/storage type /s/had/have
Source:
protected <T> Response performCreate(VdcActionType task, VdcActionParametersBase taskParams, IResolver<T, Q> entityResolver, boolean block) { return performCreate(task, taskParams, entityResolver, block, null); }

Target:
should be final as well?
Source:
protected StorageDomain deprecatedPopulate(StorageDomain model, storage_domains entity) { if (StorageDomainSharedStatus.Unattached.equals(entity.getstorage_domain_shared_status())) { model.setStatus(StatusUtils.create(StorageDomainStatus.UNATTACHED)); } else { model.setStatus(null); } return model; }

Target:
no need to return super.deprecatedPopulate() ?
Source:
protected File determineActualFile(final HttpServletRequest request, Locale locale) { File file = ServletUtils.makeFileFromSanePath(request.getPathInfo(), base); // Check if file is found. If not found go ahead and try and look up the English US locale version. if (null != file && !ServletUtils.canReadFile(file)) { file = ServletUtils.makeFileFromSanePath(replaceLocaleWithUSLocale(request.getPathInfo(), locale), base); } return file; }

Target:
Please use "something <operator> null" convention
Source:
protected Locale getLocaleFromRequest(final HttpServletRequest request) { String localeString = getLocaleStringFromReferer(request); //Unable to determine locale string from referer (preferred way) if (null == localeString) { //Note this fails if the is something like /menu.css localeString = getLocaleStringFromPath(request.getPathInfo()); } //Validate that the locale string is valid. Locale locale = LocaleUtils.getLocaleFromString(localeString, true); return locale; }

Target:
Please use "something <operator> null" convention
Source:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Locate the requested file: File file = ServletUtils.makeFileFromSanePath(request.getPathInfo(), base); file = checkForIndex(request, response, file, request.getPathInfo()); if (null == file) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } else { // Send the content of the file: // type is the default MIME type of the Servlet. ServletUtils.sendFile(request, response, file, type); } }

Target:
Please use "something <operator> null" convention
Source:
private List<String> getListOfIpAddresses(String ipAddressesAsString) { if (ipAddressesAsString == null) { return Collections.emptyList(); } return Arrays.asList(StringUtils.split(ipAddressesAsString,DELIMITER)); }

Target:
Why not return null?
Source:
public void setUp() throws Exception { super.setUp(); when(getQuery().getDbFacade()).thenReturn(dbFacade); when(dbFacade.getVmGuestAgentInterfaceDao()).thenReturn(vmGuestAgentInterfaceDao); }

Target:
You can use getDbFacadeMockInstance() instead of mocking it yourself
Source:
public boolean runForSingleConnectionInHost(storage_domains storageDomain, Guid storagePoolId, int type) { storage_pool pool = DbFacade.getInstance().getStoragePoolDao().get(storagePoolId); if (pool.getspm_vds_id() != null) { return runConnectionStorageToDomain(storageDomain, pool.getspm_vds_id().getValue(), type); } else { log.errorFormat("Pool {0} does not have spm vds id to connect storage to domain.", pool.getname()); return false; } }

Target:
The return terminates the if - you should remove the else
Source:
public VM getVm() { VM vm = super.getVm(); if (vm != null) { return vm; } vm = getVmDAO().get(getParameters().getVmId()); if (vm != null) { setVm(vm); setVmId(vm.getId()); } return vm; }

Target:
super.getVm() will do dao call...
Source:
private boolean isVmRunning(VM vm) { return vm != null && vm.getStatus() == VMStatus.Up && vm.getRunOnVds() != null && !vm.getRunOnVds().equals(Guid.Empty); }

Target:
you can't get here with vm == null, so it should be removed from here.
Source:
private boolean isVmDown(VM vm) { return vm != null && vm.getStatus() == VMStatus.Down; }

Target:
you can't get here with vm == null, so it should be removed from here.
Source:
private List<LiveMigrateDisksParameters> getLiveMigrateDisksParametersList() { List<LiveMigrateDisksParameters> liveMigrateDisksParametersList = new ArrayList<LiveMigrateDisksParameters>(); for (Guid vmId : vmsLiveMigrateParametersMap.keySet()) { List<LiveMigrateDiskParameters> parametersList = vmsLiveMigrateParametersMap.get(vmId); LiveMigrateDisksParameters liveMigrateDisksParameters = new LiveMigrateDisksParameters(parametersList, vmId); liveMigrateDisksParameters.setParentCommand(VdcActionType.MoveDisks); liveMigrateDisksParameters.setSessionId(getParameters().getSessionId()); liveMigrateDisksParametersList.add(liveMigrateDisksParameters); } return liveMigrateDisksParametersList; }

Target:
You're iterating over the keyset, and calling get from the map in the first line. Just iterate over the entrySet instead
Source:
public synchronized void removeQuotaFromCache(Guid storagePoolId, List<Guid> quotaList) { lock.writeLock().lock(); try { if (!storagePoolQuotaMap.containsKey(storagePoolId)) { return; } synchronized (storagePoolQuotaMap.get(storagePoolId)) { Map<Guid, Quota> map = storagePoolQuotaMap.get(storagePoolId); for (Guid quotaId : quotaList) { map.remove(quotaId); } } } finally { lock.writeLock().unlock(); } }

Target:
Please check if really needed.
Source:
private boolean canDoSnapshot(VM vm) { //if version is 3.0 - live snapshot is not available, thus if vm is up snapshot is not possible so it needs to be //checked if it's up or not //if version is 3.1, there is no need to check if vm is up since in any case snapshot is possible boolean canSnapshot = true; if(!isLiveSnapshotEnabled() && !ImagesHandler.isVmDown(vm)) { //if there is no live snapshot and the vm is up - snapshot is not possible addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_DATA_CENTER_VERSION_DOESNT_SUPPORT_LIVE_SNAPSHOT); canSnapshot = false; } return canSnapshot; }

Target:
I agree with Vered
Source:
private Guid getDisksStorageDomainId() { Disk disk = getVm().getDiskMap().values().iterator().next(); if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { return ((DiskImage) disk).getstorage_ids().get(0); } else { return Guid.Empty; } }

Target:
This is obviously only relevant to Images. So why are we even getting here if we're hadnling a LUN disk?
Source:
private void executeAndSetReturnValue(String volumeName) { VDSReturnValue returnValue = executeCommand(volumeName); getQueryReturnValue().setReturnValue(returnValue.getReturnValue()); return; }

Target:
this "return;" statement is of no use.
Source:
protected boolean canDoAction() { if (getVm() == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_FOUND); } if (getVm().isDeleteProtected()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DELETE_PROTECTION_ENABLED); } if (!(super.canDoAction() && canRemoveVm())) { return false; } return true; }

Target:
You can remove all the following code: if (!(.... return false; } return true; With simply : return super.canDoAction() && canRemoveVm()
Source:
private void removeGlusterVolumesFromDb() { List<GlusterVolumeEntity> volumes = getGlusterVolumeDao().getByClusterId(getVdsGroupId()); if (volumes.size() > 0) { getGlusterVolumeDao().removeByClusterId(getVdsGroupId()); } }

Target:
The check for volumes count doesn't add any value. You'll execute one query all the time, and two when there are volumes. Directly invoking the removeByClusterId() will mean only one query in all cases. When there are no volumes, it won't delete anything, but still succeed. So it should work.
Source:
public static <V> ExecutorCompletionService<V> createCompletionService() { ExecutorCompletionService<V> ecs = new ExecutorCompletionService<V>(es); return ecs; }

Target:
you forgot to inline into one liner method as moti suggested on patch #1 .. :-) other than that - looks good to me.
Source:
private Network getNetworkByName(List<Network> networks) { return LinqUtils.firstOrNull(networks, new Predicate<Network>() { @Override public boolean eval(Network network) { return network.getname().equals(getNetworkName()); } }); }

Target:
LinqUtils could be replaced with for loop and return statement which will simplify the reading and reduce the need of creating new anonymous class.
Source:
private void applyModeCustomizations() { if (ApplicationModeHelper.getUiMode() == ApplicationMode.GlusterOnly) { optimizationTab.setVisible(false); resiliencePolicyTab.setVisible(false); clusterPolicyTab.setVisible(true); dataCenterPanel.addStyleName(style.generalTabTopDecoratorEmpty()); } }

Target:
please make the policy tab hidden in Gluster mode.
Source:
public boolean hasConflicts() { return this.conflictStatus > 0; }

Target:
I guess we need a null check as well.
Source:
public void testRemoveAll() { List<Guid> hookIds = new ArrayList<Guid>(); hookIds.add(HOOK_ID); hookIds.add(HOOK_ID2); dao.removeAll(hookIds); List<GlusterHookEntity> hooks = dao.getByClusterId(CLUSTER_ID); assertNotNull(hooks); }

Target:
Also check if result is empty?
Source:
public void testUpdateGlusterHookStatus() { dao.updateGlusterHookStatus(FixturesTool.HOOK_ID, null, GlusterHookStatus.ENABLED); GlusterHookEntity hook = dao.getById(FixturesTool.HOOK_ID); assertNotNull(hook); assertEquals(GlusterHookStatus.ENABLED, hook.getStatus()); }

Target:
i think you need to pass the SERVER_ID which you want to update the status.
Source:
public ValidationResult clusterNetworkNotUsedByTemplates() { List<VmTemplate> templatesUsingNetwork = new ArrayList<VmTemplate>(); for (VmTemplate template : getVmTemplateDAO().getAllForVdsGroup(networkCluster.getClusterId())) { for (VmNetworkInterface nic : getVmNetworkInterfaceDao().getAllForTemplate(networkCluster.getClusterId())) { if (nic.getNetworkName() == network.getName()) { templatesUsingNetwork.add(template); } } } return networkNotUsed(templatesUsingNetwork, VdcBllMessages.VAR__ENTITIES__VM_TEMPLATES); }

Target:
I think you meant: getVmNetworkInterfaceDao().getAllForTemplate(*template.getId()*)
Source:
private void internalFreeMac(String mac) { if (allocatedMacs.containsKey(mac)) { removeMacFromMap(allocatedMacs, mac); availableMacs.add(mac); } else if (allocatedCustomMacs.containsKey(mac)) { removeMacFromMap(allocatedCustomMacs, mac); } }

Target:
I'm troubled about this line: Since the AllowDuplicateMacAddress configuration variable is reloadable, this code won't serve well in case we moved from permissive to restrictive mode: returning a MAC address to the available mac address pool should be done only if it no longer in use by the allocatedMacs
Source:
private boolean addMacToMap(Map<String, Integer> macMap, String mac) { boolean returnValue = false; if (!macMap.containsKey(mac)) { macMap.put(mac, 1); // First time this mac is used returnValue = true; } else if (allowDuplicate()) { incrementMacInMap(macMap, mac); returnValue = true; } return returnValue; }

Target:
I wouldn't use a variable for this but just return on the spot, this method is not that complicated that you would need a variable to track it's return value.
Source:
public static void InitDictionaries() { log.info("Start initializing dictionaries"); _managersDictionary.clear(); for (Version ver : Config.<HashSet<Version>> GetValue(ConfigValues.SupportedClusterLevels)) { _managersDictionary.put(ver, new CpuFlagsManager(ver)); } log.info("Finished initializing dictionaries" + CpuFlagsManagerHandler.class.getSimpleName()); }

Target:
why "+ CpuFlagsManagerHandler.class.getSimpleName() "? if you do leave it..space is missing between "dictionaries" and it.
Source:
protected void endVmCommand() { super.endVmCommand(); // if we got here, the target snapshot exists for sure getSnapshotDao().updateStatus(getParameters().getDstSnapshotId(), SnapshotStatus.OK); }

Target:
seems to be like this should be before the vm is unlocked in super.endVmCommand();
Source:
protected Map<String, String> getExclusiveLocks() { if (getVdsGroup().supportsGlusterService() && !isInternalExecution()) { return Collections.singletonMap(getVdsGroupId().toString(), LockingGroup.GLUSTER.name()); } return super.getExclusiveLocks(); }

Target:
You don't need call to super method
Source:
public Map<String, String> getJobMessageProperties() { if (volume != null) { if (jobProperties == null) { jobProperties = super.getJobMessageProperties(); } jobProperties.put(GlusterConstants.VOLUME, volume.getName()); } return jobProperties; }

Target:
there is a potential NPE here since jobProperties might not be initialized. I'd suggest changing it to: @Override public Map<String, String> getJobMessageProperties() { if (jobProperties == null) { jobProperties = super.getJobMessageProperties(); if (volume != null) { jobProperties.put(GlusterConstants.VOLUME, volume.getName()); } } return jobProperties; }
Source:
protected List<Network> getNetworks() { if (networks == null) { networks = getDbFacade().getNetworkDao().getAllForDataCenter(network.getDataCenterId()); if (networks == null) { networks = Collections.<Network> emptyList(); } } return networks; }

Target:
This code is not necessary, it's the DAO responsibility to return empty list if there are no networks. That is the de-facto contract in the system.
Source:
public void networkExists() throws Exception { assertEquals(ValidationResult.VALID.getMessage(), validator.networkExists().getMessage()); }

Target:
Since using assertEquals to compare objects, you can compare the ValidationResult objects: assertEquals(ValidationResult.VALID, validator.networkExists()); here and elsewhere in the file.
Source:
public void dataCenterDoesntExist() throws Exception { doReturn(null).when(validator).getDataCenter(); // replace default mock data center with null data center assertEquals(new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_EXIST).getMessage(), validator.dataCenterExists().getMessage()); }

Target:
Please replace the doReturn() with when() around the entire file, i.e. when(validator.getDataCenter()).thenReturn(null);
Source:
public SubTabProviderGeneralView(DetailModelProvider<ProviderListModel, ProviderGeneralModel> modelProvider) { super(modelProvider); // Init formPanel formPanel = new GeneralFormPanel(); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); Driver.driver.initialize(this); // Build a form using the FormBuilder formBuilder = new FormBuilder(formPanel, 1, 1); formBuilder.addFormItem(new FormItem(constants.nameProvider(), name, 0, 0)); }

Target:
Done
Source:
public void setMainTabSelectedItem(Provider selectedItem) { Driver.driver.edit(getDetailModel()); formBuilder.update(getDetailModel()); }

Target:
Done
Source:
public static synchronized void addToCache(AttestationValue value){ if (!attestationValues.containsKey(value.getHostName())) attestationValues.putIfAbsent(value.getHostName(), value); }

Target:
This "if" is not needed, the "putIfAbsent" method already performs the check, and it doees it in a atomic way, so the "synchronized" modifier is not required.
Source:
public static synchronized void removeFromCache(String key){ if (key != null){ attestationValues.remove(key); } }

Target:
The remove method of the ConcurrentHashMap already performs its own synchronization, so the "synchronized" modifier is not required.
Source:
public static AttestationValue getValueFromCache(String key){ AttestationValue value = attestationValues.get(key); return value; }

Target:
return statement can be one line: return attestationValues.get(key);
Source:
public static synchronized void removeFromCache(String key){ if (attestationValues.containsKey(key)){ attestationValues.remove(key); } }

Target:
Won't "attestationValues.remove(...)" be enough?
Source:
protected boolean canDoAction() { boolean returnValue = super.canDoAction(); // the condition allows to get only user and password which are both set (even with empty string) or both aren't // set (null), the action will fail if only one of those parameters is null. if (returnValue && (getParameters().getSysPrepUserName() == null ^ getParameters().getSysPrepPassword() == null)) { addCanDoActionMessage(VdcBllMessages.VM_CANNOT_RUN_ONCE_WITH_ILLEGAL_SYSPREP_PARAM); returnValue = false; } // only administrator can specify destination host if(getParameters().getDestinationVdsId() != null && !getCurrentUser().isAdmin()) { addCanDoActionMessage(VdcBllMessages.VM_CANNOT_RUN_ONCE_NOT_ADMIN_FOR_DESTINATION_VDS_PARAM); returnValue = false; } return returnValue; }

Target:
the action shouldn't fail if: the above & getParam().getDestHost == getVm().getDestHost()
Source:
public final static String encrypt(String source, String certificateFile, String passwd, String alias) throws Exception { try { String result = ""; if (!StringHelper.isNullOrEmpty(source.trim())) { KeyStore store = EncryptionUtils.getKeyStore(certificateFile, passwd, certType); result = encrypt(source, store.getCertificate(alias)); } return result; } catch (Exception e) { log.error("Error doing the encryption", e); throw e; } }

Target:
StringUtils.isNotEmpty(source)
Source:
public String getMessage() { return ("done".equalsIgnoreCase(_message.toLowerCase())) ? "" : _message; }

Target:
Not related to your change, but isn't there anywhere some enum instead of using hardcoded "done"?
Source:
protected void executeCommand() { final DiskImage newDiskImage = getParameters().getDiskImage(); if (newDiskImage != null) { addDiskImageToDb(newDiskImage, getCompensationContext()); getReturnValue().setActionReturnValue(newDiskImage.getId()); getReturnValue().setSucceeded(true); } }

Target:
The null check should be in the canDoAction(), not the executeCommand()
Source:
public static boolean isManagementNetwork(Network net) { return Config.<String> GetValue(ConfigValues.ManagementNetwork).equalsIgnoreCase(net.getName()); }

Target:
please use case-sensitive comparison
Source:
protected storage_domains createStorageDomain(int availableSpace, Guid storageDomainId) { storage_domains sd = new storage_domains(); sd.setstorage_domain_type(StorageDomainType.Master); sd.setstatus(StorageDomainStatus.Active); sd.setavailable_disk_size(availableSpace); sd.setused_disk_size(USED_SPACE_GB); sd.setId(storageDomainId); return sd; }

Target:
should be private static.
Source:
public Hosts list() { // Filtered users are not allowed to view hosts if (isFiltered()) { throw new WebApplicationException(Response.Status.FORBIDDEN); } ApplicationMode appMode = getCurrent().get(ApplicationMode.class); if (appMode == ApplicationMode.GlusterOnly) { return listGlusterOnly(); } else { return listAll(); } }

Target:
1. this error is not needed as you removed (VdcQueryAuthType.User) from GetAllHosts query 2. please also remove this exception from BackendHostResource.get() after you make GetVdsByVdsId admin-only as well thanks.
Source:
private static int compDigitSequence(String seq1, String seq2) { int compRes = ((Integer) Integer.parseInt(seq1)).compareTo(Integer.parseInt(seq2)); return compRes != 0 ? compRes : compNonDigitSequence(seq1, seq2); }

Target:
Perhaps it would be easier to read a positive check than a negative one?
Source:
private boolean removeVm() { VM vm = getVm(); Guid vmId = getVmId(); hasImages = vm.getDiskList().size() > 0; if (getParameters().isRemoveDisks() && hasImages) { if (!removeVmImages(null)) { return false; // We get here if we got imageDoesNotExistsInDomain for all the VM disks from VDSM. } else if (getReturnValue().getTaskIdList().isEmpty()) { endCommandWithoutTasks(); } } else { endCommandWithoutTasks(); } return true; }

Target:
no need for the "else" word..it's just makes the code more confusing in my opinion.
Source:
private boolean validateDestStorage(Guid imageId, Guid destDomainId) { DiskImage diskImage = getDiskImageById(imageId); Guid storagePoolId = diskImage.getStoragePoolId().getValue(); StorageDomainValidator validator = getValidator(destDomainId, storagePoolId); return validate(validator.isDomainExistAndActive()) && validate(validator.domainIsValidDestination()); }

Target:
Why not using getStoragePoolId() instead fetching it from the disk
Source:
public MockEJBStrategyRule(Map<BeanType, Object> beans) { this(beans, new EnumMap<ContainerManagedResourceType,Object>(ContainerManagedResourceType.class));; }

Target:
You have an extra semicolon at the end here.
Source:
boolean validateVdsGroup() { if (getVdsGroup() == null) { return failCanDoAction(VdcBllMessages.VDS_CLUSTER_IS_NOT_VALID); } return true; }

Target:
please set a modifier - protected seem suitable
Source:
boolean isGlusterSupportEnabled() { return getVdsGroup().supportsGlusterService() && getParameters().isGlusterPeerProbeNeeded(); }

Target:
use protected access modifier instead of default (all-over)
Source:
private Provider getDeletedProvider() { if (deletedProvider == null) { deletedProvider = getDbFacade().getProviderDao().get(getParameters().getProvider().getId()); } return deletedProvider; }

Target:
why not encapsulate with getProviderDao() and not getDbFacade().getProviderDao() ?
Source:
public String getValue() { final StringBuilder val = new StringBuilder(); if (this.major > -1) val.append(this.major); appendVersionComponent(val, this.minor); appendVersionComponent(val, this.build); appendVersionComponent(val, this.revision); return val.toString(); }

Target:
Why this is done outside the appendVersionComponent method? the logic looks same as other appended version parts.
Source:
static void appendVersionComponent(StringBuilder val, int versionNumber) { if (versionNumber > -1) { if (val.length() != 0) { val.append("."); } val.append(versionNumber); } }

Target:
Is there a reason to make it static? And why isn't it declared as private method?
Source:
public VDSReturnValue runVdsCommand(VDSCommandType commandType, VDSParametersBase parameters) throws VdcBLLException { VDSReturnValue returnValue = getBackendResourceManager().RunVdsCommand(commandType, parameters); if (!returnValue.getSucceeded()) { throw new VdcBLLException(returnValue.getVdsError().getCode(), returnValue.getVdsError() .getMessage()); } return returnValue; }

Target:
Should this be protected?
Source:
protected void copyVmDevices() { ArrayList<VmDevice> devices = new ArrayList<VmDevice>(vmFromConfiguration.getVmUnamagedDeviceList()); devices.addAll(vmFromConfiguration.getManagedVmDeviceMap().values()); VmDeviceUtils.copyVmDevices(getVmIdFromSnapshot(), getVmId(), vmFromConfiguration, vmFromConfiguration.getStaticData(), true, devices, newDiskImages, _vmInterfaces); }

Target:
devices can (and should) be defined as List<VmDevice> Also, I'd initialize the arraylist with FromConfiguration.getVmUnamagedDevic eList().size() + vmFromConfiguration.getManagedVmDeviceMap().size(), and then add both items, but it's a matter of taste.
Source:
public MainTabBasicDetailsView(ApplicationResources resources) { operatingSystem = new EnumLabel<VmOsType>(); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); Driver.driver.initialize(this); ViewIdHandler.idHandler.generateAndSetIds(this); }

Target:
In this case you don't need to create the instance by yourself - remove the (provided = true) from the declaration, remove this operatingSystem = new EnumLabel<VmOsType>(); completely and than MainTabBasicDetailsView.ui.xml declare a new namespace like: xmlns:l="urn:import:org.ovirt.engine.ui.common.widget.label" and than you can replace <g:ValueLabel ui:field="operatingSystem"... by <l:EnumLabel ui:field="operatingSystem" ...
Source:
public String toString() { StringBuilder builder = new StringBuilder(50); builder.append("commandId: "); //$NON-NLS-1$ builder.append(getCommandId()); builder.append(", user: "); //$NON-NLS-1$ builder.append(getParametersCurrentUser().getUserName()); builder.append(", commandType: "); //$NON-NLS-1$ builder.append(getCommandType()); return builder.toString(); }

Target:
Can't this cause NPE? what is the user in case of internal command?
Source:
private void debugAction(VdcActionType actionType, VdcActionParametersBase params) { if(log.isDebugEnabled()) { StringBuilder builder = new StringBuilder(50); builder.append("Action type: "); //$NON-NLS-1$ builder.append(actionType); builder.append(", Parameters: "); //$NON-NLS-1$ builder.append(params); } }

Target:
missing "log.debug(builder.toString());"?
Source:
private Guid getQuotaIdForDisk(DiskImage diskImage) { // If the DiskInfoDestinationMap is available and contains information about the disk if (getParameters().getDiskInfoDestinationMap() != null && getParameters().getDiskInfoDestinationMap().get(diskImage.getId()) != null) { return getParameters().getDiskInfoDestinationMap().get(diskImage.getId()).getQuotaId(); } else { return diskImage.getQuotaId(); } }

Target:
consider removing else clause
Source:
private Locale getLocaleFromCookies(final Cookie[] cookies) { Locale locale = null; if (null != cookies) { for (Cookie cookie: cookies) { if (LOCALE.equalsIgnoreCase(cookie.getName())) { locale = LocaleUtils.getLocaleFromString(cookie.getValue()); break; } } } return locale; }

Target:
Minor thing: please use "something <operator> null" convention.
Source:
public void setMigrationMode(MigrationSupport value) { for (Object migrationModeEntityModel : getMigrationMode().getItems()) { if (((EntityModel)migrationModeEntityModel).getEntity() == value) { getMigrationMode().setSelectedItem(migrationModeEntityModel); break; } } }

Target:
not needed after using Enum...
Source:
public static void GetVmsRunningOnOrMigratingToVds(AsyncQuery aQuery, Guid id) { aQuery.converterCallback = new IAsyncConverter() { @Override public Object Convert(Object source, AsyncQuery _asyncQuery) { ArrayList<VM> vms = (ArrayList<VM>) source; return vms; } }; Frontend.RunQuery(VdcQueryType.GetVmsRunningOnOrMigratingToVds, new GetVmsRunningOnOrMigratingToVdsParameters(id), aQuery); }

Target:
this convert should do some logic (e.g. if the source is null than return emtpy list or something like this). Here it would be enough just to "return source;" or have no converter at all.
Source:
private boolean managementNetworkModifiedCorrectly(VdsNetworkInterface iface) { if (!Config.<String> GetValue(ConfigValues.ManagementNetwork).equals(iface.getNetworkName())) { return true; } if (iface.getBootProtocol() == NetworkBootProtocol.STATIC_IP && vds.getHostName().matches(ValidationUtils.IP_PATTERN)) { return StringUtils.equals(vds.getHostName(), iface.getAddress()); } return true; }

Target:
I don't think this check should be inside, rather outside in the if that is calling this method. Also, how about extracting this to method in NetworkUtils (there is already a very similar method there isManagementNetwork(Network) that you can extract a method isManagementNetwork(String) method from)?
Source:
protected Guid getUpServerId() { if (brick == null) { return super.getUpServerId(clusterId); } VDS brickServer = getVdsDao().get(brick.getServerId()); if (brickServer.getStatus() == VDSStatus.Up) { return brickServer.getId(); } // brick server is down return super.getUpServerId(clusterId); }

Target:
does super ref needed here?
Source:
private GlusterVolumeAdvancedDetails fetchAdvancedDetails(String volumeName) { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetGlusterVolumeAdvancedDetails, new GlusterVolumeAdvancedDetailsVDSParameters(getUpServerId(), clusterId, volumeName, brick.getQualifiedName(), detailRequired)); return (GlusterVolumeAdvancedDetails) returnValue.getReturnValue(); }

Target:
NPE possible here - as brick could be null. I think if brick is null, null should be passed to the method, so that advanceddetails of all bricks are fetched?
Source:
private boolean networkRequiredOnVds(VmNetworkInterface vmIface, Map<String, Network> networksByName, boolean onlyRequiredNetworks) { boolean networkRequiredOnVds = true; if (!vmIface.isPlugged()) { networkRequiredOnVds = false; } else if (onlyRequiredNetworks) { Network network = networksByName.get(vmIface.getNetworkName()); networkRequiredOnVds = network.getCluster().isRequired() && network.isVmNetwork(); } return networkRequiredOnVds; }

Target:
How does this make sense? How can you have non-vm network on a vNIC? I think this scenario should be blocked and not allowed to arrive to this state elsewhere.
Source:
public VdsNotRespondingTreatmentCommand(T parameters) { super(parameters); mVmList.addAll(getVmDAO().getAllMigratingToHost(getVdsId())); }

Target:
is there an option to move this from the ctor to other place? maybe even execute? its not a must but it feels not related to the ctor
Source:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } List<VmDevice> watchdogs = getVmDeviceDao().getVmDeviceByVmIdAndType(getParameters().getVmId(), VmDeviceType.WATCHDOG.getName()); if (watchdogs.isEmpty()) { return failCanDoAction(VdcBllMessages.WATCHDOG_NOT_FOUND); } return super.canDoAction(); }

Target:
you are calling super.canDoAction twice, i guess here it should be return true
Source:
protected void buildVmWatchdog() { throw new NotImplementedException("not implemented"); // Not supported in old code }

Target:
why throwing exception?
Source:
protected void executeCommand() { List<VmDevice> watchdogs = getWatchdogs(); VmDevice watchdogDevice = watchdogs.get(0); // there must be only one watchdogDevice.setSpecParams(getSpecParams()); getVmDeviceDao().update(watchdogDevice); setActionReturnValue(watchdogDevice); setSucceeded(true); }

Target:
setSucceeded(true) is enough in update command.
Source:
protected WatchDog doPopulate(WatchDog model, VmWatchdog entity) { model.setAction(entity.getAction() == null ? null : entity.getAction().name()); model.setModel(entity.getModel() == null ? null : entity.getModel().name()); model.setId(entity.getId().toString()); return model; }

Target:
doPopulate() is used to execute additional queries to complete the entity, while what you did should reside in the WatchDogMapper.
Source:
protected <T> boolean matchEntity(VmWatchdog entity, T id) { //since there can be only one return true; }

Target:
even if it's true, why not just ---> return entity.getId().equals(id); why to cut corners?
Source:
private CommandManager() { executionContextMap = CacheProviderFactory.<NGuid, ExecutionContext>getCacheWrapper(EXECUTION_CONTEXT_MAP_NAME); commandMap = CacheProviderFactory.<NGuid, CommandEntity>getCacheWrapper(COMMAND_MAP_NAME); }

Target:
Bare in mind that for External task injection feature, Eli is going to introduce a map from jobId to ExecutionContext. In addition, if ExecutionContext gets evicted (due to LFU - btw, should this be LFU or LRU? ) - how are we going to restore the context due to "cache miss"? can you please elaborate?
Source:
private String getFullPath(final String path) { String result = null; if (ServletUtils.isSane(path)) { List<BrandingTheme> brandingPaths = brandingManager. getBrandingThemes(); for (BrandingTheme brandingTheme: brandingPaths) { if (path.startsWith(brandingTheme.getPath())) { result = brandingManager.getBrandingRootPath(). getAbsolutePath() + path; } } } else { log.error("The path \"" + path //$NON-NLS-1$ + "\" is not sane"); //$NON-NLS-1$ } return result; }

Target:
Instead of iterating over List<BrandingTheme> on every request, you can use Map<String, BrandingTheme> - mapping brandingTheme.getPath() to corresponding BrandingTheme instance. This is to avoid O(n) access due to iteration, in favor of O(1) access due to map value access, with regard to appropriate BrandingTheme instance.
Source:
protected MessageDigest getMd5Digest(final HttpServletRequest request) throws NoSuchAlgorithmException { MessageDigest digest = createMd5Digest(); for (MD5Attributes attribute: MD5Attributes.values()) { if (request.getAttribute(attribute.getAttributeKey()) != null) { digest.update(request.getAttribute(attribute.getAttributeKey()). toString().getBytes()); } } return digest; }

Target:
Excellent change! +1
Source:
public BrandingManager(final File etcDir) { brandingRootPath = new File(etcDir + BRANDING_PATH); }

Target:
new File(etcDir, BRANDING_PATH) and remove / from BRANDING_PATH
Source:
public KeyMaker(String vmId, ConsoleContext context) { super(); this.vmId = vmId; this.context = context; }

Target:
no need to call super
Source:
protected boolean isVmNotLocked() { return getVmId() != null && validate(new VmValidator(getVm()).vmNotLocked()); }

Target:
even after getVmId() is checked, getVm() can return null here and cause to NPE.
Source:
protected boolean canDoAction() { disk = getDiskDao().get(getParameters().getDiskId()); return isVmExist() && isVmInUpPausedDownStatus() && isDiskExist(disk) && checkCanPerformPlugUnPlugDisk() && isVmNotInPreviewSnapshot() && isVmNotLocked(); }

Target:
it's already checked that the vm is up/paused/down in line 45..so you will never reach here with the vm locked.
Source:
protected Version getStoragePoolClusterLevel(Guid StoragePoolId) { StoragePool storagePool = DbFacade.getInstance().getStoragePoolDao().get(StoragePoolId); if (storagePool != null) { return storagePool.getcompatibility_version(); } else { log.errorFormat( "IrsBroker::getStoragePoolClusterLevel:: Could not find master domain for pool {0} !!!", getParameters().getStoragePoolId()); return null; } }

Target:
Would be awesome if you add a method of getStoragePoolDao() that will return DbFacade.getInstance().getStoragePoolDao. I promised you an explanation on why , and I will provide it (it will make mocking life easier, and a better step towards Dependency injection).
Source:
public void edit(final HostBondInterfaceModel object) { super.edit(object); // hide widgets info.setVisible(false); message.setVisible(false); checkConnectivity.setVisible(false); commitChanges.setVisible(false); // resize layoutPanel.remove(infoPanel); layoutPanel.setWidgetSize(mainPanel, 300); asPopupPanel().setPixelSize(400, 400); }

Target:
Redundant, you already did getCheckConnectivity().setIsAvailable(false) in SetupNetworksBondPopupView
Source:
private void checkEntityForRollback(BusinessEntity<?> entity) { if(entity == null) { throw new IllegalArgumentException("Can not create snapshot from a null entity"); } Class<? extends BusinessEntity> entityClazz = entity.getClass(); if(DbFacade.getInstance().getDaoForEntity((Class<BusinessEntity<Serializable>>)entityClazz) == null) { throw new IllegalArgumentException("There is no rollback DAO registered for entity type "+entityClazz.getName()); } }

Target:
I'd call the variable entityClass
Source:
public Object mapFromContext(Object ctx) { if (ctx == null) { return null; } DirContextAdapter searchResult = (DirContextAdapter) ctx; Attributes attributes = searchResult.getAttributes(); if (attributes == null) { return null; } try { return attributes.get("uid").get(0); } catch (NamingException e) { System.err.println(ERROR_PREFIX + "Failed getting user GUID"); return null; } }

Target:
Please replace this ^ with "log.error(...)".
Source:
public void setTotalDiskSize(Integer value) { value = (value == null) ? new Integer(0) : value; if (!totalDiskSize.equals(value)) { totalDiskSize = value; } }

Target:
This will produce a Number Constructor FindBugs warning. Please use Integer.valueOf(0)
Source:
private static Double assignDoubleValueWithNullProtection(XmlRpcStruct input, String name) { Double doubleValue = AssignDoubleValue(input, name); return (doubleValue == null ? new Double(0.0) : doubleValue); }

Target:
Here too - use Double.valueOf(0.0)
Source:
public GetQuotaByQuotaIdQueryParameters(Guid quotaId) { this(); this.quotaId = quotaId; }

Target:
Remove the call to this();
Source:
public Guid persistAsyncTaskPlaceHolder(VdcActionType parentCommand) { Guid retValue = Guid.Empty; try { AsyncTasks task = createAsyncTask(new AsyncTaskCreationInfo(), parentCommand); retValue = task.getTaskId(); AsyncTaskUtils.addOrUpdateTaskInDB(task, null, EMPTY_GUID_ARRAY); } catch (RuntimeException ex) { log.errorFormat("Error during persistAsyncTaskPlaceHolders for command: {0}. Exception {1}", this.getClass().getName(), ex); } return retValue; }

Target:
"this" here is redundant.
Source:
public void Cluster_SelectedItemChanged() { UpdateDefaultHost(); updateCustomPropertySheet(); UpdateMinAllocatedMemory(); UpdateNumOfSockets(); if ((VmTemplate) getModel().getTemplate().getSelectedItem() != null) { VmTemplate template = (VmTemplate) getModel().getTemplate().getSelectedItem(); updateQuotaByCluster(template.getQuotaId(), template.getQuotaName()); } updateCpuPinningVisibility(); }

Target:
redundant cast
Source:
protected void ExecuteVdsBrokerCommand() { status = getBroker().desktopLogoff(mVmId.toString(), (Boolean.valueOf(mForce)).toString()); ProceedProxyReturnValue(); }

Target:
Instead of using Boolean.valueOf(boolean).toString(), just use String.valueOf(boolean)
Source:
protected void ExecuteVdsBrokerCommand() { if (getParameters().getGracefully()) { status = getBroker().shutdown(getParameters().getVmId().toString(), (Integer.valueOf(getParameters().getSecondsToWait())).toString(), Config.<String> GetValue(ConfigValues.VmGracefulShutdownMessage)); } else { status = getBroker().destroy(getParameters().getVmId().toString()); } ProceedProxyReturnValue(); }

Target:
Instead of Integer.valueOf(int).toString(), just use String.valueOf(int)
Source:
private static void addBootOrder(VmDevice vmDevice, Map<String, Object> struct) { String s = Integer.valueOf(vmDevice.getBootOrder()).toString(); if (!org.apache.commons.lang.StringUtils.isEmpty(s) && !s.equals("0")) { struct.put(VdsProperties.BootOrder, s); } }

Target:
Instead of Integer.valueOf(int).toString(), just use String.valueOf(int)
Source:
public void setLunId(String value) { if (!privateLunId.equals(value)) { privateLunId = value; onPropertyChanged(new PropertyChangedEventArgs("LUN ID")); //$NON-NLS-1$ } }

Target:
nullity check here too :)
Source:
private boolean isEntityModelEmpty(EntityModel model) { return !(model.getEntity() != null && !model.getEntity().equals("")); }

Target:
Save the null check: !"".equals(model.getEntity())
Source:
private void handleError(Exception e, VDSStatus status) { log.errorFormat( "Host installation failed for host {0}, {1}.", getVds().getId(), getVds().getName(), e ); setVdsStatus(status); setSucceeded(false); _failureMessage = getErrorMessage(e.getMessage()); addCustomValue("FailedInstallMessage", _failureMessage); }

Target:
Since you already extracted this code, you should notice that this line is redundant and already done on line 80. Also the getError message on the line above is done on line 80 anyway.. For your consideration
Source:
public void setManagementNetwork(String managementNetwork) { this._managementNetwork = managementNetwork; }

Target:
Why do you need "this." ?
Source:
public static String combine(String head, List<ParametersSet> params) { StringBuilder combined_params = new StringBuilder(""); if (params != null) { for (ParametersSet ps : params) { for (Parameter param : ps.getParameters()) { combined_params.append(String.format(MATRIX_PARAMETER_TEMPLATE, param.getName(), param.getValue())); } } } combined_params.insert(0, head); return combined_params.toString(); }

Target:
The empty string in the constructor is redundant.
Source:
String getFormattedNote() { StringBuilder formattedNote = new StringBuilder(constants.empty()); for (int i = 0; i < notes.size(); i++) { String note = notes.get(i); formattedNote.append(constants.lineBreak()); formattedNote.append(constants.htmlTab()); formattedNote.append(note); } return formattedNote.toString(); }

Target:
Consider doing this in a single line: formattedNote.append(constants.lineBreak().append(constants.htmlTab().append(note);
Source:
public BootSequence getSequence() { StringBuilder str = new StringBuilder(""); //$NON-NLS-1$ for (EntityModel a : getItems()) { if (a.getIsChangable()) { BootSequence bs = (BootSequence) a.getEntity(); str.append(bs.toString()); } } return !str.equals("") ? BootSequence.valueOf(str.toString()) : null; //$NON-NLS-1$ }

Target:
The empty string here is redundent
Source:
private void clearAsyncTasksWithOutVdsmId() { for (Guid asyncTaskId : getReturnValue().getAsyncTaskIdList()) { AsyncTasks task = DbFacade.getInstance().getAsyncTaskDao().get(asyncTaskId); if (task.getVdsmTaskId().equals(NGuid.Empty)) { AsyncTaskManager.failTaskWithoutVdsmId(task); } } }

Target:
/s/DbFacade.getInstance().getAsyncTaskDao()/getAsyncTaskDao
Source:
public HashCodeBuilder(final int prime) { super(); this.prime = prime; }

Target:
IMHO, the explicit Object constructor is redundant.
Source:
protected void revertTask() { // Preventing rollback on VmReplicateDiskFinish success // (checks whether the disk moved successfully to the target storage domain) Guid targetStorageDomainId = getEnclosingCommand().getParameters().getTargetStorageDomainId(); Guid destinationImageId = getEnclosingCommand().getParameters().getDestinationImageId(); DiskImage diskImage = getDiskImageDao().get(destinationImageId); if (diskImage != null && diskImage.getStorageIds().get(0) == targetStorageDomainId) { getEnclosingCommand().getParameters().setExecutionIndex(0); } }

Target:
Use equals - there is no guarantee that it's the same Guid instance.
Source:
public BootSequence getSequence() { StringBuilder str = new StringBuilder(); for (EntityModel a : getItems()) { if (a.getIsChangable()) { BootSequence bs = (BootSequence) a.getEntity(); str.append(bs.toString()); } } String bootStr = str.toString(); if (!bootStr.equals("")) { //$NON-NLS-1$ return BootSequence.valueOf(bootStr); } return null; }

Target:
Is it just for replacing the ternary if? why is it better?
Source:
public AuditLogType getAuditLogTypeValue() { return getSucceeded() ? (disksLeftInVm.isEmpty() ? AuditLogType.USER_REMOVE_VM_FINISHED : AuditLogType.USER_REMOVE_VM_FINISHED_WITH_ILLEGAL_DISKS) : AuditLogType.USER_FAILED_REMOVE_VM; }

Target:
Remove VM will always take place audit log should be removed
Source:
public void testMemoryMapping() { VDS vds = new VDS(); vds.setId(Guid.Empty); vds.setPhysicalMemMb(4000); Host host = HostMapper.map(vds, (Host) null); assertNotNull(host.getMemory()); assertEquals(host.getMemory().longValue(), 4194304000L); }

Target:
potential NPE, host.getMemory() can be NULL instead please remove Long.valueOf() from host.getMemory() and make Long from 4194304000L.
Source:
protected void updateModelDataCenterFromVds(ArrayList<StoragePool> dataCenters, VDS vds) { if (dataCenters != null && vds.getStoragePoolId() != null) { getDataCenter().setItems(dataCenters); getDataCenter().setSelectedItem(Linq.firstOrDefault(dataCenters, new Linq.DataCenterPredicate(vds.getStoragePoolId()))); if (getDataCenter().getSelectedItem() == null) { getDataCenter().setSelectedItem(Linq.firstOrDefault(dataCenters)); } } }

Target:
Why do you need to check- vds.getStoragePoolId() != null ?
Source:
protected void executeCommand() { VDSGroup vdsGroup = getVdsGroup(); boolean initSucceeded = true; if (vdsGroup.supportsTrustedService()) { setSucceeded(initTrustedService()); } if (vdsGroup.supportsVirtService()) { initSucceeded = initVirtResources(); } if (initSucceeded && vdsGroup.supportsGlusterService()) { initSucceeded = initGlusterHost(); } setSucceeded(initSucceeded); }

Target:
Done
Source:
public UrlValidation(String[] allowedSchemes) { if (allowedSchemes == null) { this.allowedSchemes.add(new String()); } else for (String scheme : allowedSchemes) { this.allowedSchemes.add(scheme.toLowerCase()); } }

Target:
Please format this code correctly. Enter and { after else.
Source:
private String getTemplateExclusiveLockMessage() { if (getVmTemplate() != null) { return new StringBuilder(VdcBllMessages.ACTION_TYPE_FAILED_TEMPLATE_IS_BEING_REMOVED.name()) .append(String.format("$TemplateName %1$s", getVmTemplate().getName())) .toString(); } return VdcBllMessages.ACTION_TYPE_FAILED_OBJECT_LOCKED.name(); }

Target:
if the template is null, the can-do-action checks will fail the command. so it might be better to check whether the template is null or not in #getExclusiveLocks(), and in case it is null to return null there, so that we won't even build the engine lock and acquire it.
Source:
private boolean isIsoVersionSupported(Version isoVersion, OVirtNodeInfo Info) { boolean result = false; Version supported = new Version(Info.minimumVersion); if (isoVersion.compareTo(supported) > 0) { result = true; } return result; }

Target:
Why have you removed the static?
Source:
private boolean isNewerVersion(Version isoClusterVersion) { VDS vds = getVdsByVdsId(getParameters().getVdsId()); Version vdsClusterVersion = vds.getVdsGroupCompatibilityVersion(); log.debugFormat( "vdsClusterVersion {0} isoClusterVersion {1}", vdsClusterVersion.toString(), isoClusterVersion.toString() ); return (vdsClusterVersion.getMajor() == isoClusterVersion.getMajor() && vdsClusterVersion.getMinor() <= isoClusterVersion.getMinor()); }

Target:
I think (or want to believe) that the .toString() is implicit when formatting, hence can be removed from here.
Source:
public static synchronized OVirtNodeInfo getInstance() { if (instance == null) { instance = new OVirtNodeInfo(); } return instance; }

Target:
please add sync protection, see EngineLocalConfig.
Source:
private Pattern getIsoPattern(OVirtNodeInfo info) { log.infoFormat("getIsoPatter - pattern [{0}]", info.pattern); String expectedPattern = info.pattern; if (isoPattern == null || !expectedPattern.equals(isoPattern.toString())) { isoPattern = Pattern.compile(expectedPattern); } return isoPattern; }

Target:
why have you removed the static?
Source:
public static VmPropertiesUtils getInstance() { if (vmPropertiesUtils == null) { synchronized (VmPropertiesUtils.class) { if (vmPropertiesUtils == null) { vmPropertiesUtils = new VmPropertiesUtils(); } } } return vmPropertiesUtils; }

Target:
While you're at it, fix the initialization here, same way as you did with the singleton for Device Custom Properties.
Source:
protected void executeCommand() { if (!(Guid.isNullOrEmpty(clusterId))) { performActionForServicesOfCluster(); } else if (!(Guid.isNullOrEmpty(serverId))) { performActionForServicesOfServer(); } }

Target:
what if the user provides both cluterId and serverId?. So you could swap the above comparisons.
Source:
public void canDoActionFails() { GlusterServiceParameters params = new GlusterServiceParameters(); params.setActionType("InvalidActionType"); cmd = spy(new ManageGlusterServiceCommand(params)); assertFalse(cmd.canDoAction()); params.setServiceType(ServiceType.SMB); cmd = spy(new ManageGlusterServiceCommand(params)); assertFalse(cmd.canDoAction()); params.setClusterId(null); params.setServerId(null); assertFalse(cmd.canDoAction()); }

Target:
You can move these to separate tests. You can also verify the error message returned from canDoAction
Source:
private void extendDiskImageSize() { lockImageInDb(); VdcReturnValueBase ret = getBackend().runInternalAction( VdcActionType.ExtendImageSize, createExtendImageSizeParameters(), ExecutionHandler.createDefaultContexForTasks(getExecutionContext()) ); if (ret.getSucceeded()) { getReturnValue().getTaskIdList().addAll(ret.getInternalTaskIdList()); } else { propagateInternalCommandFailure(ret); unlockImageInDb(); getReturnValue().setFault(ret.getFault()); } setSucceeded(ret.getSucceeded()); }

Target:
the CDA messages of the extend won't be displayed in the CDA phase.
Source:
public String[] getCompletion(String wordPart) { if (wordPart == null || wordPart.isEmpty()) { return EMPTY_COMPLETION_LIST; } List<String> list = new ArrayList<String>(); for (String osName : OsRepositoryImpl.INSTANCE.getOsNames().values()) { if (osName.startsWith(wordPart)) { list.add(osName); } } return list.toArray(new String[]{}); }

Target:
well, I would prefer list.toArray(new String[list.size()]) - you save one instance :)