auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void removeDiskFromDbCallBack(final CinderDisk cinderVolume) { final Snapshot updated; START if (getParameters().isUpdateSnapshot()) { END updated = getSnapshotWithoutCinderVolume(cinderVolume); } else { updated = null; } TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Object>() { @Override public Object runInTransaction() { removeDiskFromDb(cinderVolume, updated); return null; } }); } consider ternary instead

Target:
protected void removeDiskFromDbCallBack(final CinderDisk cinderVolume) { final Snapshot updated = getParameters().isUpdateSnapshot() ? getSnapshotWithoutCinderVolume(cinderVolume) : null; TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Object>() { @Override public Object runInTransaction() { removeDiskFromDb(cinderVolume, updated); return null; } }); }
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 START newServerConnection = END 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()); } newServerConnection seems completely redundant

Target:
public void setUp() throws Exception { super.setUp(); dao = dbFacade.getStorageServerConnectionLunMapDao(); StorageServerConnectionDao storageServerConnectionDao = dbFacade.getStorageServerConnectionDao(); StorageServerConnections existingConnection = storageServerConnectionDao.get("0cc146e8-e5ed-482c-8814-270bc48c297e"); existingLUNStorageMap = dao.get(new LUNStorageServerConnectionMapId("1IET_00180001", existingConnection.getid())); newLUNStorageMap = new LUNStorageServerConnectionMap(FREE_LUN_ID, existingConnection.getid()); }
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()); } START lock = new ReentrantLock(); END } 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)

Target:
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()); } }
Source:
private long findUnusedMac() { int index = usedMacs.nextClearBit(startingLocationWhenSearchingForUnusedMac); boolean notFound = index == numberOfMacsInRange; if (notFound) { index = usedMacs.nextClearBit(0); } START startingLocationWhenSearchingForUnusedMac = index + 1; END return rangeStart + index; } shouldn't it be- (index +1) % numberOfMacsInRange ?

Target:
private long findUnusedMac() { int index = usedMacs.nextClearBit(startingLocationWhenSearchingForUnusedMac); boolean notFound = index == numberOfMacsInRange; if (notFound) { index = usedMacs.nextClearBit(0); } startingLocationWhenSearchingForUnusedMac = (index + 1) % numberOfMacsInRange; return rangeStart + index; }
Source:
START public boolean isSchemaEnum(Type type) { END for (Name name : SCHEMA_ENUMS) { if (name.toString().equals(type.getName().toString())) { return true; } } return false; } The "Name" class implements correctly the "equals" method, so you can do just this: return SCHEMA_ENUMS.contains(type.getName());

Target:
public boolean isSchemaEnum(Type type) { 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); }; START ThreadPoolUtil.execute(task); END } } Why do we need temp variable? ThreadPoolUtil.execute(() -> { waitUntilFencingAllowed(); startHosts(hostsWithPMInReboot); });

Target:
private void startHostsWithPMInReboot(List<VDS> hosts) { final List<VDS> hostsWithPMInReboot = hosts.stream() .filter(host -> host.isPmEnabled()) .filter(host -> host.getStatus() == VDSStatus.Reboot) .collect(Collectors.toList()); if (hostsWithPMInReboot.size() > 0) { 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) { START messageLabel.setText(message); END } } 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.

Target:
public void setMessage(String message) { super.setMessage(message); // Hide table in case of message if (message != null && message.length() > 0) { table.setVisible(false); messageLabel.setText(message); } }
Source:
public String toString() { START return Objects.toString(getFirst(), null) + '.' + Objects.toString(getSecond(), null); END } You can just use Objects.toString(getFirst()) and Objects.toString(getSecond()), it has the same behavior.

Target:
public String toString() { return Objects.toString(getFirst()) + '.' + Objects.toString(getSecond()); }
Source:
public RemoveMemoryVolumesParameters() { this.memoryVolumes = ""; this.vmId = Guid.Empty; START this.forceRemove = false; END } I would drop that since it is false by default

Target:
public RemoveMemoryVolumesParameters() { this.memoryVolumes = ""; this.vmId = Guid.Empty; }
Source:
private void update(List<VmNetworkInterface> interfaces) { START if (interfaces != null && !interfaces.isEmpty()) { END for (VmNetworkInterface ifc : interfaces) { VmNetworkStatistics stats = ifc.getStatistics(); vmManager.update(stats); } } } If interfaces.isEmpty() the loop body will not be run, so this check is redundant.

Target:
private void update(List<VmNetworkInterface> interfaces) { if (interfaces == null) { return; } for (VmNetworkInterface ifc : interfaces) { vmManager.update(ifc.getStatistics()); } }
Source:
public boolean equals(Object o) { START if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; END NetworkFilter that = (NetworkFilter) o; return Objects.equals(name, that.name) && Objects.equals(version, that.version) && Objects.equals(id, that.id); } please configure your IDE to use brackets in equals methods around if statements. Those should be by convention present everywhere.

Target:
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); }
Source:
START GetAllSupportedNetworkFiltersByVersionQuery(VersionQueryParameters parameters) { END super(parameters); } Why is it package private?

