auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void checkImageTarget() { // TODO: // This is a workaround until bz 1332019 will be merged // since KVM is currently the only source for which we use Libvirt streaming API. // Libvirt currently reports the actual disk size and the virtual one, // when using preallocated qcow2 on block domain the size that the Libvirt stream emits // can be larger then the actual size. if (getVm().getOrigin() == OriginType.KVM && getActionState() == CommandActionState.EXECUTE) { StorageDomain domain = storageDomainDao.get(getStorageDomainId()); for (DiskImage image : getVm().getImages()) { if (domain.getStorageType().isBlockDomain()) { image.setActualSizeInBytes(image.getSize()); } } } }

Target:
how about making it a bit more declarative: if (domain.getStorageType().isBlockDomain()) { getVm().getImages().forEach(image -> image.setActualSizeInBytes(image.getSize())); }
Source:
private void freeLockForValidationPassedCommands() { for (CommandBase<?> command : getCommands()) { if (command.getReturnValue().isValid()) { command.freeLock(); } } }

Target:
why not with stream API? will be cleaner
Source:
private boolean isSparsifyCommandAvailable() { ArrayList<Disk> disks = getSelectedItems() != null ? Linq.<Disk> cast(getSelectedItems()) : new ArrayList<Disk>(); for (Disk disk : disks) { if (isDiskLocked(disk) || (!isVmDown() && disk.getPlugged())) { return false; } } return true; }

Target:
just one space
Source:
public void setResourcesDir(File newResourcesDir) { this.resourcesDir = newResourcesDir; }

Target:
The purpose of naming it "new..." is to avoid the "this...", can you remove it?
Source:
public void testCannotUpdateOSNotSupportVirtioScsi() { prepareVmToPassValidate(); group.setCompatibilityVersion(Version.v4_0); when(command.isVirtioScsiEnabledForVm(any(Guid.class))).thenReturn(true); when(osRepository.getDiskInterfaces(any(Integer.class), any(Version.class))).thenReturn( new ArrayList<>(Collections.singletonList("VirtIO"))); ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_ILLEGAL_OS_TYPE_DOES_NOT_SUPPORT_VIRTIO_SCSI); }

Target:
you can drop the new ArrayList<>(...) surroundings. It's sufficient to return just the singletonList.
Source:
protected void setUpLogExpectations(boolean debug) throws Exception{ Field field = BaseBackendResource.class.getDeclaredField("log"); Logger logger = mock(Logger.class); when(logger.isDebugEnabled()).thenReturn(debug); setFinalStatic(field, logger); }

Target:
Please add a space before the curly bracket
Source:
public void cleanup() { networkProviderWidget.cleanup(); fenceAgentsEditor.cleanup(); proxySourceEditor.cleanup(); driver.cleanup(); }

Target:
shouldn't these fields be covered by the autogenerated driver.cleanup() method? (Since they are fields and implement HasCleanup interface)
Source:
public void cleanup() { labelsWidget.cleanup(); driver.cleanup(); }

Target:
same question here: shouldn't labelsWidget.cleanup() be included in the generated driver.cleanup()?
Source:
public void cleanup() { driver.cleanup(); vmDiskPopupWidget.cleanup(); }

Target:
same question here
Source:
public DataCenter reInitializeDataCenter(String dcId) throws RuntimeException { log.info("about to reinitialize dc"); DataCenter dataCenter = new DataCenter(); dataCenter.setId(dcId); updateDataCenter(dataCenter); return dataCenter; }

Target:
why public? Are we planning to use it outside of this class?
Source:
public StorageDomain recoverStorageDomain(String sdUUID) { log.info("about to recover SD {}", sdUUID); StorageDomain storageDomain = new StorageDomain(); storageDomain.setId(sdUUID); updateStorageDomain(storageDomain); return storageDomain; }

Target:
why public? Are we planning to use it outside of this class?
Source:
public void syncSearch(VdcQueryType vdcQueryType, VdcQueryParametersBase vdcQueryParametersBase) { AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object ReturnValue) { setItems((Collection<T>) ((VdcQueryReturnValue) ReturnValue).getReturnValue()); } }; vdcQueryParametersBase.setRefresh(getIsQueryFirstTime()); Frontend.getInstance().runQuery(vdcQueryType, vdcQueryParametersBase, _asyncQuery); setIsQueryFirstTime(false); }

Target:
Why isn't this protected like in the master patch?
Source:
public String get(String macPoolId, String macPoolName) { if (macPoolId != null) { return macPoolId; } if (macPoolName != null) { MacPool macPoolByName = callerResource.getEntity(MacPool.class, VdcQueryType.GetMacPoolByName, new NameQueryParameters(macPoolName), null, true); if (macPoolByName != null) { return macPoolByName.getId().toString(); } } return null; }

Target:
I guess this should be requestedMacPoolName rather then null, as it's used for a failure reporting.
Source:
public ValidationResult isOsSupportedForVirtIoScsi(VM vm) { if (!VmValidationUtils.isDiskInterfaceSupportedByOs( vm.getOs(), vm.getCompatibilityVersion(), DiskInterface.VirtIO_SCSI)) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_GUEST_OS_VERSION_IS_NOT_SUPPORTED); } return ValidationResult.VALID; }

Target:
Can be private.
Source:
public void updateVirtioScsiController(VmBase vm, Boolean isVirtioScsiEnabled) { if (isVirtioScsiEnabled == null) { return; //we don't want to update the device } if (isVirtioScsiEnabled) { if (!hasVirtioScsiController(vm.getId())) { addVirtioScsiController(vm); } } else { removeVirtioScsiControllers(vm.getId()); } }

Target:
yes, I agree, before this method is called, you need to remove the controllers first.
Source:
public SysprepVmTemplateParameters(Guid vmTemplateId) { this.vmTemplateId = vmTemplateId; }

Target:
VmTemplateParameters also contains the id, can pass that to it and drop it from this class
Source:
private MethodExpression removePrefix(MethodExpression expression) { return expression.getMethod().getWords().get(0).equals(MANDATORY) || expression.getMethod().getWords().get(0).equals(OPTIONAL) ? (MethodExpression)expression.getParameters().get(0) : expression; }

Target:
Same than before, consider making "OPTINAL" a "Name".
Source:
public static String or(Object... params) { return ""; }

Target:
Why "String" and not "Object"?
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof DnsResolverConfiguration)) { return false; } DnsResolverConfiguration that = (DnsResolverConfiguration) o; return Objects.equals(getNameServers(), that.getNameServers()); }

