auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public List<VdsNetworkInterface> getNics(Guid hostId) { if (!hostIdToNics.containsKey(hostId)) { VDS host = new VDS(); host.setId(hostId); NetworkConfigurator configurator = new NetworkConfigurator(host, commandContext); hostIdToNics.put(hostId, configurator.filterBondsWithoutSlaves(interfaceDao.getAllInterfacesForVds(hostId))); } return hostIdToNics.get(hostId); }

Target:
it seems, that filterBondsWithoutSlaves is not interrested in 'host' and neither in commandContext. we can make at least the method static — that's easy although ugly and goes against CDI. Better would be to move this method to different class. Please notice, that this class requires commandContext although it's only usage is this fake one. So doing this change will simplify this method, heal NetworkConfigurator, simplify this class constructor, and all descendants.
Source:
protected void loadVmInit() { if (!getVm().isInitialized() && getVm().getVmInit() == null) { VmHandler.updateVmInitFromDB(getVm().getStaticData(), false); } }

Target:
why we need to check for getVm().isInitialized() ?
Source:
protected Integer parseNodeInteger(XmlNode sourceNode, String string, Integer defaultValue) { XmlNode subNode = selectSingleNode(sourceNode, string, _xmlNS); if (subNode != null && subNode.innerText != null) { Integer ret = Integer.parseInt(subNode.innerText); return ret; } return defaultValue; }

Target:
please inline, no need for the 'ret' variable
Source:
public IntegerValidation() { super(Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.class); }

Target:
Here, you can simply call the other constructor: this(Integer.MIN_VALUE, Integer.MAX_VALUE);
Source:
protected void executeCommand() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getCompensationContext().snapshotEntity(getVmPool()); setPoolBeingDestroyed(); setPrestartedToZero(); getCompensationContext().stateChanged(); return null; } }); setCommandShouldBeLogged(false); // disable logging at the end of command execution log(); // and log the message now stopVms(); if (allVmsDown) { getParameters().setTaskGroupSuccess(true); endSuccessfully(); } else { setSucceeded(true); } }

Target:
this line is redundant now that you call endSuccessfully directly
Source:
private StorageDomainSharedStatus getStorageDomainSharedStatus() { StorageDomainSharedStatus status = null; if (getStorageDomain() != null) { status = getStorageDomain().getStorageDomainSharedStatus(); } return status; }

Target:
You consider following syntax: return getStorageDomain() == null ? null : getStorageDomain().getStorageDomainSharedStatus()
Source:
protected void addStorageDomainStatusIllegalMessage() { addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2); StorageDomainStatus status = getStorageDomainStatus(); StorageDomainSharedStatus sharedStatus = getStorageDomainSharedStatus(); Object messageParameter; if (status == StorageDomainStatus.Unknown && sharedStatus != null) { // We got more informative information than "Unknown". messageParameter = sharedStatus; } else { messageParameter = status; } addCanDoActionMessageVariable("status", messageParameter); }

Target:
You can initialize messageParameter with status, i.e: Object messageParameter = getStorageDomainStatus(); And then do the check: if (messageParameter == Unknown && sharedStatus != null) { messageParameter = sharedStatus; } This way you can save the 'else' part. BTW, if the call to getStorageDomainSharedStatus() is expensive, you may want to save it by first validating that getStorageDomainStatus() is not Unknown: Object messageParameter = getStorageDomainStatus(); if (messageParameter == Unknown) { SDSharedStatus sharedStatus = getSDSharedStatus(); if (sharedStatus != null) { messageParameter = sharedStatus; } } addCanDo ...
Source:
public static EngineError forValue(int value) { return mappings.getOrDefault(value, ERROR_CODE_NOT_FOUND); }

Target:
getOrDefault was introduced in java 8 - this class is being compiled to gwt which supports 1.7. You should implement the behavior yourself.
Source:
private void initAllModels(boolean fetchFromBackend) { if (fetchFromBackend) { // run query for networks, this chains the query for nics, and also stops progress when done startProgress(); queryLabels(); queryVfMap(); } else { initLabelModels(); initNetworkModels(); initNicModels(); } }

Target:
queryLabels invokes a chain of queries that the final one initiates the class models. You should add your query to the chain (it can be the last one). Your query cannot be parallel to the chain since there is chance the chain will be finished before your query comes back. It will cause NPE in the models initialization since it assumes vfMap is not null.
Source:
protected boolean canDoAction() { final VM vm = getVm(); if (vm == null) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_VM_NOT_FOUND); } if (!canRunActionOnNonManagedVm()) { return false; } if (getVm().getStatus() != VMStatus.Up && getVm().getStatus() != VMStatus.PoweringUp) { return failVmStatusIllegal(); } return true; }

Target:
please inline (I see you'r'e using getVm() later on)
Source:
protected boolean runVm(Guid vmId, EngineLock lock) { return backend.runInternalAction( VdcActionType.RunVm, new RunVmParams(vmId), ExecutionHandler.createInternalJobContext(lock)).getSucceeded(); }

Target:
why did you reorder the methods? 1. it makes it harder to review the patch 2. methods that are not that interesting like getVmDynamicDao appear before the interesting methods in this class such as startFailedAutoStartVms
Source:
public boolean isStrict() { return value == STRICT.value ? true : false; }

Target:
sed 's/value == STRICT.value ? true : false/value == STRICT.value/' (Redundant inline if)
Source:
public static BondMode getBondMode(String bondOptions){ if(bondOptions == null){ return null; } String bondModeValue = findMode(bondOptions); if (bondModeValue == null){ return null; } for (BondMode bondMode : BondMode.values()){ if (bondMode.getValue().equals(bondModeValue)){ return bondMode; } } return null; }

Target:
It is still public. Why?
Source:
public static BondMode getBondMode(String bondOptions){ if(bondOptions == null){ return BOND0; } String bondModeValue = findMode(bondOptions); if (bondModeValue == null){ return BOND0; } for (BondMode bondMode : BondMode.values()){ if (bondMode.getValue().equals(bondModeValue)){ return bondMode; } } return BOND0; }

Target:
Please check if the are any usages of this method outside this class. If not, please make it private.
Source:
public CreateUserSessionParameters(String ssoToken, String profileName, String principalName, String principalId, String email, String sourceIp, List<Map> groupIds, boolean adminRequired) { setSsoToken(ssoToken); setProfileName(profileName); setPrincipalName(principalName); setPrincipalId(principalId); setEmail(email); // setSourceIp(sourceIp); setSourceIp("fe80::56ee:75ff:fe5c:6cc7"); setGroupIds(groupIds); setAdminRequired(adminRequired); }

Target:
please fix
Source:
private NetworkClusterDao getNetworkClusterDao() { return DbFacade.getInstance().getNetworkClusterDao(); }

Target:
The removal of the static causes the patch to fail compilation.
Source:
public Response add(SchedulingPolicy schedulingPolicy) { // Allow the usage of "policy" for backward-compatibility if (!schedulingPolicy.isSetName()){ schedulingPolicy.setName(schedulingPolicy.getPolicy()); } validateParameters(schedulingPolicy, "name"); return performCreate(VdcActionType.AddClusterPolicy, new ClusterPolicyCRUDParameters(null, map(schedulingPolicy)), queryIdResolver); }

Target:
This is done by the mapper, so we don't need to do it again here. In addition we don't need to support the "policy" attribute when adding scheduling policies, only when changing the policy of a cluster.
Source:
public boolean isEmptyOrNullAllowed() { return emptyOrNullAllowed; }

Target:
If we need this method for unit tests only, it can have default (package) visibility instead of public: boolean isEmptyOrNullAllowed() { ... }
Source:
public static Version getEffective(Version vmCustomCompatibilityVersion, Version vdsGroupCompatibilityVersion, Version defaultVersion) { if (vmCustomCompatibilityVersion != null) { return vmCustomCompatibilityVersion; } else if (vdsGroupCompatibilityVersion != null) { return vdsGroupCompatibilityVersion; } else { return defaultVersion; } }

Target:
I find it more readable as: if (vmCustomCompatibilityVersion != null) { return vmCustomCompatibilityVersion; } if (vdsGroupCompatibilityVersion != null) { return vdsGroupCompatibilityVersion; } return defaultVersion; please consider
Source:
private Guid getNewMacPoolId() { //TODO MM: this feels as duplicate to code in 'getPermissionCheckSubjects' but I'm not sure if // I can get null-valued storagePool elsewhere than in getPermissionSubjects. return getParameters().getStoragePool().getMacPoolId(); }

Target:
Why not using "getNewMacPoolId()" in getPermissionCheckSubjects as well (please notice there is also a null check- 'getParameters().getStoragePool() == null', please add it here as well).
Source:
protected void executeCommand() { // This will cache the snapshot names, avoiding '<UNKNOWN>' in the audit log upon command completion getSnapshotsNames(); if (isLiveMerge()) { getParameters().setLiveMerge(true); persistCommand(getParameters().getParentCommand(), true); } removeCinderSnapshotDisks(); setSucceeded(true); }

Target:
Is it mandatory? The names should be already cached upon calling 'addAuditLogCustomValues', which is invoked on CommandBase's execute flow (execute -> logCommand).
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof OpenstackNetworkProviderProperties)) { return false; } OpenstackNetworkProviderProperties other = (OpenstackNetworkProviderProperties) obj; return super.equals(obj) && Objects.equals(pluginType, pluginType) && Objects.equals(agentConfiguration, other.agentConfiguration); }

Target:
I guess you forgot "other." prefix
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof IconWithOsDefault)) return false; IconWithOsDefault other = (IconWithOsDefault) obj; return Objects.equals(icon, other.icon) && Objects.equals(osDefaultIcon, other.osDefaultIcon) && Objects.equals(smallIconId, other.smallIconId) && Objects.equals(validationResult, other.validationResult); }