Target:
public GetAllSupportedNetworkFiltersByVersionQuery(VersionQueryParameters parameters) { super(parameters); }
Source:
public String disableEffectsAsString() { StringBuilder disableEffectsBuffer = new START StringBuilder(""); END int countdown = getWanDisableEffects().size(); for (ConsoleOptions.WanDisableEffects disabledEffect : getWanDisableEffects()) { disableEffectsBuffer.append(disabledEffect.asString()); if (countdown != 1) { disableEffectsBuffer.append(", "); } countdown--; } return disableEffectsBuffer.toString(); } 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.

Target:
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(); }
Source:
private Predicate<Constructor<?>> createConstructorInaccessibleFromPackagePredicate(Package sourcePackage) { return constructor -> { START int constructorModifiers = constructor.getModifiers(); END return Modifier.isPrivate(constructorModifiers) || (!sourcePackage.equals(constructor.getDeclaringClass().getPackage()) && !Modifier.isPublic(constructorModifiers)); }; } I'd inline this and make it a single statement predicate

Target:
private Predicate<Constructor<?>> createConstructorInaccessibleFromPackagePredicate(Package sourcePackage) { return constructor -> Modifier.isPrivate(constructor.getModifiers()) || (!sourcePackage.equals(constructor.getDeclaringClass().getPackage()) && !Modifier.isPublic(constructor.getModifiers())); }
Source:
private static VideoRAMSettings selectVideoRAMSettings(VmBase vmBase) { Version clusterVersion = ClusterUtils.getCompatibilityVersion(vmBase); if(clusterVersion == null) { clusterVersion = Version.getLast(); START } END if (clusterVersion.greaterOrEquals(new Version(3, 6))) { return new VgamemVideoRAMSettings(); } else { return new LegacyVideoRAMSettings(); } } 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

Target:
private static VideoRAMSettings selectVideoRAMSettings(VmBase vmBase) { if (ClusterUtils.getCompatibilityVersion(vmBase).greaterOrEquals(new Version(3, 6))) { return new VgamemVideoRAMSettings(); } else { return new LegacyVideoRAMSettings(); } }
Source:
START boolean validate() END { getTemplateName().validateEntity( new IValidation[] { new LengthValidation(BusinessEntitiesDefinitions.VM_TEMPLATE_NAME_SIZE), new I18NExtraNameOrNoneValidation() }); return getTemplateName().getIsValid(); } please add 'public' prefix..