Target:
Why the 'id' is not part of the equals?
Source:
public NameServer flush() { return new NameServer(this.nameServerEntity.getEntity()); }

Target:
Please remove the "this".
Source:
public DnsConfigurationWidget() { setDnsConfigurationEditor = new EntityModelCheckBoxEditor(Align.RIGHT); initWidget(WidgetUiBinder.uiBinder.createAndBindUi(this)); WidgetIdHandler.idHandler.generateAndSetIds(this); driver.initialize(this); setDnsConfigurationEditor.setLabel(constants.setDnsConfigurationLabel()); }

Target:
Please use prefered declarative approach - attribute in *.ui.xml
Source:
private static AddDiskParameters createParameters() { DiskImage image = new DiskImage(); DiskVmElement dve = new DiskVmElement(null, vmId); dve.setDiskInterface(DiskInterface.IDE); dve.setUsingScsiReservation(true); return new AddDiskParameters(dve, image); }

Target:
Why? You already set the value in each of the three tests that you changed here. I think that this line should be removed.
Source:
public void testIscsiLunCanBeAdded() { LunDisk disk = createISCSILunDisk(); command.getParameters().setDiskInfo(disk); DiskVmElement dve = new DiskVmElement(); command.getParameters().getDiskVmElement().setUsingScsiReservation(false); assertTrue("checkIfLunDiskCanBeAdded() failed for valid iscsi lun", command.checkIfLunDiskCanBeAdded(spyDiskValidator(disk))); }

Target:
Looks redundant - please remove.
Source:
private DiskVmElement createDiskVmElementUsingScsiReserevation() { DiskVmElement dve = new DiskVmElement(); dve.setUsingScsiReservation(true); return dve; }

Target:
Should be static
Source:
public void canDisableVirtioScsiFail() { Disk disk = new DiskImage(); DiskVmElement dve = new DiskVmElement(disk.getId(), vm.getId()); dve.setDiskInterface(DiskInterface.VirtIO_SCSI); disk.setDiskVmElements(Collections.singletonList(dve)); when(DbFacade.getInstance().getVmNetworkInterfaceDao()).thenReturn(vmNetworkInterfaceDao); assertThat(validator.canDisableVirtioScsi(Collections.singletonList(disk)), failsWith(EngineMessage.CANNOT_DISABLE_VIRTIO_SCSI_PLUGGED_DISKS)); }

Target:
huh?
Source:
public CommandCallback getCallback() { if (isDataOperationsByHSM()){ return new ConcurrentChildCommandsExecutionCallback(); } return null; }

Target:
you can inline that- return isDataOperationsByHSM() ? new .. : null;
Source:
public void endTaskStep(Guid stepId, JobExecutionStatus exitStatus) { try { if (stepId != null) { Step step = jobRepository.getStep(stepId); if (step != null) { step.setProgress(100); step.markStepEnded(exitStatus); jobRepository.updateStep(step); } } } catch (Exception e) { log.error("Failed to terminate step '{}' with status '{}': {}", stepId, exitStatus, e.getMessage()); log.debug("Exception", e); } }

Target:
pls avoid magic numbers
Source:
public List<GlusterVolumeEntity> getVolumesSupportedAsStorageDomain() { List<GlusterVolumeEntity> volumes = getCallsHandler().executeReadList("GetGlusterVolumesSupportedAsStorageDomain", volumeRowMapper, getCustomMapSqlParameterSource() .addValue("replica_count", 3)); fetchRelatedEntities(volumes); return volumes; }

Target:
Won't it be better to pass the replica count as a parameter in getVolumesSupportedAsStorageDomain, or just remove it from the stored procedure instead
Source:
public ChangeVmClusterValidator(VmCommand parentCommand, Guid targetClusterId, Version vmCustomCompatibilityVersion) { this.parentCommand = parentCommand; this.targetClusterId = targetClusterId; this.vmCompatibilityVersion = vmCustomCompatibilityVersion; }

Target:
It's better to make the constructor private or protected.
Source:
private QemuVolumeFormat(String value) { value = value; }

Target:
this.value = value;
Source:
public CommandCallback getCallback() { if (getVm().isQualifiedForLiveSnapshotMerge() || getParameters().isUseCinderCommandCallback() || FeatureSupported.isQemuimgCommitSupported(getStoragePool().getCompatibilityVersion())) { return new ConcurrentChildCommandsExecutionCallback(); } return null; }

Target:
please export this check a method, it's long and repeating itself few times.
Source:
public CommandCallback getCallback() { if (FeatureSupported.isQemuingCommitSupported(getStoragePool().getCompatibilityVersion())) { return new ConcurrentChildCommandsExecutionCallback(); } if (getVm().isQualifiedForLiveSnapshotMerge() || getParameters().isUseCinderCommandCallback()) { return new ConcurrentChildCommandsExecutionCallback(); } return null; }

Target:
why not merging the condition with line 505?
Source:
private VdcActionType getSnapshotActionType() { if (getVm().isQualifiedForLiveSnapshotMerge()) { return VdcActionType.RemoveSnapshotSingleDiskLive; } if (FeatureSupported.isQemuimgCommitSupported(getStoragePool().getCompatibilityVersion())) { return VdcActionType.ColdMergeSnapshotSingleDisk; } return VdcActionType.RemoveSnapshotSingleDisk; }

Target:
please use the added method isQemuimgCommitSupported() here as well
Source:
public void releaseMacsOnCommit(List<String> macs) { CompensationContext compensationContext = this.commandContext.getCompensationContext(); ReleaseMacsCompensationListener compensationListener = this.compensationListener; log.debug("Registering macs: to be released in case of successful execution", Arrays.toString(macs.toArray())); compensationListener.macsToReleaseOnCommit.addAll(macs); log.debug("Registering compensation listener {}" + compensationListener); compensationContext.addListener(compensationListener); }