Target:
missing { and }
Source:
public int hashCode() { return Objects.hash( forceMigrationForNonMigratableVm, getVmId(), targetVdsGroupId ); }

Target:
it is not that good - let's say I add a field in VmOperationParameterBase then I'll need to go over all the classes that inherit it to add the new field in their hashCode?
Source:
public void testInvalidParameterKey() { try { String key = "version=1;uuid=12345610-0000-0000-0000-000000000001"; DataMapKey deserializedParam = DataMapKey.deserialize(key); fail("InvalidParameterKeyException should have been raised"); } catch (InvalidPersistentMapKeyException e) { assertNotNull(e); } }

Target:
please use @Test(expected=InvalidPersistentMapKeyException.class) instead of try{} catch
Source:
private List<VM> getMigratableVmsRunningOnVds(final VmDao vmDao, final Guid hostId) { List<VM> vmsFromDB = vmDao.getAllRunningForVds(hostId); return vmsFromDB.stream() .filter( v -> v.getMigrationSupport() == MigrationSupport.MIGRATABLE // must not be pinned to the host && !v.getDedicatedVmForVdsList().contains(hostId) ).collect(Collectors.toList()); }

Target:
while on it can you please rename v to vm ?
Source:
protected void removeDiskFromDbCallBack(final CinderDisk cinderVolume) { final Snapshot updated; if (getParameters().isUpdateSnapshot()) { updated = getSnapshotWithoutCinderVolume(cinderVolume); } else { updated = null; } TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Object>() { @Override public Object runInTransaction() { removeDiskFromDb(cinderVolume, updated); return null; } }); }

Target:
consider ternary instead
Source:
public void setUp() throws Exception { super.setUp(); dao = dbFacade.getStorageServerConnectionLunMapDao(); StorageServerConnectionDao storageServerConnectionDao = dbFacade.getStorageServerConnectionDao(); StorageServerConnections existingConnection = storageServerConnectionDao.get("0cc146e8-e5ed-482c-8814-270bc48c297e"); StorageServerConnections newServerConnection = new StorageServerConnections(); newServerConnection.setid("0cc146e8-e5ed-482c-8814-270bc48c2980"); newServerConnection.setconnection(EXISTING_DOMAIN_STORAGE_NAME); existingLUNStorageMap = dao.get(new LUNStorageServerConnectionMapId("1IET_00180001", existingConnection.getid())); newLUNStorageMap = new LUNStorageServerConnectionMap(FREE_LUN_ID, existingConnection.getid()); }

Target:
newServerConnection seems completely redundant
Source:
private void initialize() { log.info("Start initializing {}", getClass().getSimpleName()); Integer backupCheckPeriodInHours = Config.<Integer>getValue(ConfigValues.BackupCheckPeriodInHours); // disable feature if value is negative if (backupCheckPeriodInHours > 0) { schedulerUtil.scheduleAFixedDelayJob(this, "backupCheck", new Class[] {}, new Object[] {}, backupCheckPeriodInHours, backupCheckPeriodInHours, TimeUnit.HOURS); log.info("Finished initializing {}", getClass().getSimpleName()); } lock = new ReentrantLock(); }

Target:
this is error prone: if the schedule will start the process before this line is executed, you'll face NPE in line 82. Please initialize the lock in the c'tor or when it is declared (line 52)
Source:
private long findUnusedMac() { int index = usedMacs.nextClearBit(startingLocationWhenSearchingForUnusedMac); boolean notFound = index == numberOfMacsInRange; if (notFound) { index = usedMacs.nextClearBit(0); } startingLocationWhenSearchingForUnusedMac = index + 1; return rangeStart + index; }

Target:
shouldn't it be- (index +1) % numberOfMacsInRange ?
Source:
public boolean isSchemaEnum(Type type) { for (Name name : SCHEMA_ENUMS) { if (name.toString().equals(type.getName().toString())) { return true; } } return false; }

Target:
The "Name" class implements correctly the "equals" method, so you can do just this: return SCHEMA_ENUMS.contains(type.getName());
Source:
private void startHostsWithPMInReboot(List<VDS> hosts) { final List<VDS> hostsWithPMInReboot = hosts.stream() .filter(host -> host.isPmEnabled() && host.getStatus() == VDSStatus.Reboot).collect(Collectors.toList()); if (hostsWithPMInReboot.size() > 0) { Runnable task = () -> { waitUntilFencingAllowed(); startHosts(hostsWithPMInReboot); }; ThreadPoolUtil.execute(task); } }

Target:
Why do we need temp variable? ThreadPoolUtil.execute(() -> { waitUntilFencingAllowed(); startHosts(hostsWithPMInReboot); });
Source:
public void setMessage(String message) { super.setMessage(message); // Hide table in case of message if (message != null && message.length() > 0) { table.setVisible(false); } if (message != null) { messageLabel.setText(message); } }

Target:
Shouldn't you just push this into the previous if? I don't see a point in setting the text of an empty string and not make it visible.
Source:
public String toString() { return Objects.toString(getFirst(), null) + '.' + Objects.toString(getSecond(), null); }

Target:
You can just use Objects.toString(getFirst()) and Objects.toString(getSecond()), it has the same behavior.
Source:
public RemoveMemoryVolumesParameters() { this.memoryVolumes = ""; this.vmId = Guid.Empty; this.forceRemove = false; }

Target:
I would drop that since it is false by default
Source:
private void update(List<VmNetworkInterface> interfaces) { if (interfaces != null && !interfaces.isEmpty()) { for (VmNetworkInterface ifc : interfaces) { VmNetworkStatistics stats = ifc.getStatistics(); vmManager.update(stats); } } }

Target:
If interfaces.isEmpty() the loop body will not be run, so this check is redundant.
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NetworkFilter that = (NetworkFilter) o; return Objects.equals(name, that.name) && Objects.equals(version, that.version) && Objects.equals(id, that.id); }

Target:
please configure your IDE to use brackets in equals methods around if statements. Those should be by convention present everywhere.
Source:
GetAllSupportedNetworkFiltersByVersionQuery(VersionQueryParameters parameters) { super(parameters); }

Target:
Why is it package private?
Source:
public String disableEffectsAsString() { StringBuilder disableEffectsBuffer = new StringBuilder(""); int countdown = getWanDisableEffects().size(); for (ConsoleOptions.WanDisableEffects disabledEffect : getWanDisableEffects()) { disableEffectsBuffer.append(disabledEffect.asString()); if (countdown != 1) { disableEffectsBuffer.append(", "); } countdown--; } return disableEffectsBuffer.toString(); }

Target:
if at it, i don't see the advantage of initializing the builder with an empty string. This seems to have no affect and the default c'tor can be used instead.
Source:
private Predicate<Constructor<?>> createConstructorInaccessibleFromPackagePredicate(Package sourcePackage) { return constructor -> { int constructorModifiers = constructor.getModifiers(); return Modifier.isPrivate(constructorModifiers) || (!sourcePackage.equals(constructor.getDeclaringClass().getPackage()) && !Modifier.isPublic(constructorModifiers)); }; }

Target:
I'd inline this and make it a single statement predicate
Source:
private static VideoRAMSettings selectVideoRAMSettings(VmBase vmBase) { Version clusterVersion = ClusterUtils.getCompatibilityVersion(vmBase); if(clusterVersion == null) { clusterVersion = Version.getLast(); } if (clusterVersion.greaterOrEquals(new Version(3, 6))) { return new VgamemVideoRAMSettings(); } else { return new LegacyVideoRAMSettings(); } }

Target:
clusterVersion can never be null - if there is no cluster (which is not likely to happen), then 3.0 is returned by ClusterUtils#getCompatibilityVersion so 124-126 is redundant - can be removed
Source:
boolean validate() { getTemplateName().validateEntity( new IValidation[] { new LengthValidation(BusinessEntitiesDefinitions.VM_TEMPLATE_NAME_SIZE), new I18NExtraNameOrNoneValidation() }); return getTemplateName().getIsValid(); }

Target:
please add 'public' prefix..
Source:
public void createMandatoryConstructorSignaturePredicate() { // Signature for a constructor that gets parameters and context objects. mandatoryConstructorSignature = createConstructorSignaturePredicate(VdcActionParametersBase.class, CommandContext.class); }

Target:
The members can be static and the methods @BeforeClass - this data doesn't change per test executed, and is read only.
Source:
protected void auditLog(AuditLogableBase logable, AuditLogType logType) { auditLogDirector.log(logable, logType); }

Target:
not related.
Source:
private void fillInUnsetIpConfigs() { for (NetworkAttachment networkAttachment : getParameters().getNetworkAttachments()) { if (networkAttachment.getIpConfiguration() == null) { IpConfiguration ipConfiguration = NetworkUtils.createDefaultIpConfiguration(); networkAttachment.setIpConfiguration(ipConfiguration); } } }

Target:
please replace with java8 stream.filter.forEach()
Source:
private NetworkFilter resolveVnicProfileDefaultNetworkFilter() { final Version dataCenterVersion = resolveDataCenterVersion(); NetworkFilter networkFilter = null; if (FeatureSupported.antiMacSpoofing(dataCenterVersion) && Config.<Boolean> getValue(ConfigValues.EnableMACAntiSpoofingFilterRules)) { networkFilter = networkFilterDao.getNetworkFilterByName(NetworkFilter.VDSM_NO_MAC_SPOOFING); } return networkFilter; }

Target:
there's no need for this variable in broad scope. If you want to define name for this value, define this variable inside of 'if'.
Source:
public ValidationResult validUseDefaultNetworkFilterFlag(boolean useDefaultNetworkFilterId) { return ValidationResult.failWith(EngineMessage.ACTION_TYPE_FAILED_INVALID_VNIC_PROFILE_NETWORK_ID_CONFIGURATION, ReplacementUtils.createSetVariableString(VAR_VNIC_PROFILE_NAME, vnicProfile.getName()), ReplacementUtils.createSetVariableString(VAR_NETWORK_FILTER_ID, vnicProfile.getNetworkFilterId())) .when(useDefaultNetworkFilterId & vnicProfile.getNetworkFilterId() != null); }

Target:
Please use && Done.
Source:
public boolean check(VM vm) { if (vm.getStatus() == VMStatus.Suspended || vm.getStatus() == VMStatus.SavingState || vm.getStatus() == VMStatus.RestoringState) { Version vmCustomCompatibilityVersion = vm.getCustomCompatibilityVersion(); return vmCustomCompatibilityVersion == null ? false // checked by isApplicable() : vmCustomCompatibilityVersion.greaterOrEquals(newClusterVersion); } return true; }

Target:
If VM's custom compatibility version is set, cluster's compatibility version is ignored. That means we don't need to display any warning, because nothing was changed for the VM.
Source:
protected List<Guid> getFailedVolumeIds(Guid spmVdsId) { return getParameters().getImageList().stream() .filter((volumeId) -> volumeExists(spmVdsId, volumeId)) .collect(toList()); }

Target:
The brackets around the left hand of the -> operator are redundant (and frankly, a bit confusing). Please remove them.
Source:
public static Collection<VdsNetworkInterface> findAllInterfaceBondNameIsEmpty(List<VdsNetworkInterface> items) { return where(items, new IPredicate<VdsNetworkInterface>() { @Override public boolean match(VdsNetworkInterface i) { return !StringHelper.isNullOrEmpty(i.getBondName()); } }); }

Target:
This method should return the interfaces with an empty bond name, you should remove the negation
Source:
protected Array createArrayOf(String typeName, Object[] array) { Connection connection = null; try { connection = getJdbcTemplate().getDataSource().getConnection(); return connection.createArrayOf(typeName, array); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (connection != null) { try { connection.close();} catch (SQLException e) } } }

Target:
the pool may keep it open of course which is the entire idea of course
Source:
public void setSpmMap(String spId, Host host) { spmMap.put(spId, host); }

Target:
you refer to spmMap with and without "this". Please be consistent.
Source:
public static void handleIoTune(VmDevice vmDevice, Guid diskProfileId, QosCache cache) { if (cache == null) { cache = new QosCache(); } Map<String, Long> ioTune = buildIoTune(diskProfileId, cache); if (ioTune == null) { return; } if (vmDevice.getSpecParams() == null) { vmDevice.setSpecParams(new HashMap<>()); } vmDevice.getSpecParams().put(VdsProperties.Iotune, ioTune); }

Target:
Maybe move it to "buildIoTune" method, where the cache is actually used. That way when the method is called there is no chance of it falling on null cache.
Source:
public static void flatGroups(ExtMap principal) { HashMap<String, ExtMap> accumulator = new HashMap<>(); flatGroups(principal, PrincipalRecord.GROUPS, accumulator); principal.put(PrincipalRecord.GROUPS, new ArrayList<>(accumulator.values())); }

Target:
Right, I missed that :-(
Source:
public void onSucceeded() { TransactionSupport.executeInNewTransaction(() -> { syncDbRecords(true); return null; }); log.info("Successfully merged snapshot '{}' images '{}'..'{}'", getDiskImage().getImage().getSnapshotId(), getDiskImage().getImageId(), getDestinationDiskImage() != null ? getDestinationDiskImage().getImageId() : "(n/a)"); }

Target:
if a transaction is started in all the calls to syncDbRecords(), it makes sense to move the transaction to the method itself (and if its unneeded avoid creating the transaction), that way the callers doesn't have to repeat and remember to use it instead of adding it to each call.
Source:
public boolean isVMWithMemoryCompatible(VM vm) { if (vm == null) { return true; } Version recentClusterVersion = vm.getClusterCompatibilityVersion(); // the cluster version in which the memory snapshot was taken Version originalClusterVersion = vm.getClusterCompatibilityVersionOrigin(); if (vm.getCustomCompatibilityVersion() != null) { return true; } return originalClusterVersion != null && recentClusterVersion.getMajor() == originalClusterVersion.getMajor() && recentClusterVersion.getMinor() == originalClusterVersion.getMinor(); }

Target:
how about to move line 439-441 to be before line 435 - not because of performance but to make it more clear that in this case we don't need the cluster version
Source:
private Network findCurrentNetwork(Map<Network, Set<Guid>> networks) { if (networks != null) { for (Map.Entry<Network, Set<Guid>> entry : networks.entrySet()) { Network current = entry.getKey(); ProviderNetwork providedBy = current.getProvidedBy(); if (Objects.equals(providedBy.getExternalId(), id)) { return current; } } } notFound(); // Will never be reached, as notFound throws a WebApplicationException return null; }

Target:
Done
Source:
public String localize(final String errorMsg, final Locale requestLocale) { String localizedErrorMsg = ""; ResourceBundle resourceBundle = getResourceBundle(requestLocale == null ? Locale.getDefault() : requestLocale); if (resourceBundle != null && resourceBundle.containsKey(errorMsg)) { localizedErrorMsg = resourceBundle.getString(errorMsg); } else if (!StringUtils.isEmpty(errorMsg)) { localizedErrorMsg = StringUtils.join(errorMsg.toLowerCase().split("[_]", -1), " "); } return localizedErrorMsg; }

Target:
Why don't we fallback to default locale initialized in constructor if we don't have translation for client locale? If we did then we wouldn't be forced to use this nasty split/join code ...
Source:
private synchronized ResourceBundle getResourceBundle(Locale locale) { try { if (!resourceBundlesByLocale.containsKey(locale)) { resourceBundlesByLocale.put(locale, ResourceBundle.getBundle(messageSource, locale)); } } catch (RuntimeException e) { log.error("File: '{}' could not be loaded: {}", messageSource, e.getMessage()); log.debug("Exception", e); } return resourceBundlesByLocale.get(locale); }

Target:
Hmm, just an idea: Wouldn't it be faster to load all messages for all existing locales at startup (IMO we don't have that many messages/locales to cause memory issue) than calling synchronized method for each translated message in each user request?
Source:
private void scanDisks() { StorageDomain storageDomain = getSelectedItem(); Frontend.getInstance().runAction(VdcActionType.ScanStorageForUnregisteredDisks, new StorageDomainParametersBase(storageDomain.getStoragePoolId(), storageDomain.getId())); }

Target:
check for null here
Source:
public PermissionsOperationsParameters(Permission permission, Guid targetId) { this.permission = permission; this.targetId = targetId; }

Target:
Why not reuse existing constructors? public PermissionsOperationsParameters(Permission permission, Guid targetId) { this(permission); this.targetId = targetId; }
Source:
public HostJobsReturnForXmlRpc(Map<String, Object> innerMap) { super(innerMap); Object temp = innerMap.get(JOBS_KEY); if (temp != null) { hostJobsInfo = (Map<String, Object>) innerMap.get(JOBS_KEY); } }

Target:
Why not : hostJobsInfo = (Map<String, Object>) temp;
Source:
private void removeUserRemovedNetworkAttachments(List<NetworkAttachment> existingNetworkAttachments) { for (Guid attachmentId : userRemovedNetworkAttachments) { networkAttachmentDao.remove(attachmentId); } // Remove the attachment from the existing attachments list for (Iterator<NetworkAttachment> iterator = existingNetworkAttachments.iterator(); iterator.hasNext();) { Guid networkAttachmentId = iterator.next().getId(); if (networkAttachmentId != null && userRemovedNetworkAttachments.contains(networkAttachmentId)) { iterator.remove(); break; } } }

Target:
all existing network attachments (returned from db) should have id set.
Source:
public boolean isSessionInUse(long sessionSeqId) { CommandStatus cmdStatus; for (Guid cmdId : CommandCoordinatorUtil.getCommandIdsBySessionSeqId(sessionSeqId)) { cmdStatus = CommandCoordinatorUtil.getCommandStatus(cmdId); if (cmdStatus == CommandStatus.NOT_STARTED || cmdStatus == CommandStatus.ACTIVE) { return true; } } if (!jobDao.getJobsBySessionSeqIdAndStatus(sessionSeqId, JobExecutionStatus.STARTED).isEmpty()) { return true; } return false; }

Target:
lines 25-29 can be simplified to: return !jobDao.getJobsBySessionSeqIdAndStatus(sessionSeqId, JobExecutionStatus.STARTED).isEmpty();
Source:
protected void setClientTokenProvider(Quantum client) { String tenantName = ((OpenstackNetworkProviderProperties) provider.getAdditionalProperties()).getTenantName(); KeystoneTokenProvider keystoneTokenProvider = new KeystoneTokenProvider(provider.getAuthUrl(), provider.getUsername(), provider.getPassword()); client.setTokenProvider(keystoneTokenProvider.getProviderByTenant(tenantName)); }

Target:
seems as unneeded cast
Source:
protected Map<String, String> createPortAllocationRuntimeProperties(Port port) { Map<String, String> runtimeProperties = super.createPortAllocationRuntimeProperties(port); runtimeProperties.put("plugin_type", ((OpenstackNetworkProviderProperties) provider.getAdditionalProperties()).getPluginType()); return runtimeProperties; }

Target:
seems as unneeded cast
Source:
public void testEnumReadMany() { V4Vm object = objectFromXml( "<vm>" + "<display_types>" + "<display_type>spice</display_type>" + "<display_type>VNC</display_type>" + "</display_types>" + "</vm>" ); List<V4VmDisplayType> expected = Arrays.asList(new V4VmDisplayType[]{V4VmDisplayType.SPICE, V4VmDisplayType.VNC}); assertThat(object.displayTypes(), is(expected)); }

Target:
Done
Source:
public final void updateSessionLastActiveTime(String sessionId) { if (StringUtils.isNotEmpty(sessionId) && isSessionExists(sessionId)) { setData(sessionId, SESSION_LAST_ACTIVE_TIME, new Date()); } }

Target:
Isn't the isSessionExists condition enough?
Source:
public void setSpicePluginImplEnabled(boolean enabled, String reason) { spicePluginImplRadioButton.setVisible(enabled);// Unsupported since 4.0 spicePluginImplRadioButton.setEnabled(enabled); if (!enabled) { spicePluginImplRadioButtonTooltip.setText(reason); } }

Target:
you need a different method for this - the fact if the plugin is supported in the browser or not is independent of the one if it is enabled in vdc_options. If it is enabled, it has to work the same way as it did before.
Source:
private Integer getAutoMaxBandwidthForCluster(Guid clusterId) { Integer qosBandwidth = getQosBandwidth(clusterId); if (qosBandwidth != null) { return qosBandwidth; } Integer linkSpeedBandwidth = getLinkSpeedBandwidth(clusterId); return linkSpeedBandwidth; }

Target:
please inline linkSpeedBandwidth
Source:
public void testReadBooleans() { V4Vm object = objectFromJson("{'properties': [false, true]}"); List<Boolean> expected = Arrays.asList(false, true); assertEquals(expected, object.properties()); }

Target:
Actually this should fail, because the input isn't a list of strings, and the type of "properties" is "String[]".
Source:
public void testReadBooleanList() { List<Boolean> expected = Arrays.asList(true, false); XmlReader reader = openReader("<action><value>true</value><value>false</value></action>"); reader.next(); List<Boolean> booleans = reader.readBooleans(); assertEquals(XMLStreamConstants.END_ELEMENT, reader.getEventType()); assertEquals("action", reader.getLocalName()); assertEquals(expected, booleans); }

Target:
These tests are OK, but I think we should have tests like the ones that you did for JSON, checking that the result is correct, not just that the cursor is positioned correctly.
Source:
protected void addVmToDb() { super.addVmToDb(); if (getVm().getOrigin() == OriginType.KVM) { ImportUtils.updateGraphicsDevices(getVm().getStaticData(), getStoragePool().getCompatibilityVersion()); VmDeviceDao dao = DbFacade.getInstance().getVmDeviceDao(); dao.saveAll(getVm().getStaticData().getManagedDeviceMap().values()); } }

Target:
you can simply call getVmDeviceDao instead
Source:
private ExtensionEntry(Properties props, File file) { this.file = file; this.name = props.getProperty( Base.ConfigKeys.NAME, String.format("__unamed_%1$03d__", extensionNameIndex++) ); this.enabled = Boolean.valueOf(props.getProperty(Base.ConfigKeys.ENABLED, "true")); this.isDefault = Boolean.valueOf(props.getProperty(Authn.ConfigKeys.DEFAULT.getUuid().getName(), "false")); }

Target:
Do we really need this? Can't we access extension configuration via its Properties instance, ie getContext().get(CONFIGURATION).getProperty(DEFAULT_PROFILE) ?
Source:
public static long getSnapshotMemorySizeInBytes(VM vm) { long videoRam = (long)VideoDeviceSettings.totalVideoRAMSizeMb(vm) * 1024 * 1024; return vm.getVmMemSizeMb() + 200 + videoRam; }

Target:
VM's memory size and the 200MB buffer should be converted to bytes as well
Source:
public void disableAutoSetHostname() { canAutoSetHostname = disableOnHostnameChanged ? canAutoSetHostname : false; }

Target:
it is correct but quite unusual... Please change to: if (!disableOnHostChanged) { canAutoSetHostname = false; }
Source:
public CpuVendor getVendor() { final CpuVendor cpuVendor = CpuVendor.fromFlags(privateFlags); if (cpuVendor != null) { return cpuVendor; } throw new RuntimeException("Unknown processor vendor. Flags: " + privateFlags); }

Target:
I find it similar to what you ask me about the 'null' architecture - in what scenario would we get to #101? don't we want to prevent things like that in validate method instead of throwing exception when it happens?
Source:
public VdsStatic() { serverSslEnabled = false; vdsStrength = 100; vdsSpmPriority = HOST_DEFAULT_SPM_PRIORITY; sshPort = DEFAULT_SSH_PORT; sshUsername = DEFAULT_SSH_USERNAME; name = ""; comment = ""; vdsType = VDSType.VDS; autoRecoverable = true; disablePowerManagementPolicy = false; pmKdumpDetection = true; hostProviderId = null; currentKernelCmdline = null; lastStoredKernelCmdline = null; }

Target:
why do we need to explicitly initialize them to null?
Source:
public int hashCode() { return Objects.hash( id, hostName, consoleAddress, name, otpValidity, pmEnabled, pmKdumpDetection, port, protocol, sshPort, sshUsername, serverSslEnabled, uniqueId, clusterId, vdsStrength, vdsType, disablePowerManagementPolicy, hostProviderId, hostProviderId, currentKernelCmdline, kernelCmdlineParsable, lastStoredKernelCmdline, kernelCmdlineIommu, kernelCmdlineKvmNested, kernelCmdlinePciRealloc, kernelCmdlineUnsafeInterrupts ); }

Target:
looks like a mistake, right?
Source:
protected Map<Guid, Integer> getGlusterVolumeHealInfo(VDS upServer, String volumeName) { VDSReturnValue result = runVdsCommand(VDSCommandType.GetGlusterVolumeHealInfo, new GlusterVolumeVDSParameters(upServer.getId(), volumeName)); if(result.getSucceeded()){ return (Map<Guid, Integer>) result.getReturnValue(); }else{ return Collections.emptyMap(); } }

Target:
why protected ?
Source:
public static boolean isHealingRequired(GlusterVolumeEntity volume) { for (GlusterBrickEntity brick : volume.getBricks()) { if (brick.getUnSyncedEntries() != null && brick.getUnSyncedEntries() > 0) { return true; } } return false; }

Target:
The Java accepted check for not empty is: !brick.getUnSyncedEntries().isEmpty()
Source:
private Network findCurrentNetwork(Map<Network, Set<Guid>> networks) { Network result = networks == null ? null : networks.keySet() .stream() .filter(network -> Objects.equals(network.getProvidedBy().getExternalId(), id)) .findFirst() .orElse(null); if (result == null) { // This will never return but always throw a WebApplicationException notFound(); } return result; }

Target:
This is really hard to read. Can you at least avoid the ternary operator?
Source:
protected boolean validateImages() { List<DiskImage> imagesToValidate = getDiskImagesToValidate(); DiskImagesValidator diskImagesValidator = new DiskImagesValidator(imagesToValidate); boolean isVmQualifiedForLMOrImagesNotIllegal = getVm().isQualifiedForLiveSnapshotMerge() || validate(diskImagesValidator.diskImagesNotIllegal()); return getParameters().isNeedsLocking() ? isVmQualifiedForLMOrImagesNotIllegal && validate(diskImagesValidator.diskImagesNotLocked()) : isVmQualifiedForLMOrImagesNotIllegal; }

Target:
return (!getParameters().isNeedsLocking() || validate(diskImagesValidator.diskImagesNotLocked())) && (getVm().isQualifiedForLiveSnapshotMerge() || validate(diskImagesValidator.diskImagesNotIllegal()));
Source:
private boolean validateClusterExistsForArchitecture(ArchitectureType architecture, StoragePool dataCenter) { if (!clusterArchitecturesInDataCenters.get(dataCenter.getId()).contains(architecture)) { showErrorPopup(constants.noClusterSupportingArchitectureInDC()); return false; } return true; }

Target:
- this can be null (at least in theory) since it is inited from a callback. Please either init it before or handle it here. - the clusterArchitecturesInDataCenters.get(dataCenter.getId()) also can return null in some rare cases, please handle also that case
Source:
public static int getCdDeviceIndex(String cdInterface) { if ("scsi".equals(cdInterface)) { return 0; } else if ("ide".equals(cdInterface)) { return 2; } else if ("sata".equals(cdInterface)) { return 0; } return -1; }

Target:
how about replacing it with switch-case statement?
Source:
public AuditLogType getAuditLogTypeValue() { this.addCustomValue("DiskAlias", getDiskImage().getDiskAlias()); return getSucceeded() ? AuditLogType.USER_REGISTER_DISK_FINISHED_SUCCESS : AuditLogType.USER_REGISTER_DISK_FINISHED_FAILURE; }

Target:
why do you need the "this."?
Source:
public Cluster getCluster(Guid clusterId) { return DbFacade.getInstance().getClusterDao().get(clusterId); }

Target:
change to getClusterDao()
Source:
private void createNewDiskId() { Guid diskId = !getParameters().isUsePassedDiskId() ? Guid.newGuid() : getParameters().getDiskInfo().getId(); getParameters().getDiskInfo().setId(diskId); if (!isFloatingDisk()) { getDiskVmElement().getId().setDeviceId(diskId); } }

Target:
please switch to positive if
Source:
public void removeDisk() { VdcReturnValueBase vdcReturnValue = Backend.getInstance().runInternalAction(VdcActionType.RemoveDisk, new RemoveDiskParameters(getParameters().getImageGroupID())); getReturnValue().getVdsmTaskIdList().addAll(vdcReturnValue.getInternalVdsmTaskIdList()); }

Target:
this line is unneeded.
Source:
protected void updateCurrentCd(String cdPath) { cdPath = cdPath.isEmpty() ? null : cdPath; VmHandler.updateCurrentCd(getVdsId(), getVm(), cdPath); }

Target:
what if cdPath is already null?
Source:
public OvfUpdateProcessHelper(VmDeviceUtils vmDeviceUtils) { Objects.requireNonNull(vmDeviceUtils); this.vmDeviceUtils = vmDeviceUtils; this.ovfManager = new OvfManager(); }

Target:
We should control the clients which call this class, I don't think we should have this validation here. If you do think it is necessary to check null value we should validate it in the client that calls this helper.
Source:
public ValidationResult validateAddProvider() { ValidationResult result = validatePluginType(); if (!result.isValid()) { return result; } if (!(result = validateAuthentication()).isValid()) { return result; } return super.validateAddProvider(); }

Target:
we should not care about LOC metric. We should care about expressions without side effect. ~~ Ideally if test should not have modify anything, unless actually needed. Please update result variable, and only after that proceed with testing it.
Source:
public void completeDefaultIpConfiguration(IpConfiguration ipConfiguration) { if (ipConfiguration.getIPv4Addresses().isEmpty()) { final IPv4Address ipv4Address = NetworkCommonUtils.createDefaultIpv4Address(); ipConfiguration.setIPv4Addresses(Collections.singletonList(ipv4Address)); } if (ipConfiguration.getIpV6Addresses().isEmpty()) { final IpV6Address ipv6Address = NetworkCommonUtils.createDefaultIpv6Address(); ipConfiguration.setIpV6Addresses(Collections.singletonList(ipv6Address)); } }

Target:
In case the 'ipConfiguration' is null, there will be NPE here.
Source:
public void refreshNetworks(ArrayList<VdcActionParametersBase> parameters) { if (!parameters.isEmpty()) { HostSetupNetworksParametersBuilder.updateParametersSequencing(parameters); runInternalMultipleActions(VdcActionType.PersistentHostSetupNetworks, parameters); } }

Target:
please make it protected
Source:
public NetworkAttachment createNetworkAttachment(Network network, HostNetworkQos hostNetworkQos) { NetworkAttachment networkAttachment = new NetworkAttachment(); networkAttachment.setId(Guid.newGuid()); networkAttachment.setHostNetworkQos(hostNetworkQos); networkAttachment.setNetworkId(network.getId()); return networkAttachment; }

Target:
Please make it private
Source:
public void setDefaultInterface() { Guid vmId = getVmId(); if (!Guid.isNullOrEmpty(vmId)) { getDiskInterface().setSelectedItem(getDisk().getDiskVmElementForVm(vmId).getDiskInterface()); } else { getDiskInterface().setSelectedItem(DiskInterface.VirtIO); } }

Target:
Let's have the if in the positive branch
Source:
private boolean isClusterLevelChange() { Version newVersion = getParameters().getClusterLevelChangeToVersion(); return newVersion != null && getVm().isRunningOrPaused() && (getVm().getCustomCompatibilityVersion() == null || !newVersion.equals(getVm().getCompatibilityVersion())); }

Target:
shouldn't the last part be (getVm().getCustomCompatibilityVersion() == null && !newVersion.equals(getVm().getCompatibilityVersion())) ?
Source:
private String getMethodName(String httpMethod) { if (httpMethod.equals("POST")) { return "add"; } if (httpMethod.equals("PUT")) { return "update"; } if (httpMethod.equals("GET")) { return "get"; } if (httpMethod.equals("DELETE")) { return "remove"; } return ""; //shouldn't reach here. }

Target:
Consider using a "switch" statement.
Source:
public String getPrettyName() { return prettyName == null ? "" : prettyName; }

Target:
We don't need that here, null is OK if pretty name was not specified.
Source:
public VMNamesListReturnForXmlRpc(Map<String, Object> innerMap) { status = new StatusForXmlRpc((Map<String, Object>) innerMap.get(STATUS)); Object[] vmNames = (Object[]) innerMap.get(VM_NAMES); if (vmNames != null) { vmNamesList = Arrays.asList(vmNames).stream().map(Objects::toString).collect(Collectors.toList()); } }

Target:
can use Arrays.stream(vmNames) instead of creating a list as intermediate step
Source:
public String getUrl() { return this.url; }

Target:
if you're gonna rebase this patch, please consider dropping those `this.` prefixes from getters.
Source:
public void testVmElementDiskPluggedStatus() { DiskVmElement dvePlugged = dao.get(new VmDeviceId(PLUGGED_DISK_ID, FixturesTool.VM_RHEL5_POOL_57)); assertTrue(dvePlugged.isPlugged()); DiskVmElement dveUnlugged = dao.get(new VmDeviceId(UNPLUGGED_DISK_ID, FixturesTool.VM_RHEL5_POOL_57)); assertFalse(dveUnlugged.isPlugged()); }

Target:
I'd have this in a different test. I'd also try to fetch the DiskVmElement of a floating disk and assert it returns null.
Source:
private List<StorageServerConnections> getConnections() { List<StorageServerConnections> connectionsList = new ArrayList<>(); for (int i = 0; i == NUMBER_OF_EXISTING_CONNECTIONS; i++) { StorageServerConnections conn = new StorageServerConnections(); conn.setId(Guid.newGuid().toString()); connectionsList.add(conn); } return connectionsList; }

Target:
This will create 0 connections. Didn't you mean < ?
Source:
private List<StorageServerConnections> getConnections() { List<StorageServerConnections> connectionsList = new ArrayList<>(); for (int i = 0; i <= NUMBER_OF_EXISTING_CONNECTIONS; i++) { StorageServerConnections conn = new StorageServerConnections(); conn.setId(Guid.newGuid().toString()); connectionsList.add(conn); } return connectionsList; }

Target:
This will create 4 connections and not 3. You either init the index with 1 or use '<'
Source:
private void lockImageInDb() { final DiskImage diskImage = getDiskImage(); TransactionSupport.executeInNewTransaction(() -> { getCompensationContext().snapshotEntityStatus(diskImage.getImage()); getCompensationContext().stateChanged(); diskImage.setImageStatus(ImageStatus.LOCKED); ImagesHandler.updateImageStatus(diskImage.getImageId(), ImageStatus.LOCKED); return null; }); }

Target:
This command is currently transactional (should it be transactional?), I guess it should be set to non transactional with compensation, so: 1. the stateChanged need to be called after the actual change 2. need to add the NonTransactive annotation 3. need to add empty constructor
Source:
private Map<String, Pair<String, String>> getSharedLocksForTemplateDisk() { initVmTemplateId(); return Collections.singletonMap(getVmTemplateId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.TEMPLATE, EngineMessage.VM_TEMPLATE_IS_LOCKED)); }

Target:
it is a bit unusual to init things in the getSharedLocks flow.. how about moving it to 'init' method? (need to check the VmEntityType there..)
Source:
public boolean isAlive() { return this == HostJobStatus.running || this == HostJobStatus.pending; }

Target:
Don't qualify with HostJobStatus: return this == running || this == pending
Source:
private boolean canRemoveVmPool(Guid vmPoolId) { return getVmPoolDao().getVmPoolsMapByVmPoolId(vmPoolId).size() == 0; }

Target:
while on it, how about changing to isEmpty?
Source:
public void activateClearance(StorageDomain storageDomain){ storageDomain.setDomainStatus(StorageDomain.DomainStatus.ACTIVE); updateStorageDomain(storageDomain); }

Target:
Possible NPE. In line 340 we could return null which would blow up here.
Source:
public MacPool getMacPoolForDataCenter(Guid dataCenterId, CommandContext commandContext) { final MacPool macPool; try { macPool = getMacPoolById(getMacPoolId(dataCenterId), commandContext); } catch (Exception e) { throw new IllegalStateException( String.format("An exception was thrown while retrieving the mac-pool for DC='%s'", dataCenterId), e); } return macPool; }

Target:
Done
Source:
private static IllegalStateException prepareNotFoundException(Guid macPoolId) { final String msg = String.format(INEXISTENT_POOL_EXCEPTION_MESSAGE, macPoolId); return new IllegalStateException(msg); }

Target:
private static? What is this good for? Don't use static at all (except for utility methods like in Math class) or static factories etc.
Source:
boolean validatePluginAction(String pluginName, boolean allowWhileLoading) { Plugin plugin = getPlugin(pluginName); if (plugin == null) { return false; } boolean isInitializingOrInUse = plugin.isInState(PluginState.INITIALIZING) || plugin.isInState(PluginState.IN_USE); boolean isLoading = plugin.isInState(PluginState.LOADING); return allowWhileLoading ? (isLoading || isInitializingOrInUse) : isInitializingOrInUse; }

Target:
how about return isInitializingOrInUse || (allowWhileLoading && isLoading); ?
Source:
public void testActionParameters() { hostService.setupNetworks() .modifiedBonds( hostNic() .name("bond0") .bonding( bonding() .options( option() .name("mode") .type("4") .build() ) .slaves( hostNic() .name("eth1") .build(), hostNic() .name("eth2") .build() ) .build() ) .build() ).send(); }

Target:
If I remember correctly this call to "build" isn't required, as the "options" method accepts an object and also a builder. If it is a builder it will call the "build" method internally. Same for the other calls to "build".
Source:
public CommandCallback getCallback() { if (getParameters().isUseCinderCommandCallback()) { return new ConcurrentChildCommandsExecutionCallback(); } return new SerialChildCommandsExecutionCallback(); }

Target:
return getParameters().isUseCinderCommandCallback() ? new ConcurrentChildCommandsExecutionCallback() : new SerialChildCommandsExecutionCallback();
Source:
public void onBrowserEvent(Context context, Element parent, GlusterVolumeEntity volume, SafeHtml tooltipContent, NativeEvent event, ValueUpdater<GlusterVolumeEntity> valueUpdater) { VolumeStatus status = GlusterVolumeUtils.getVolumeStatus(volume); if (BrowserEvents.CLICK.equals(event.getType()) && onClickCommand != null && (status == VolumeStatus.ALL_BRICKS_DOWN || status == VolumeStatus.SOME_BRICKS_DOWN)) { onClickCommand.execute(); } else { super.onBrowserEvent(context, parent, volume, tooltipContent, event, valueUpdater); } }

Target:
I think it would be better to always call super.onBrowserEvent, the click might do something in the super class as well.