Target:
public boolean validate() { getTemplateName().validateEntity( new IValidation[] { new LengthValidation(BusinessEntitiesDefinitions.VM_TEMPLATE_NAME_SIZE), new I18NExtraNameOrNoneValidation() }); return getTemplateName().getIsValid(); }
Source:
public void createMandatoryConstructorSignaturePredicate() { // Signature for a constructor that gets parameters and context objects. mandatoryConstructorSignature = createConstructorSignaturePredicate(VdcActionParametersBase.class, CommandContext.class); START } END The members can be static and the methods @BeforeClass - this data doesn't change per test executed, and is read only.

Target:
public static void createMandatoryConstructorSignaturePredicate() { // Signature for a constructor that gets parameters and context objects. mandatoryConstructorSignature = createConstructorSignaturePredicate(VdcActionParametersBase.class, CommandContext.class); }
Source:
START protected void END auditLog(AuditLogableBase logable, AuditLogType logType) { auditLogDirector.log(logable, logType); } not related.

Target:
void auditLog(AuditLogableBase logable, AuditLogType logType) { auditLogDirector.log(logable, logType); }
Source:
private void fillInUnsetIpConfigs() { START for (NetworkAttachment networkAttachment : getParameters().getNetworkAttachments()) { END if (networkAttachment.getIpConfiguration() == null) { IpConfiguration ipConfiguration = NetworkUtils.createDefaultIpConfiguration(); networkAttachment.setIpConfiguration(ipConfiguration); } } } please replace with java8 stream.filter.forEach()

Target:
private void fillInUnsetIpConfigs() { getParameters().getNetworkAttachments().stream().forEach(networkAttachment -> { if (networkAttachment.getIpConfiguration() == null) { IpConfiguration ipConfiguration = NetworkUtils.createDefaultIpConfiguration(); networkAttachment.setIpConfiguration(ipConfiguration); } }); }
Source:
private NetworkFilter resolveVnicProfileDefaultNetworkFilter() { final Version dataCenterVersion = resolveDataCenterVersion(); START NetworkFilter networkFilter = null; END if (FeatureSupported.antiMacSpoofing(dataCenterVersion) && Config.<Boolean> getValue(ConfigValues.EnableMACAntiSpoofingFilterRules)) { networkFilter = networkFilterDao.getNetworkFilterByName(NetworkFilter.VDSM_NO_MAC_SPOOFING); } return networkFilter; } 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'.

Target:
private NetworkFilter resolveVnicProfileDefaultNetworkFilter() { if (Config.<Boolean> getValue(ConfigValues.EnableMACAntiSpoofingFilterRules)) { return networkFilterDao.getNetworkFilterByName(NetworkFilter.VDSM_NO_MAC_SPOOFING); } return null; }
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())) START .when(useDefaultNetworkFilterId & vnicProfile.getNetworkFilterId() != null); END } Please use && Done.

Target:
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); }
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() START : vmCustomCompatibilityVersion.greaterOrEquals(newClusterVersion); END } return true; } 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.

Target:
public boolean check(VM vm) { if (vm.getStatus() == VMStatus.Suspended || vm.getStatus() == VMStatus.SavingState || vm.getStatus() == VMStatus.RestoringState) { return vm.getCustomCompatibilityVersion() == null; // checked by isApplicable() } return true; }
Source:
protected List<Guid> getFailedVolumeIds(Guid spmVdsId) { return getParameters().getImageList().stream() START .filter((volumeId) -> volumeExists(spmVdsId, volumeId)) END .collect(toList()); } The brackets around the left hand of the -> operator are redundant (and frankly, a bit confusing). Please remove them.

Target:
protected List<Guid> getFailedVolumeIds(Guid spmVdsId) { return getParameters().getImageList().stream() .filter(volumeId -> volumeExists(spmVdsId, volumeId)) .collect(toList()); }
Source:
public static Collection<VdsNetworkInterface> findAllInterfaceBondNameIsEmpty(List<VdsNetworkInterface> items) { return where(items, new IPredicate<VdsNetworkInterface>() { @Override public boolean match(VdsNetworkInterface i) { return START !StringHelper.isNullOrEmpty(i.getBondName()); END } }); } This method should return the interfaces with an empty bond name, you should remove the negation

Target:
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()); } }); }
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) { START try { connection.close();} catch (SQLException e) END } } } the pool may keep it open of course which is the entire idea of course

Target:
protected Array createArrayOf(String typeName, Object[] array) { try (Connection connection = getJdbcTemplate().getDataSource().getConnection()) { return connection.createArrayOf(typeName, array); } catch (SQLException ex) { throw new RuntimeException(ex); } }
Source:
public void setSpmMap(String spId, Host host) { START spmMap.put(spId, host); END } you refer to spmMap with and without "this". Please be consistent.

Target:
public void setSpmMap(String spId, Host host) { this.spmMap.put(spId, host); }
Source:
public static void handleIoTune(VmDevice vmDevice, Guid diskProfileId, QosCache cache) { START if (cache == null) { cache = new QosCache(); } END 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); } 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.