Target:
why not to rely on AbstractCollection..toString?
Source:
public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> listPermissionSubjects = new ArrayList<>(); if (!isImageProvided()) { listPermissionSubjects.add(new PermissionSubject(getParameters().getStorageDomainId(), VdcObjectType.Storage, ActionGroup.CREATE_DISK)); } else { // DISK_OPERATOR role is granted and persisted for the user who created the disk. // Therefor, returning a CREATE_DISK permission subject on the target disk will enforce that the only user // who can do I/O to this disk is its creator. listPermissionSubjects.add(new PermissionSubject(getParameters().getImageId(), VdcObjectType.Disk, ActionGroup.CREATE_DISK)); } return listPermissionSubjects; }

Target:
would you mind inverting the condition to simplify it and skip the negation ? if (isImageProvided()) { ... } else { ... }
Source:
private void unlockImageInDb() { DiskImage diskImage = getDiskImage(); diskImage.setImageStatus(ImageStatus.OK); ImagesHandler.updateImageStatus(diskImage.getImageId(), ImageStatus.OK); }

Target:
Not needed, the next statement handles it in the DB, do we really care if we have the status changed in the instance?
Source:
public boolean equals(Object o) { if (o instanceof PermissionSubject) { PermissionSubject other = (PermissionSubject) o; return Objects.equals(other.objectId, objectId) && Objects.equals(other.ObjectType, ObjectType) && Objects.equals(other.actionGroup, actionGroup); } return false; }

Target:
This one is missing: if (this == obj) { return true; }
Source:
public ColdMergeCommandParameters(Guid storagePoolId, SubchainInfo subchainInfo) { super(); setStoragePoolId(storagePoolId); this.subchainInfo = subchainInfo; }

Target:
needed?
Source:
public GlusterStorageDomainDRSyncJob() { super(); backend = Injector.get(BackendInternal.class); storageDomainDao = Injector.get(StorageDomainDao.class); geoRepDao = Injector.get(GlusterGeoRepDao.class); }

Target:
instead using the Injector here, pls use the @Inject annotation, and when you intend to use GlusterStorageDomainDRSyncJob, declare it using @Inject or using Injector.get(GlusterStorageDomainDRSyncJob.class);
Source:
public ValidationResult isMacAssignableValidator() { Boolean allowDupMacs = macPool.isDuplicateMacAddressesAllowed(); boolean illegalDuplicateMacUsage = !allowDupMacs && macPool.isMacInUse(macAddress); EngineMessage failMessage = EngineMessage.NETWORK_MAC_ADDRESS_IN_USE; return ValidationResult .failWith(failMessage, ReplacementUtils.getVariableAssignmentString(failMessage, macAddress)) .when(illegalDuplicateMacUsage); }

Target:
(feel free to ignore this) This is outside the scope of the patch, so please feel free to ignore this, but maybe we could change: Boolean -> boolean
Source:
private void failValidationCannotPlugPassthroughVnicNoSuitableVf() { failValidation(EngineMessage.CANNOT_PLUG_PASSTHROUGH_VNIC_NO_SUITABLE_VF, String.format("$vnicName %1$s", getInterfaceName())); }

Target:
why not to prefet it to return the value of the inner method ? so line 134-135 would look like: return failValidationCannotPlugPassthroughVnicNoSuitableVf (...); ?
Source:
private String acquireVF() { try { hostDeviceManager.acquireHostDevicesLock(getVdsId()); String vfToUse = findFreeVf(); networkDeviceHelper.setVmIdOnVfs(getVdsId(), getVmId(), Collections.singleton(vfToUse)); return vfToUse; } finally { hostDeviceManager.releaseHostDevicesLock(getVdsId()); } }

Target:
vfToUse might be null. This should not cause any problems, as setVmIdOnVfs seems to handle it correctly, but it might be safer to check against it (as was the case in the original code).
Source:
public HostValidator(VDS host) { this.host = host; }

Target:
Perhaps make it private so no one will be able to initialize it outside the class? It makes sense cause regular initialization will not do much without injecting the members
Source:
private void updateActionAvailability() { ArrayList<StorageDomainDR> domainDRs = getSelectedItems() != null ? Linq.<StorageDomainDR> cast(getSelectedItems()) : new ArrayList<StorageDomainDR>(); getNewCommand().setIsExecutionAllowed(true); getEditCommand().setIsExecutionAllowed(domainDRs.size() == 1); }

Target:
Is new allowed always. I think by default all commands are allowed. If so then we can remove it.
Source:
public void addVideoDevices(VmBase vmBase, int numberOfVideoDevices) { if (vmBase.getDefaultDisplayType() != DisplayType.none && vmBase.getDefaultDisplayType().getDefaultVmDeviceType() != null) { for (int i = 0; i < numberOfVideoDevices; i++) { addManagedDevice( new VmDeviceId(Guid.newGuid(), vmBase.getId()), VmDeviceGeneralType.VIDEO, vmBase.getDefaultDisplayType().getDefaultVmDeviceType(), getVideoDeviceSpecParams(vmBase), true, false); } } }

Target:
why do we need this part?
Source:
public void buildVmVideoCards() { boolean videoCardOverridden = vm.isRunOnce() && vm.getDefaultDisplayType() != null; boolean isHeadlessMode = vm.getDefaultDisplayType() == DisplayType.none; if (videoCardOverridden) { if(isHeadlessMode) { return; } buildVmVideoDeviceOverridden(); } else { buildVmVideoDevicesFromDb(); } }

Target:
missing space
Source:
public static void setTooltipOnElement(String tooltip, Element element) { if (tooltip!= null) { element.setTitle(tooltip); } }

Target:
Don't we want to handle null tooltip as well? if (tooltip != null) { element.setTitle(tooltip); } else { element.setTitle(""); }
Source:
private void endSuccessfullySynchronous() { if (reloadVmTemplateFromDB() != null) { endDefaultOperations(); } sealVmTemplate(); setSucceeded(true); }

Target:
but no tasks --> no disks, so no need to seal it, right?
Source:
private static List<TagObject> activeTagList(TagModel model) { List<TagObject> result = new ArrayList<>(); if (model.getSelection()) { result.add(from(model, false)); } for(TagModel child: model.getChildren()) { List<TagObject> activeChildTags = activeTagList(child); if (!activeChildTags.isEmpty()) { result.addAll(activeChildTags); } } return result; }

Target:
Why is this check necessary?
Source:
private void setAllListModelsUnavailable() { for (ListModel m : getItems()) { // Don't mark plugin models as unavailable, the plug-ins themselves will hide/show the tabs. if (!(m instanceof PluginModel)) { m.setIsAvailable(false); } } }

Target:
Another way to do this would be to override setIsAvailable in PluginModel to be no-op. (This would allow us to get rid of the instanceof check here.)
Source:
protected void executeVmCommand() { resourceManager.getVmManager(getVmId()).getStatistics().setMigrationProgressPercent(0); try { setSucceeded(initVdss() && perform()); } catch (Exception e) { setSucceeded(false); } if (!getSucceeded()) { cleanupPassthroughVnics(getDestinationVdsId()); } }

Target:
please wait until it's done there. I don't believe we can remove this trycatch.
Source:
protected boolean validate() { return isNoLeasesOnStorageDomain() && canDetachStorageDomainWithVmsAndDisks(getStorageDomain()) && canDetachDomain(getParameters().getDestroyingPool(), getParameters().getRemoveLast()); }

Target:
please move the check to be after canDetachDomain() which validates that the domain exists. We'll need to move also canDetachStorageDomainWithVmsAndDisks() in a separate patch.
Source:
public int compare(Nameable nameable1, Nameable nameable2) { final String name1 = nameable1.getName(); final String name2 = nameable2.getName(); final NumericSuffixNormalizer numericSuffixNormalizer = new NumericSuffixNormalizer(); final List<String> normalizedNames = numericSuffixNormalizer.normalize(name1, name2); return ObjectUtils.compare(normalizedNames.get(0), normalizedNames.get(1)); }

Target:
extract to field; we do not need N creations of this when lets say sorting collection.
Source:
protected void initEffectiveCompatibilityVersion() { Version effectiveCompatibilityVersion = VmPropertiesUtils.getInstance().getSupportedClusterLevels().contains(getParameters().getVmStaticData().getCustomCompatibilityVersion()) ? CompatibilityVersionUtils.getEffective(getParameters().getVmStaticData(), this::getCluster) : CompatibilityVersionUtils.getEffective(this::getCluster); // The effective Compatibility Version will be taken from Cluster setEffectiveCompatibilityVersion(effectiveCompatibilityVersion); }

Target:
I don't think that's not the right place for this. I see two options: 1. to validate the custom-compatibility version in CompatibilityVersionUtils#getEffective instead. 2. not to validate it at this point, set what could be an incorrect value, and rely on the validation in te 'validate' method. I would go with #2 - there's no point in validating something just to put another value (which is also incorrect - if I asked for a VM with CCV 5.7, I expect to get this compatibility or an error if that's invalid).
Source:
protected boolean validateLeaseStorageDomain(Guid leaseStorageDomainId) { StorageDomain domain = storageDomainDao.getForStoragePool(leaseStorageDomainId, getStoragePoolId()); StorageDomainValidator validator = new StorageDomainValidator(domain); if (!validate(validator.isDomainExistAndActive()) || !validate(validator.isDataDomain())) { return false; } return true; }

Target:
consider change to return validate(validator.isDomainExistAndActive()) && validate(validator.isDataDomain())
Source:
public List<GraphicsDevice> getPrevDevices() { return prevDevices; }

Target:
protected?
Source:
private String getNextRunMessage(String field) { if (field.equals("minAllocatedMem")) { //$NON-NLS-1$ String translated = nextRunMessages.minAllocatedMem(); try { translated = nextRunMessages.getString("minAllocatedMem"); //$NON-NLS-1$ } catch (MissingResourceException e) { // ignore } return translated; } return field; }

Target:
and if the MissingResourceException is not enough here, you can do catch (Exception) { // ignore } But I think the MissingResourceException is ok
Source:
public EntityModelWidgetWithInfo(EnableableFormLabel label, Widget contentWidget, Align alignment) { this.label = label; if (this.label == null) { this.label = new EnableableFormLabel(); this.label.setVisible(false); } this.contentWidget = contentWidget; this.alignment = alignment; infoIcon = new InfoIcon(SafeHtmlUtils.EMPTY_SAFE_HTML); initWidget(WidgetUiBinder.uiBinder.createAndBindUi(this)); }

Target:
I'd suggest to use an explicit if/else like: if (label != null) { this.label = label; } else { this.label = new EnableableFormLabel(); this.label.setVisible(false); }
Source:
public int setTabIndexes(int nextTabIndex) { nextTabIndex++; nameEditor.setTabIndex(nextTabIndex++); cidrEditor.setTabIndex(nextTabIndex++); ipVersionEditor.setTabIndex(nextTabIndex++); gatewayEditor.setTabIndex(nextTabIndex++); return dnsServersEditor.setTabIndexes(nextTabIndex); }

Target:
still needed? should be redundant after I91dbedee38d893302f1006c9ce1e58d146ce7cce
Source:
private int calculateValue(NetworkCluster networkCluster) { int res = 0; if (networkCluster != null) { if (networkCluster.isDefaultRoute()) { res += 16; } if (networkCluster.isManagement()) { res += 8; } if (networkCluster.isDisplay()) { res += 4; } if (networkCluster.isMigration()) { res += 2; } if (networkCluster.isGluster()) { res += 1; } } return res; }

Target:
Please keep the management network with the highest number. So it will be displayed first.
Source:
boolean isMonitoringNeeded(VDSStatus status) { switch (status) { case Up: case NonResponsive: case Error: case NonOperational: case PreparingForMaintenance: case Initializing: case Connecting: return true; default: return false; } }

Target:
I agree, but I'm ok with leaving it that way - the patch still makes stuff better than it was without it. but: 1. if we keep it that way, it worth to note that in a comment 2. I think the formatter will remove the spaces before the 'case' keyword (so they will be right below the 'switch'), can you please check that?
Source:
public boolean isImageNetworkDisk(DiskImage diskImage, Version clusterVersion, Guid clusterId) { StorageType storageType = diskImage.getStorageTypes().get(0); if (storageType == StorageType.GLUSTERFS) { if (FeatureSupported.libgfApiSupported(clusterVersion)) { return true; } return isFeatureSupportedAsAdditionalFeature(clusterId, ConfigValues.LibgfApiSupported.name()); } return false; }

Target:
That could be reduced to a single boolean expression, which is more more clear to understand: return FeatureSupported.libgfApiSupported(clusterVersion) || isFeatureSupportedAsAdditionalFeature(clusterId, ConfigValues.LibgfApiSupported.name());
Source:
private void onOk() { FenceProxyModel windowModel = (FenceProxyModel) getWindow(); setWindow(null); ListModel<FenceProxyModel> currentModels = windowModel.getCurrentProxies(); FenceProxyModel selectedModel = windowModel.getAvailableProxies().getSelectedItem(); setEntity(selectedModel.getEntity()); Collection<FenceProxyModel> items = currentModels.getItems(); currentModels.setItems(null); currentModels.setItems(items); }

Target:
Hmm, OK, I can try this locally to see what's going on. In general, after you call setWindow(null) to hide the dialog (bound to model's `Window` property), you should not use the dialog's model (e.g. FenceProxyModel) anymore, since it's cleaned up. (When a model gets cleaned up, all handlers/listeners are removed and references to shared objects nullified as needed.)
Source:
public void passthroughProfileDoesNotContainFilterIdButDefaultWillBeUsed() { passthroughProfileContainsSupportedPropertiesTest(true, false, DEFAULT_GUID, INVALID_NETWORK_FILTER_ID); assertThat(validator.passthroughProfileContainsSupportedProperties(true), failsWith(EngineMessage.ACTION_TYPE_FAILED_PASSTHROUGH_PROFILE_CONTAINS_NOT_SUPPORTED_PROPERTIES)); }

Target:
Instead of 'INVALID_NETWORK_FILTER_ID' you should pass null.
Source:
public void testExecuteQueryWithNotExistingIscsiBond() { IscsiBond iscsiBond = new IscsiBond(); iscsiBond.setId(Guid.newGuid()); when(getQueryParameters().getId()).thenReturn(iscsiBondId); getQuery().executeQueryCommand(); IscsiBond result = getQuery().getQueryReturnValue().getReturnValue(); assertNull(result); }

Target:
I think we can also remove this now after you removed line 87
Source:
public void setIpv6BootProtocol(Ipv6BootProtocol ipv6BootProtocol) { this.ipv6BootProtocol = ipv6BootProtocol; }

Target:
Ipv4 has the following code - "bootProtocol == null) ? Ipv4BootProtocol.NONE : bootProtocol;" Why didn't you adopted the same code here?
Source:
private boolean isUpdateRequired(VM.VMStatus status){ //TODO: fill this list on going. // list of statuses which required vdsm update {up, poweringdown, paused} if (status == VM.VMStatus.Up || status == VM.VMStatus.PoweringDown || status == VM.VMStatus.Paused) { return true; } return false; }

Target:
why not switch/case?
Source:
protected Pair<Boolean, StorageDomain> syncDomainLuns(StorageDomain storageDomain) { return new Pair<>( StorageHelperDirector.getInstance() .getItem(storageDomain.getStorageType()).syncDomainInfo(storageDomain, null), storageDomain); }

Target:
perhaps have the pair as Pair<Boolean, Guid>, we don't need the entire domain object.
Source:
public String getAttributeValue(String name) { for (int i = 0; i < reader.getAttributeCount(); i++) { String attrName = reader.getAttributeLocalName(i); if (attrName.equals(name)) { return reader.getAttributeValue(i); } } return null; }

Target:
I think that the underlying XMLStream reader has a 'getAttributeValue' method. It receives the namespace and the name of the attribute. If you pass 'null' and the name of the attribute it will return the value of the attribute, which is what we need: https://docs.oracle.com/javase/8/docs/api/javax/xml/stream/XMLStreamReader.html#getAttributeValue-java.lang.String-java.lang.String-
Source:
protected boolean perform() { try { getParameters().setStartTime(new Date()); destinationHostLock = new EngineLock(hostLocking.getSetupNetworksLock(getDestinationVdsId())); lockManager.acquireLockWait(destinationHostLock); if (unplugPassthroughNics() && connectLunDisks(getDestinationVdsId()) && migrateVm()) { ExecutionHandler.setAsyncJob(getExecutionContext(), true); return true; } // otherwise runningFailed(); return false; } catch (Exception e) { runningFailed(); throw e; } }

Target:
If I understand correctly, the purpose of the patch is to fix a specific problem - failure of migration because of 'refreshCaps' failure to take a lock. It is enough to take a waiting lock inside the ActivateDeactivateVmIntefaceCommand before calling the refresh, instead of locking the host for the whole migration period. You can pass 'lockProperties.withScope(Scope.Execution).withWait(true)' as the 'lockProperties' of the parameters you pass to 'RefreshHost' (the 'RefreshHost' should pass it the 'RefreshCaps').
Source:
public void setReturnValueFailure(VDSReturnValue returnValueFailure) { setSucceeded(false); final EngineFault engineFault = new EngineFault(); engineFault.setError(returnValueFailure.getVdsError().getCode()); engineFault.setMessage(returnValueFailure.getVdsError().getMessage()); getReturnValue().setFault(engineFault); }

Target:
this is redundant - it is false unless explicitly set to true
Source:
private void setDcCompatibilityLevelUpgradeNeeded(List<StoragePool> dataCenters) { Config.<Set<Version>> getValue(ConfigValues.SupportedClusterLevels) .stream() .max(Comparator.naturalOrder()) .ifPresent( maxSupportedClusterLevel -> dataCenters.forEach( dataCenter -> dataCenter.setStoragePoolCompatibilityLevelUpgradeNeeded( maxSupportedClusterLevel.compareTo(dataCenter.getCompatibilityVersion()) > 0))); }

Target:
still lambda in lambda. From my point of view ~ not readable.
Source:
protected boolean amendDiskRequested() { if (getOldDisk().getDiskStorageType() == DiskStorageType.IMAGE) { DiskImage oldDisk = (DiskImage) getOldDisk(); return (oldDisk.getVolumeFormat() == VolumeFormat.COW) && !Objects.equals(oldDisk.getQcowCompat().getCompatValue(), ((DiskImage) getNewDisk()).getQcowCompat().getCompatValue()); } return false; }

Target:
unneeded brackets
Source:
public void setUp() { Map<String, String> headers = new HashMap<>(); headers.put("my", "value"); setXmlResponse("clusters", 200, "<clusters/>"); setXmlResponse("clusters/123", 200, "<cluster id=\"123\"><name>test</name></cluster>"); startServer(); connection = (HttpConnection) testConnectionBuilder().header("my", "value").build(); clustersService = connection.systemService().clustersService(); clusterService = clustersService.clusterService("123"); }

Target:
These ^ lines aren't needed.
Source:
private void validateDiscardAfterDelete() { if (getDiscardAfterDelete().getIsAvailable() && getDiscardAfterDelete().getEntity()) { SanStorageModelBase sanStorageModel = (SanStorageModelBase) getCurrentStorageItem(); Collection<LunModel> luns = sanStorageModel.getAddedLuns(); if (luns != null && !storageDomainSupportsDiscard(luns)) { getDiscardAfterDelete().setIsValid(false); getDiscardAfterDelete().getInvalidityReasons().add( constants.discardIsNotSupportedByUnderlyingStorage()); return; } } getDiscardAfterDelete().setIsValid(true); }

Target:
Try moving it to the previous line. I think it should solve the tool-tip issue.
Source:
public SyncLunsParameters(Guid storagePoolId) { super(storagePoolId); }

Target:
This is a code smell. You should have only one path to the super. Instead, call this(storagePoolId, null)
Source:
public static int getCdDeviceIndex(String cdInterface) { switch (cdInterface) { case "scsi": return 2; case "ide": return 2; case "sata": return 2; default: return -1; } }

Target:
Since it is 2, 2, 2, it could be rewritten to: case "scsi": case "ide": case "sata": return 2; default: return -1;
Source:
private void updateVmAfterMigrationToDifferentCluster() { if (getParameters().getTargetClusterId() != null || getVm().getClusterId().equals(getParameters().getTargetClusterId())) { return; } ChangeVMClusterParameters params = new ChangeVMClusterParameters( getParameters().getTargetClusterId(), getVmId(), getVm().getCustomCompatibilityVersion()); setSucceeded(getBackend().runInternalAction(VdcActionType.ChangeVMCluster, params).getSucceeded()); }

Target:
Shouldn't it be '== null'?
Source:
public String getUuid() { return UUID.randomUUID().toString(); }

Target:
this method is useless. Can you send a patch to remove it so all the code that needs uuid will simply use UUID class?
Source:
private List<SubchainInfo> mockSnapshotList(List<DiskImage> snapshots, Version version) { mockCluster(version); configRule.mockConfigValue(ConfigValues.QemuimgCommitSupported, version); List<DiskImage> childSnapshots = createChildSnapshots(snapshots); when(diskImageDao.getAllSnapshotsForParents( snapshots .stream() .map(DiskImage::getImageId) .collect(Collectors.toList()) ) ).thenReturn(childSnapshots); return cmd.getAllDisksSnapshot(snapshots); }

Target:
This replicates the logic from the production code. Can't we just create the DiskImages and the SubchainInfo in symetrically?
Source:
public void removeLeftoverDevices(VmBase vmBase) { List<VmDevice> spiceChannels = vmDeviceDao.getVmDeviceByVmIdTypeAndDevice( vmBase.getId(), VmDeviceGeneralType.CHANNEL, VmDeviceType.SPICEVMC.getName()); // remove spice channel if we are no longer using spice if (!hasGraphicsDevice(vmBase.getId(), GraphicsType.SPICE)) { removeVmDevices(spiceChannels); } }

Target:
Please note that this doesn't handle templates, only VMs (while the original bug was opened to handle templates) - maybe it worth adding a remark in BZ saying that we won't remove spicevmc channels for templates..
Source:
private void enableLoadBalancer() { if (Config.<Boolean>getValue(ConfigValues.EnableVdsLoadBalancing)) { log.info("Start scheduling to enable vds load balancer"); executor.scheduleWithFixedDelay(() -> performLoadBalancing(), Config.<Integer>getValue(ConfigValues.VdsLoadBalancingIntervalInMinutes), Config.<Integer>getValue(ConfigValues.VdsLoadBalancingIntervalInMinutes), TimeUnit.MINUTES); log.info("Finished scheduling to enable vds load balancer"); } }

Target:
this::performLoadBalancing?
Source:
private void enableHaReservationCheck() { if (Config.<Boolean>getValue(ConfigValues.EnableVdsLoadBalancing)) { log.info("Start HA Reservation check"); Integer interval = Config.<Integer> getValue(ConfigValues.VdsHaReservationIntervalInMinutes); executor.scheduleWithFixedDelay(() -> performHaResevationCheck(), interval, interval, TimeUnit.MINUTES); log.info("Finished HA Reservation check"); } }

Target:
the same, why not use method reference?
Source:
public void backupCheck() { // skip backup check if previous operation is not completed yet if (lock.tryLock()) { try { log.info("Backup check started."); doBackupCheck(); log.info("Backup check completed."); } finally { lock.unlock(); } } }

Target:
private?
Source:
public void availableUpdates() { hostDao.getAll() .stream() .filter(h -> h.getStatus().isEligibleForCheckUpdates()) .forEach(this::submitCheckUpdatesForHost); }

Target:
private?
Source:
public void cleanCompletedJob() { Date succeededJobsDeleteTime = new Date(System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(succeededJobTime, TimeUnit.MINUTES)); Date failedJobsDeleteTime = new Date(System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(failedJobTime, TimeUnit.MINUTES)); try { jobDao.deleteCompletedJobs(succeededJobsDeleteTime, failedJobsDeleteTime); } catch (RuntimeException e) { log.error("Failed to delete completed jobs: {}", e.getMessage()); log.debug("Exception", e); } }

Target:
private?
Source:
void stubGetUserBySessionIdQuery() { VdcQueryReturnValue returnValue = new VdcQueryReturnValue(); returnValue.setSucceeded(true); returnValue.setReturnValue(mockUser); when(mockBackend.runQuery( eq(VdcQueryType.GetUserBySessionId), isA(VdcQueryParametersBase.class) )).thenReturn(returnValue); }

Target:
This is probably a good idea regardless of making the VdcQueryReturnValue final. I wonder if it's worth having this small cleanup in a separate patch.
Source:
} catch (NoSuchAlgorithmException e) { new RuntimeException("Unable to generate KeyPair", e); }

Target:
Is it possible to throw RuntimeException from static block?
Source:
protected void addLink(LinksTreeNode linksTree, String link) { //link segments are separated by '.' (e.g: (disk_attachements.template) String[] linkSegments = link.split("\\."); for (String segment : linkSegments) { linksTree = updateTree(linksTree, segment); } }

Target:
Why protected? Do we have any subclass? Try to make everything 'private' unless something else is required. We can always make things more accessible in the future. The other way around is harder.
Source:
private static String getMessageOrNull(AuditLogType logType) { final String key = logType.name(); try { return resourceBundle.getString(key); } catch (Exception e) { log.error("Key '{}' is not translated in '{}'", key, getResourceBundleName()); return null; } }

Target:
related?
Source:
public EngineScheduleExpression(String cronExpression) { super(); String[] cron = cronExpression.split("\\s *"); second(cron[0]).minute(cron[1]).hour(cron[2]).dayOfMonth(cron[3]).month(cron[4]).dayOfWeek(cron[5]); if (cron.length >= 7) { year(cron[6]); } }

Target:
One method invocation per line would be more readable
Source:
private void cleanup() { try { log.info("Start cleanup"); DateTime latestTimeToKeep = DateTime.getNow().addDays( Config.<Integer>getValue(ConfigValues.CommandEntityAgingThreshold) * -1); commandCoordinatorUtil.removeAllCommandsBeforeDate(latestTimeToKeep); log.info("Finished cleanup"); } catch (Throwable t) { log.error("Exception in performing command entity cleanup: {}", ExceptionUtils.getRootCauseMessage(t)); log.debug("Exception", t); } }

Target:
We should move that to debug in different patch (or remove at all), I see no value for that in INFO level
Source:
protected void executeCommand() { VdcActionType actionToExecute = getParameters().getAction(); VdcActionParametersBase actionParameters = getParameters().getActionParameters(); actionParameters.setEndProcedure(VdcActionParametersBase.EndProcedure.COMMAND_MANAGED); actionParameters.setParentCommand(VdcActionType.RunAsyncAction); actionParameters.setParentParameters(getParameters()); CommandCoordinatorUtil.executeAsyncCommand( actionToExecute, actionParameters, cloneContextAndDetachFromParent()); setSucceeded(true); }

Target:
Can't we avoid setting the parent command/parent parameters? it may be preferred to just delete lines 34-35.
Source:
private void updateActionAvailability() { getNewCommand().setIsExecutionAllowed(true); boolean hasSelectedItems = getSelectedItems() != null && getSelectedItems().size() > 0; getEditCommand().setIsExecutionAllowed(hasSelectedItems && getSelectedItems().size() == 1); getRemoveCommand().setIsExecutionAllowed(hasSelectedItems); }

Target:
If the `new` command is always allowed, do we need this line?
Source:
private void cancel() { setConfirmWindow(null); }

Target:
I've seen other list models doing setWindow(null) as well. Not sure if we need to do it here too, though.
Source:
protected void addCommands() { UICommand command = UICommand.createDefaultOkUiCommand("OnSave", this); //$NON-NLS-1$ getCommands().add(command); getCommands().add(UICommand.createCancelUiCommand("Cancel", this)); //$NON-NLS-1$ }

Target:
Maybe inline this local variable?
Source:
public boolean isDiskExists(Guid id) { return baseDiskDao.exists(id); }

Target:
This should be private
Source:
public void logServerMessage(final VDS server, final AuditLogType logType) { logAuditMessage(server == null ? Guid.Empty : server.getClusterId(), server == null ? null : server.getClusterName(), null, server, logType, Collections.emptyMap()); }

Target:
Done
Source:
protected boolean validateInputManagementNetwork() { if (!findInputManagementNetwork()) return false; final NetworkClusterValidatorBase networkClusterValidator = createNetworkClusterValidator(); return validate(networkClusterValidator.networkBelongsToClusterDataCenter(getCluster(), managementNetwork)) && validate(networkClusterValidator.managementNetworkRequired(managementNetwork)) && validate(networkClusterValidator.managementNetworkNotExternal(managementNetwork)); }

Target:
Doesn't it make sense to have those validation in the update use case as well?
Source:
protected void log() { final Transaction transaction = TransactionSupport.suspend(); try { try { auditLogDirector.log(this, getAuditLogTypeValue()); } catch (final RuntimeException ex) { log.error("Error during log command: {}. Exception {}", getClass().getName(), ex.getMessage()); log.debug("Exception", ex); } } finally { TransactionSupport.resume(transaction); } }

Target:
Wouldn't it be more readable to use TransactionSupport.executeInNewTransaction() instead of the code here which does the same?
Source:
public void storageAndPoolExists() { StorageDomain sd = new StorageDomain(); Guid storagePoolId = Guid.newGuid(); sd.setStoragePoolId(storagePoolId); when(storageDomainDao.getAllForStorageDomain(any(Guid.class))).thenReturn(Collections.singletonList(sd)); when(storagePoolDao.get(storagePoolId)).thenReturn(new StoragePool()); assertTrue(cmd.validate()); }

Target:
This is redundant in Mockito 2
Source:
public void invalidStoragePool() { StorageDomain sd = new StorageDomain(); Guid storagePoolId = Guid.newGuid(); sd.setStoragePoolId(storagePoolId); when(storageDomainDao.getAllForStorageDomain(any(Guid.class))).thenReturn(Collections.singletonList(sd)); when(storagePoolDao.get(storagePoolId)).thenReturn(null); assertFalse(cmd.validate()); }

Target:
This is redundant in Mockito 2
Source:
public Boolean getUseForBackup() { return useForBackup; }

Target:
isUsedForBackup? And also why are you returning Boolean object when attribute is defined primitive boolean type?
Source:
public int setTabIndexes(int nextTabIndex) { nextTabIndex = super.setTabIndexes(nextTabIndex); nextTabIndex = createSubnetEditor.setTabIndexes(nextTabIndex); nextTabIndex = this.subnetWidget.setTabIndexes(nextTabIndex); return nextTabIndex; }

Target:
Nit-pick: no need to call super [1] since that's effectively a no-op call, you can simply skip the line above. [1] AbstractModelBoundPopupView#setTabIndexes (If this View extended some other View that would override setTabIndexes method, super should be called in any case.)
Source:
public void testValidationFailsDiskConnectedToRunningVm() { VM vm = new VM(); vm.setStatus(VMStatus.Up); VmDevice vmDevice = new VmDevice(); vmDevice.setPlugged(true); List<Pair<VM, VmDevice>> vms = Collections.singletonList(new Pair(vm, vmDevice)); doReturn(vms).when(vmDao).getVmsWithPlugInfo(diskId); ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_VM_IS_NOT_DOWN); }

Target:
don't use raw types - new Pair<>(vm, vmDevice)
Source:
private void setQcowCompatForQcowImage() { Image image = imageDao.get(getDiskImage().getImageId()); if (getDiskImage().getDiskStorageType() == DiskStorageType.IMAGE && getDiskImage().getVolumeFormat().equals(VolumeFormat.COW)) { image.setQcowCompat(getDiskImage().getQcowCompat()); imageDao.update(image); } }

Target:
why using equals for VolumeFormat and '==' for DiskStorageType ?
Source:
public void endSuccessfully() { setQcowCompatForQcowImage(); if (getParameters().getImportAsTemplate()) { Guid newTemplateId = createTemplate(); // No reason for this to happen, but checking just to make sure if (newTemplateId != null) { attachDiskToTemplate(newTemplateId); } } updateDiskStatus(ImageStatus.OK); setSucceeded(true); }

Target:
What about calling super? Is it intentional we don't call it? If so - why?
Source:
public VDSInfoReturn getVdsStats(BrokerCommandCallback callback) { JsonRpcRequest request = new RequestBuilder("Host.getStats").build(); Map<String, Object> response = new FutureMap(this.client, request, ResourceManager.getInstance().getExecutor(), callback) .withResponseKey("info"); return new VDSInfoReturn(response); }

Target:
Why not to enable lazyEval here?
Source:
protected boolean canAddLease() { if (!getParameters().getVmStaticData().isAutoStartup()) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_VM_LEASES_ARE_NOT_SUPPORTED_WITH_HA_OFF); } if (!FeatureSupported.isVmLeasesSupported(getEffectiveCompatibilityVersion())) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_VM_LEASES_ARE_NOT_SUPPORTED); } return validateLeaseStorageDomain(getParameters().getVmStaticData().getLeaseStorageDomainId()); }

Target:
Maybe it should be the first validation ?
Source:
protected boolean checkDisksNotInBackupStorage() { for (Disk disk : getVm().getDiskMap().values()) { StorageDomainStatic destDomain = storageDomainStaticDao.get(disk.getId()); if (destDomain.isBackup() == true) { return false; } } return true; }

Target:
no need for == true
Source:
public Future<JsonRpcResponse> call(JsonRpcRequest req, BrokerCommandCallback callback) throws ClientConnectionException { final Call call = new Call(req, executorService, callback); this.tracker.registerCall(req, call); retryCall(req, call); try { this.getClient().sendMessage(jsonToByteArray(req.toJson())); } finally { retryCall(req, call); } return call; }

Target:
It looks like we are using executor in this class only so let's use this field instead of passing it as part of the call object.
Source:
protected void updateMetadataDevices() { if (getStorageDomain().getVgMetadataDevice() == null || getStorageDomain().getFirstMetadataDevice() == null) { blockStorageDomainHelper.fillMetadataDevicesInfo(getStorageDomain().getStorageStaticData(), getVds().getStoragePoolId()); storageDomainStaticDao.update(getStorageDomain().getStorageStaticData()); } }

Target:
I'm not sure that will work on import storage domain. The process of import is being done through one host first so calling HSMGetStorageDomainInfo should be done through this Host.
Source:
private boolean ifaceMacCannotBeAddedToMacPool(VmNetworkInterface iface) { return !macPool.isDuplicateMacAddressesAllowed() && !shouldReassignMac(iface) && macPool.isMacInUse(iface.getMacAddress()); }

Target:
Shouldn't you verify the mac is not null to avoid NPE? 'ImportVmFromConfigurationCommand' has this check.
Source:
private void activeDetailModelChanging(HasEntity<D> newValue, boolean stopRefresh) { for (HasEntity<D> oldValue : activeDetailModels) { // Make sure we had set an entity property of details model. if (oldValue != null && stopRefresh) { oldValue.setEntity(null); if (oldValue instanceof SearchableListModel) { ((SearchableListModel) oldValue).stopRefresh(); } } } if (newValue != null) { newValue.setEntity(provideDetailModelEntity(getSelectedItem())); } }

Target:
Wouldn't a top-level if (stopRefresh) guard condition be better, instead of checking it within the loop?
Source:
public static boolean isFormatCorrect(String blob) throws IOException { final Map<String, String> map = getEncryptionMap(blob); if (map.isEmpty()) { return false; } return ARTIFACT.equals(map.get(ARTIFACT_KEY)) && VERSION.equals(map.get(VERSION_KEY)); }

Target:
Not needed to test emptiness, it's contained in condition below
Source:
public void restoreStateFromViewItem(PatternflyListViewItem<HostInterfaceLineModel> originalViewItem) { super.restoreStateFromViewItem(originalViewItem); // Need to check because we could be coming from a non bond interface and restoring the state (expanded details) // from it into a bonded interface will not work. if (originalViewItem instanceof HostNetworkInterfaceBondedListViewItem) { HostNetworkInterfaceBondedListViewItem original = (HostNetworkInterfaceBondedListViewItem) originalViewItem; setSlavesExpanded(original.getSlavesState()); } }

Target:
Nit-pick: typecast could be inlined here, avoiding explicit "original" variable declaration, since it's only needed here.
Source:
public void restoreStateFromViewItem(PatternflyListViewItem<HostInterfaceLineModel> originalViewItem) { if (originalViewItem instanceof HostNetworkInterfaceListViewItem) { HostNetworkInterfaceListViewItem original = (HostNetworkInterfaceListViewItem) originalViewItem; setLogicalNetworkExpanded(original.getLogicalNetworkState()); } }

Target:
Nit-pick: like in HostNetworkInterfaceBondedListViewItem.java, the typecast could be inlined here.
Source:
public void setInSlot(Object slot, IsWidget content) { if (slot == MainSectionPresenter.TYPE_SetHeader) { setPanelContent(headerPanel, content); } else if (slot == MainSectionPresenter.TYPE_SetMainContent) { if (!placeholderRemoved) { removeHostPagePlaceholder(); placeholderRemoved = true; } setPanelContent(mainContentPanel, content); } else { super.setInSlot(slot, content); } }

Target:
I would remove the boolean and put this after the activateMenus() above. Since we only need to call it once.
Source:
private void warnIfNotAllDisksPermitSnapshots() { for (Disk disk : getVm().getDiskMap().values()) { if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { } if (!disk.isAllowSnapshot()) { auditLogDirector.log(this, AuditLogType.USER_RUN_VM_AS_STATELESS_WITH_DISKS_NOT_ALLOWING_SNAPSHOT); break; } } }

Target:
huh?