Target:
public static void handleIoTune(VmDevice vmDevice, Guid diskProfileId, QosCache cache) { 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); }
Source:
public static void flatGroups(ExtMap principal) { START HashMap<String, ExtMap> accumulator = new HashMap<>(); END flatGroups(principal, PrincipalRecord.GROUPS, accumulator); principal.put(PrincipalRecord.GROUPS, new ArrayList<>(accumulator.values())); } Right, I missed that :-(

Target:
public static void flatGroups(ExtMap principal) { Map<String, ExtMap> accumulator = new HashMap<>(); flatGroups(principal, PrincipalRecord.GROUPS, accumulator); principal.put(PrincipalRecord.GROUPS, new ArrayList<>(accumulator.values())); }
Source:
public void onSucceeded() { START TransactionSupport.executeInNewTransaction(() -> { END syncDbRecords(true); return null; }); log.info("Successfully merged snapshot '{}' images '{}'..'{}'", getDiskImage().getImage().getSnapshotId(), getDiskImage().getImageId(), getDestinationDiskImage() != null ? getDestinationDiskImage().getImageId() : "(n/a)"); } 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.

Target:
onSucceeded() { syncDbRecords(true); log.info("Successfully merged snapshot '{}' images '{}'..'{}'", getDiskImage().getImage().getSnapshotId(), getDiskImage().getImageId(), getDestinationDiskImage() != null ? getDestinationDiskImage().getImageId() : "(n/a)"); }
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; START } END return originalClusterVersion != null && recentClusterVersion.getMajor() == originalClusterVersion.getMajor() && recentClusterVersion.getMinor() == originalClusterVersion.getMinor(); } 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

Target:
public boolean isVMWithMemoryCompatible(VM vm) { if (vm == null || vm.getCustomCompatibilityVersion() != null) { return true; } Version recentClusterVersion = vm.getClusterCompatibilityVersion(); // the cluster version in which the memory snapshot was taken Version originalClusterVersion = vm.getClusterCompatibilityVersionOrigin(); return originalClusterVersion != null && recentClusterVersion.getMajor() == originalClusterVersion.getMajor() && recentClusterVersion.getMinor() == originalClusterVersion.getMinor(); }
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; } } START } notFound(); // Will never be reached, as notFound throws a WebApplicationException return null; END } Done

Target:
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; } } } // This will never return but always throw a WebApplicationException return notFound(); }
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)) { START localizedErrorMsg = StringUtils.join(errorMsg.toLowerCase().split("[_]", -1), " "); END } return localizedErrorMsg; } 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 ...

Target:
public String localize(final String errorMsg, final Locale requestLocale) { String localizedErrorMsg = errorMsg; ResourceBundle resourceBundle = getResourceBundle(requestLocale == null ? Locale.getDefault() : requestLocale); if (resourceBundle != null && resourceBundle.containsKey(errorMsg)) { localizedErrorMsg = resourceBundle.getString(errorMsg); } return localizedErrorMsg; }
Source:
START private synchronized ResourceBundle getResourceBundle(Locale locale) { END 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); } 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?

Target:
private 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); }
Source:
private void scanDisks() { START StorageDomain storageDomain = getSelectedItem(); END Frontend.getInstance().runAction(VdcActionType.ScanStorageForUnregisteredDisks, new StorageDomainParametersBase(storageDomain.getStoragePoolId(), storageDomain.getId())); } check for null here

Target:
private void scanDisks() { StorageDomain storageDomain = getSelectedItem(); if (storageDomain != null) { Frontend.getInstance().runAction(VdcActionType.ScanStorageForUnregisteredDisks, new StorageDomainParametersBase(storageDomain.getStoragePoolId(), storageDomain.getId())); } }
Source:
public PermissionsOperationsParameters(Permission permission, Guid targetId) { START this.permission = permission; END this.targetId = targetId; } Why not reuse existing constructors? public PermissionsOperationsParameters(Permission permission, Guid targetId) { this(permission); this.targetId = targetId; }

Target:
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) { START hostJobsInfo = (Map<String, Object>) innerMap.get(JOBS_KEY); END } } Why not : hostJobsInfo = (Map<String, Object>) temp;

Target:
public HostJobsReturnForXmlRpc(Map<String, Object> innerMap) { super(innerMap); hostJobsInfo = (Map<String, Object>) innerMap.get(JOBS_KEY); }
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 START (networkAttachmentId != null && END userRemovedNetworkAttachments.contains(networkAttachmentId)) { iterator.remove(); break; } } } all existing network attachments (returned from db) should have id set.

Target:
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 (userRemovedNetworkAttachments.contains(networkAttachmentId)) { iterator.remove(); } } }
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; } } START if (!jobDao.getJobsBySessionSeqIdAndStatus(sessionSeqId, JobExecutionStatus.STARTED).isEmpty()) { END return true; } return false; } lines 25-29 can be simplified to: return !jobDao.getJobsBySessionSeqIdAndStatus(sessionSeqId, JobExecutionStatus.STARTED).isEmpty();

Target:
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; } } return !jobDao.getJobsBySessionSeqIdAndStatus(sessionSeqId, JobExecutionStatus.STARTED).isEmpty(); }
Source:
protected void setClientTokenProvider(Quantum client) { String tenantName = START ((OpenstackNetworkProviderProperties) provider.getAdditionalProperties()).getTenantName(); END KeystoneTokenProvider keystoneTokenProvider = new KeystoneTokenProvider(provider.getAuthUrl(), provider.getUsername(), provider.getPassword()); client.setTokenProvider(keystoneTokenProvider.getProviderByTenant(tenantName)); } seems as unneeded cast

Target:
protected void setClientTokenProvider(Quantum client) { String tenantName = provider.getAdditionalProperties().getTenantName(); KeystoneTokenProvider keystoneTokenProvider = new KeystoneTokenProvider(provider.getAuthUrl(), provider.getUsername(), provider.getPassword()); client.setTokenProvider(keystoneTokenProvider.getProviderByTenant(tenantName)); }
Source:
protected Map<String, String> createPortAllocationRuntimeProperties(Port port) { Map<String, String> runtimeProperties = super.createPortAllocationRuntimeProperties(port); runtimeProperties.put("plugin_type", START ((OpenstackNetworkProviderProperties) END provider.getAdditionalProperties()).getPluginType()); return runtimeProperties; } seems as unneeded cast

Target:
protected Map<String, String> createPortAllocationRuntimeProperties(Port port) { Map<String, String> runtimeProperties = super.createPortAllocationRuntimeProperties(port); runtimeProperties.put("plugin_type", provider.getAdditionalProperties().getPluginType()); return runtimeProperties; }
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}); START assertThat(object.displayTypes(), is(expected)); END } Done

Target:
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(V4VmDisplayType.SPICE, V4VmDisplayType.VNC); assertEquals(object.displayTypes(), expected); }
Source:
public final void updateSessionLastActiveTime(String sessionId) { START if (StringUtils.isNotEmpty(sessionId) && isSessionExists(sessionId)) { END setData(sessionId, SESSION_LAST_ACTIVE_TIME, new Date()); } } Isn't the isSessionExists condition enough?

Target:
public final void updateSessionLastActiveTime(String sessionId) { if (isSessionExists(sessionId)) { setData(sessionId, SESSION_LAST_ACTIVE_TIME, new Date()); } }
Source:
public void setSpicePluginImplEnabled(boolean enabled, String reason) { START spicePluginImplRadioButton.setVisible(enabled);// Unsupported since 4.0 END spicePluginImplRadioButton.setEnabled(enabled); if (!enabled) { spicePluginImplRadioButtonTooltip.setText(reason); } } 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.

Target:
public void setSpicePluginImplEnabled(boolean enabled, String reason) { spicePluginImplRadioButton.setEnabled(enabled); if (!enabled) { spicePluginImplRadioButtonTooltip.setText(reason); } }
Source:
private Integer getAutoMaxBandwidthForCluster(Guid clusterId) { Integer qosBandwidth = getQosBandwidth(clusterId); if (qosBandwidth != null) { return qosBandwidth; } Integer linkSpeedBandwidth = getLinkSpeedBandwidth(clusterId); START return linkSpeedBandwidth; END } please inline linkSpeedBandwidth

Target:
private Integer getAutoMaxBandwidthForCluster(Guid clusterId) { Integer qosBandwidth = getQosBandwidth(clusterId); if (qosBandwidth != null) { return qosBandwidth; } return getLinkSpeedBandwidth(clusterId); }
Source:
public void testReadBooleans() { V4Vm object = objectFromJson("{'properties': [false, true]}"); List<Boolean> expected = Arrays.asList(false, true); START assertEquals(expected, object.properties()); END } Actually this should fail, because the input isn't a list of strings, and the type of "properties" is "String[]".

Target:
public void testReadBooleans() { objectFromJson("{'properties': [false, true]}"); }
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); START } END 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.

Target:
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(expected, booleans); }
Source:
protected void addVmToDb() { super.addVmToDb(); if (getVm().getOrigin() == OriginType.KVM) { ImportUtils.updateGraphicsDevices(getVm().getStaticData(), getStoragePool().getCompatibilityVersion()); START VmDeviceDao dao = DbFacade.getInstance().getVmDeviceDao(); END dao.saveAll(getVm().getStaticData().getManagedDeviceMap().values()); } } you can simply call getVmDeviceDao instead

Target:
protected void addVmToDb() { super.addVmToDb(); if (getVm().getOrigin() == OriginType.KVM) { ImportUtils.updateGraphicsDevices(getVm().getStaticData(), getStoragePool().getCompatibilityVersion()); getVmDeviceDao().saveAll(getVm().getStaticData().getManagedDeviceMap().values()); } }
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")); START this.isDefault = Boolean.valueOf(props.getProperty(Authn.ConfigKeys.DEFAULT.getUuid().getName(), "false")); END } Do we really need this? Can't we access extension configuration via its Properties instance, ie getContext().get(CONFIGURATION).getProperty(DEFAULT_PROFILE) ?

Target:
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")); }
Source:
public static long getSnapshotMemorySizeInBytes(VM vm) { long videoRam = (long)VideoDeviceSettings.totalVideoRAMSizeMb(vm) * 1024 * 1024; START return vm.getVmMemSizeMb() + 200 + videoRam; END } VM's memory size and the 200MB buffer should be converted to bytes as well

Target:
public static long getSnapshotMemorySizeInBytes(VM vm) { long videoRam = (long)VideoDeviceSettings.totalVideoRAMSizeMb(vm); return (vm.getVmMemSizeMb() + 200 + videoRam) * 1024 * 1024; }
Source:
public void disableAutoSetHostname() { START canAutoSetHostname = disableOnHostnameChanged ? canAutoSetHostname : false; END } it is correct but quite unusual... Please change to: if (!disableOnHostChanged) { canAutoSetHostname = false; }

Target:
public void disableAutoSetHostname() { if (!disableOnHostnameChanged) { canAutoSetHostname = false; } }
Source:
public CpuVendor getVendor() { final CpuVendor cpuVendor = CpuVendor.fromFlags(privateFlags); if (cpuVendor != null) { return cpuVendor; } START throw new RuntimeException("Unknown processor vendor. Flags: " + privateFlags); END } 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?

Target:
public CpuVendor getVendor() { return CpuVendor.fromFlags(privateFlags); }
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; START lastStoredKernelCmdline = null; END } why do we need to explicitly initialize them to null?

Target:
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; }
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, START hostProviderId, END currentKernelCmdline, kernelCmdlineParsable, lastStoredKernelCmdline, kernelCmdlineIommu, kernelCmdlineKvmNested, kernelCmdlinePciRealloc, kernelCmdlineUnsafeInterrupts ); } looks like a mistake, right?

Target:
public int hashCode() { return Objects.hash( id, hostName, consoleAddress, name, otpValidity, pmEnabled, pmKdumpDetection, port, protocol, sshPort, sshUsername, serverSslEnabled, uniqueId, clusterId, vdsStrength, vdsType, disablePowerManagementPolicy, hostProviderId, currentKernelCmdline, kernelCmdlineParsable, lastStoredKernelCmdline, kernelCmdlineIommu, kernelCmdlineKvmNested, kernelCmdlinePciRealloc, kernelCmdlineUnsafeInterrupts ); }
Source:
START protected Map<Guid, END 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(); } } why protected ?

Target:
private 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(); } }
Source:
public static boolean isHealingRequired(GlusterVolumeEntity volume) { for (GlusterBrickEntity brick : volume.getBricks()) { START if (brick.getUnSyncedEntries() != null && brick.getUnSyncedEntries() > 0) { END return true; } } return false; } The Java accepted check for not empty is: !brick.getUnSyncedEntries().isEmpty()

Target:
public static boolean isHealingRequired(GlusterVolumeEntity volume) { for (GlusterBrickEntity brick : volume.getBricks()) { if (brick.getUnSyncedEntries() > 0) { return true; } } return false; }
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() START .orElse(null); END if (result == null) { // This will never return but always throw a WebApplicationException notFound(); } return result; } This is really hard to read. Can you at least avoid the ternary operator?

Target:
private Network findCurrentNetwork(Map<Network, Set<Guid>> networks) { final Network result; if (networks == null) { result = null; } else { result = 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; }
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()) START : isVmQualifiedForLMOrImagesNotIllegal; END } return (!getParameters().isNeedsLocking() || validate(diskImagesValidator.diskImagesNotLocked())) && (getVm().isQualifiedForLiveSnapshotMerge() || validate(diskImagesValidator.diskImagesNotIllegal()));

Target:
protected boolean validateImages() { List<DiskImage> imagesToValidate = getDiskImagesToValidate(); DiskImagesValidator diskImagesValidator = new DiskImagesValidator(imagesToValidate); return (!getParameters().isNeedsLocking() || validate(diskImagesValidator.diskImagesNotLocked())) && (getVm().isQualifiedForLiveSnapshotMerge() || validate(diskImagesValidator.diskImagesNotIllegal())); }
Source:
private boolean validateClusterExistsForArchitecture(ArchitectureType architecture, StoragePool dataCenter) { if START (!clusterArchitecturesInDataCenters.get(dataCenter.getId()).contains(architecture)) END { showErrorPopup(constants.noClusterSupportingArchitectureInDC()); return false; } return true; } - 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

Target:
private boolean validateClusterExistsForArchitecture(ArchitectureType architecture, StoragePool dataCenter) { if (clusterArchitecturesInDataCenters == null || clusterArchitecturesInDataCenters.get(dataCenter.getId()) == null) { return true; } if (!clusterArchitecturesInDataCenters.get(dataCenter.getId()).contains(architecture)) { showErrorPopup(constants.noClusterSupportingArchitectureInDC()); return false; } return true; }
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; } START return -1; END } how about replacing it with switch-case statement?

Target:
public static int getCdDeviceIndex(String cdInterface) { switch (cdInterface) { case "scsi": return 0; case "ide": return 2; case "sata": return 0; default: return -1; } }
Source:
public AuditLogType getAuditLogTypeValue() { START this.addCustomValue("DiskAlias", END getDiskImage().getDiskAlias()); return getSucceeded() ? AuditLogType.USER_REGISTER_DISK_FINISHED_SUCCESS : AuditLogType.USER_REGISTER_DISK_FINISHED_FAILURE; } why do you need the "this."?

Target:
public AuditLogType getAuditLogTypeValue() { addCustomValue("DiskAlias", getDiskImage().getDiskAlias()); return getSucceeded() ? AuditLogType.USER_REGISTER_DISK_FINISHED_SUCCESS : AuditLogType.USER_REGISTER_DISK_FINISHED_FAILURE; }
Source:
public Cluster getCluster(Guid clusterId) { START return DbFacade.getInstance().getClusterDao().get(clusterId); END } change to getClusterDao()

Target:
public Cluster getCluster(Guid clusterId) { return getClusterDao().get(clusterId); }
Source:
private void createNewDiskId() { START Guid diskId = !getParameters().isUsePassedDiskId() ? Guid.newGuid() : getParameters().getDiskInfo().getId(); END getParameters().getDiskInfo().setId(diskId); if (!isFloatingDisk()) { getDiskVmElement().getId().setDeviceId(diskId); } } please switch to positive if

Target:
private void createNewDiskId() { Guid diskId = getParameters().isUsePassedDiskId() ? getParameters().getDiskInfo().getId() : Guid.newGuid(); getParameters().getDiskInfo().setId(diskId); if (!isFloatingDisk()) { getDiskVmElement().getId().setDeviceId(diskId); } }
Source:
public void removeDisk() { VdcReturnValueBase vdcReturnValue = Backend.getInstance().runInternalAction(VdcActionType.RemoveDisk, new RemoveDiskParameters(getParameters().getImageGroupID())); START getReturnValue().getVdsmTaskIdList().addAll(vdcReturnValue.getInternalVdsmTaskIdList()); END } this line is unneeded.

Target:
public void removeDisk() { VdcReturnValueBase vdcReturnValue = Backend.getInstance().runInternalAction(VdcActionType.RemoveDisk, new RemoveDiskParameters(getParameters().getImageGroupID())); }
Source:
protected void updateCurrentCd(String cdPath) { cdPath = START cdPath.isEmpty() ? END null : cdPath; VmHandler.updateCurrentCd(getVdsId(), getVm(), cdPath); } what if cdPath is already null?

Target:
protected void updateCurrentCd(String cdPath) { cdPath = StringUtils.isEmpty(cdPath) ? null : cdPath; VmHandler.updateCurrentCd(getVdsId(), getVm(), cdPath); }
Source:
public OvfUpdateProcessHelper(VmDeviceUtils vmDeviceUtils) { START Objects.requireNonNull(vmDeviceUtils); END this.vmDeviceUtils = vmDeviceUtils; this.ovfManager = new OvfManager(); } 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.

Target:
public OvfUpdateProcessHelper(VmDeviceUtils vmDeviceUtils) { this.vmDeviceUtils = vmDeviceUtils; this.ovfManager = new OvfManager(); }
Source:
public ValidationResult validateAddProvider() { ValidationResult result = validatePluginType(); if (!result.isValid()) { return result; } if START (!(result = validateAuthentication()).isValid()) END { return result; } return super.validateAddProvider(); } 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.

Target:
public ValidationResult validateAddProvider() { ValidationResult result = validatePluginType(); if (!result.isValid()) { return result; } result = validateAuthentication(); if (!result.isValid()) { return result; } return super.validateAddProvider(); }
Source:
public void completeDefaultIpConfiguration(IpConfiguration ipConfiguration) { START if (ipConfiguration.getIPv4Addresses().isEmpty()) { END final IPv4Address ipv4Address = NetworkCommonUtils.createDefaultIpv4Address(); ipConfiguration.setIPv4Addresses(Collections.singletonList(ipv4Address)); } if (ipConfiguration.getIpV6Addresses().isEmpty()) { final IpV6Address ipv6Address = NetworkCommonUtils.createDefaultIpv6Address(); ipConfiguration.setIpV6Addresses(Collections.singletonList(ipv6Address)); } } In case the 'ipConfiguration' is null, there will be NPE here.

Target:
private 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)); } }
Source:
START public void END refreshNetworks(ArrayList<VdcActionParametersBase> parameters) { if (!parameters.isEmpty()) { HostSetupNetworksParametersBuilder.updateParametersSequencing(parameters); runInternalMultipleActions(VdcActionType.PersistentHostSetupNetworks, parameters); } } please make it protected

Target:
protected void refreshNetworks(ArrayList<VdcActionParametersBase> parameters) { if (!parameters.isEmpty()) { HostSetupNetworksParametersBuilder.updateParametersSequencing(parameters); runInternalMultipleActions(VdcActionType.PersistentHostSetupNetworks, parameters); } }
Source:
START public NetworkAttachment END createNetworkAttachment(Network network, HostNetworkQos hostNetworkQos) { NetworkAttachment networkAttachment = new NetworkAttachment(); networkAttachment.setId(Guid.newGuid()); networkAttachment.setHostNetworkQos(hostNetworkQos); networkAttachment.setNetworkId(network.getId()); return networkAttachment; } Please make it private

Target:
private NetworkAttachment createNetworkAttachment(Network network, HostNetworkQos hostNetworkQos) { NetworkAttachment networkAttachment = new NetworkAttachment(); networkAttachment.setId(Guid.newGuid()); networkAttachment.setHostNetworkQos(hostNetworkQos); networkAttachment.setNetworkId(network.getId()); return networkAttachment; }