auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean removeVm() { VM vm = getVm(); Guid vmId = getVmId(); hasImages = vm.getDiskList().size() > 0; if (getParameters().isRemoveDisks() && hasImages) { if (!removeVmImages(null)) { return false; // We get here if we got imageDoesNotExistsInDomain for all the VM disks from VDSM. START } else if (getReturnValue().getTaskIdList().isEmpty()) { END endCommandWithoutTasks(); } } else { endCommandWithoutTasks(); } return true; } no need for the "else" word..it's just makes the code more confusing in my opinion.

Target:
private boolean removeVm() { VM vm = getVm(); hasImages = vm.getDiskList().size() > 0; if (getParameters().isRemoveDisks() && hasImages) { if (!removeVmImages(null)) { return false; } } else { endCommandWithoutTasks(); } return true; }
Source:
private boolean validateDestStorage(Guid imageId, Guid destDomainId) { DiskImage diskImage = getDiskImageById(imageId); START Guid storagePoolId = diskImage.getStoragePoolId().getValue(); END StorageDomainValidator validator = getValidator(destDomainId, storagePoolId); return validate(validator.isDomainExistAndActive()) && validate(validator.domainIsValidDestination()); } Why not using getStoragePoolId() instead fetching it from the disk

Target:
private boolean validateDestStorage(Guid imageId, Guid destDomainId) { StorageDomainValidator validator = getValidator(destDomainId, getStoragePoolId().getValue()); return validate(validator.isDomainExistAndActive()) && validate(validator.domainIsValidDestination()); }
Source:
public MockEJBStrategyRule(Map<BeanType, Object> beans) { START this(beans, new EnumMap<ContainerManagedResourceType,Object>(ContainerManagedResourceType.class));; END } You have an extra semicolon at the end here.

Target:
public MockEJBStrategyRule(Map<BeanType, Object> beans) { this(beans, new EnumMap<ContainerManagedResourceType,Object>(ContainerManagedResourceType.class)); }
Source:
START boolean validateVdsGroup() { END if (getVdsGroup() == null) { return failCanDoAction(VdcBllMessages.VDS_CLUSTER_IS_NOT_VALID); } return true; } please set a modifier - protected seem suitable

Target:
protected boolean validateVdsGroup() { if (getVdsGroup() == null) { return failCanDoAction(VdcBllMessages.VDS_CLUSTER_IS_NOT_VALID); } return true; }
Source:
START boolean isGlusterSupportEnabled() { END return getVdsGroup().supportsGlusterService() && getParameters().isGlusterPeerProbeNeeded(); } use protected access modifier instead of default (all-over)

Target:
protected boolean isGlusterSupportEnabled() { return getVdsGroup().supportsGlusterService() && getParameters().isGlusterPeerProbeNeeded(); }
Source:
private Provider getDeletedProvider() { if (deletedProvider == null) { START deletedProvider = getDbFacade().getProviderDao().get(getParameters().getProvider().getId()); END } return deletedProvider; } why not encapsulate with getProviderDao() and not getDbFacade().getProviderDao() ?

Target:
private Provider getDeletedProvider() { if (deletedProvider == null) { deletedProvider = getProviderDao().get(getParameters().getProvider().getId()); } return deletedProvider; }
Source:
public String getValue() { final StringBuilder val = new StringBuilder(); if (this.major > -1) START val.append(this.major); END appendVersionComponent(val, this.minor); appendVersionComponent(val, this.build); appendVersionComponent(val, this.revision); return val.toString(); } Why this is done outside the appendVersionComponent method? the logic looks same as other appended version parts.

Target:
public String getValue() { final StringBuilder val = new StringBuilder(); if (this.major > -1) { val.append(this.major); } appendVersionComponent(val, this.minor); appendVersionComponent(val, this.build); appendVersionComponent(val, this.revision); return val.toString(); }
Source:
START static void appendVersionComponent(StringBuilder val, int versionNumber) { END if (versionNumber > -1) { if (val.length() != 0) { val.append("."); } val.append(versionNumber); } } Is there a reason to make it static? And why isn't it declared as private method?

Target:
private static void appendVersionComponent(StringBuilder val, int versionNumber) { if (versionNumber > -1) { if (val.length() != 0) { val.append("."); } val.append(versionNumber); } }
Source:
START public VDSReturnValue runVdsCommand(VDSCommandType commandType, VDSParametersBase parameters) END throws VdcBLLException { VDSReturnValue returnValue = getBackendResourceManager().RunVdsCommand(commandType, parameters); if (!returnValue.getSucceeded()) { throw new VdcBLLException(returnValue.getVdsError().getCode(), returnValue.getVdsError() .getMessage()); } return returnValue; } Should this be protected?

Target:
protected VDSReturnValue runVdsCommand(VDSCommandType commandType, VDSParametersBase parameters) throws VdcBLLException { VDSReturnValue returnValue = getBackendResourceManager().RunVdsCommand(commandType, parameters); if (!returnValue.getSucceeded()) { throw new VdcBLLException(returnValue.getVdsError().getCode(), returnValue.getVdsError() .getMessage()); } return returnValue; }
Source:
protected void copyVmDevices() { START ArrayList<VmDevice> devices = new ArrayList<VmDevice>(vmFromConfiguration.getVmUnamagedDeviceList()); END devices.addAll(vmFromConfiguration.getManagedVmDeviceMap().values()); VmDeviceUtils.copyVmDevices(getVmIdFromSnapshot(), getVmId(), vmFromConfiguration, vmFromConfiguration.getStaticData(), true, devices, newDiskImages, _vmInterfaces); } devices can (and should) be defined as List<VmDevice> Also, I'd initialize the arraylist with FromConfiguration.getVmUnamagedDevic eList().size() + vmFromConfiguration.getManagedVmDeviceMap().size(), and then add both items, but it's a matter of taste.

Target:
protected void copyVmDevices() { List<VmDevice> devices = new ArrayList<VmDevice>(vmFromConfiguration.getVmUnamagedDeviceList()); devices.addAll(vmFromConfiguration.getManagedVmDeviceMap().values()); VmDeviceUtils.copyVmDevices(getVmIdFromSnapshot(), getVmId(), vmFromConfiguration, vmFromConfiguration.getStaticData(), true, devices, newDiskImages, _vmInterfaces); }
Source:
public MainTabBasicDetailsView(ApplicationResources resources) { START operatingSystem = new EnumLabel<VmOsType>(); END initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); Driver.driver.initialize(this); ViewIdHandler.idHandler.generateAndSetIds(this); } In this case you don't need to create the instance by yourself - remove the (provided = true) from the declaration, remove this operatingSystem = new EnumLabel<VmOsType>(); completely and than MainTabBasicDetailsView.ui.xml declare a new namespace like: xmlns:l="urn:import:org.ovirt.engine.ui.common.widget.label" and than you can replace <g:ValueLabel ui:field="operatingSystem"... by <l:EnumLabel ui:field="operatingSystem" ...

Target:
public MainTabBasicDetailsView(ApplicationResources resources) { initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); Driver.driver.initialize(this); ViewIdHandler.idHandler.generateAndSetIds(this); }
Source:
public String toString() { StringBuilder builder = new StringBuilder(50); builder.append("commandId: "); //$NON-NLS-1$ builder.append(getCommandId()); builder.append(", user: "); //$NON-NLS-1$ START builder.append(getParametersCurrentUser().getUserName()); END builder.append(", commandType: "); //$NON-NLS-1$ builder.append(getCommandType()); return builder.toString(); } Can't this cause NPE? what is the user in case of internal command?

Target:
public String toString() { StringBuilder builder = new StringBuilder(50); builder.append("commandId: "); //$NON-NLS-1$ builder.append(getCommandId()); builder.append(", user: "); //$NON-NLS-1$ if(getParametersCurrentUser() != null) { builder.append(getParametersCurrentUser().getUserName()); } builder.append(", commandType: "); //$NON-NLS-1$ builder.append(getCommandType()); return builder.toString(); }
Source:
private void debugAction(VdcActionType actionType, VdcActionParametersBase params) { if(log.isDebugEnabled()) { StringBuilder builder = new StringBuilder(50); builder.append("Action type: "); //$NON-NLS-1$ builder.append(actionType); builder.append(", Parameters: "); //$NON-NLS-1$ START builder.append(params); END } } missing "log.debug(builder.toString());"?

Target:
private void debugAction(VdcActionType actionType, VdcActionParametersBase params) { if(log.isDebugEnabled()) { StringBuilder builder = new StringBuilder(50); builder.append("Action type: "); //$NON-NLS-1$ builder.append(actionType); builder.append(", Parameters: "); //$NON-NLS-1$ builder.append(params); log.debug(builder.toString()); } }
Source:
private Guid getQuotaIdForDisk(DiskImage diskImage) { // If the DiskInfoDestinationMap is available and contains information about the disk if (getParameters().getDiskInfoDestinationMap() != null && getParameters().getDiskInfoDestinationMap().get(diskImage.getId()) != null) { return getParameters().getDiskInfoDestinationMap().get(diskImage.getId()).getQuotaId(); START } else { END return diskImage.getQuotaId(); } } consider removing else clause

Target:
private Guid getQuotaIdForDisk(DiskImage diskImage) { // If the DiskInfoDestinationMap is available and contains information about the disk if (getParameters().getDiskInfoDestinationMap() != null && getParameters().getDiskInfoDestinationMap().get(diskImage.getId()) != null) { return getParameters().getDiskInfoDestinationMap().get(diskImage.getId()).getQuotaId(); } return diskImage.getQuotaId(); }
Source:
private Locale getLocaleFromCookies(final Cookie[] cookies) { Locale locale = null; START if (null != cookies) { END for (Cookie cookie: cookies) { if (LOCALE.equalsIgnoreCase(cookie.getName())) { locale = LocaleUtils.getLocaleFromString(cookie.getValue()); break; } } } return locale; } Minor thing: please use "something <operator> null" convention.

Target:
private Locale getLocaleFromCookies(final Cookie[] cookies) { Locale locale = null; if (cookies != null) { for (Cookie cookie: cookies) { if (LOCALE.equalsIgnoreCase(cookie.getName())) { locale = LocaleUtils.getLocaleFromString(cookie.getValue()); break; } } } return locale; }
Source:
public void setMigrationMode(MigrationSupport value) { START for (Object migrationModeEntityModel : getMigrationMode().getItems()) { END if (((EntityModel)migrationModeEntityModel).getEntity() == value) { getMigrationMode().setSelectedItem(migrationModeEntityModel); break; } } } not needed after using Enum...

Target:
public void setMigrationMode(MigrationSupport value) { getMigrationMode().setSelectedItem(value); }
Source:
public static void GetVmsRunningOnOrMigratingToVds(AsyncQuery aQuery, Guid id) { aQuery.converterCallback = new IAsyncConverter() { @Override public Object Convert(Object source, AsyncQuery _asyncQuery) START { END ArrayList<VM> vms = (ArrayList<VM>) source; return vms; } }; Frontend.RunQuery(VdcQueryType.GetVmsRunningOnOrMigratingToVds, new GetVmsRunningOnOrMigratingToVdsParameters(id), aQuery); } this convert should do some logic (e.g. if the source is null than return emtpy list or something like this). Here it would be enough just to "return source;" or have no converter at all.

Target:
public static void GetVmsRunningOnOrMigratingToVds(AsyncQuery aQuery, Guid id) { aQuery.converterCallback = new IAsyncConverter() { @Override public Object Convert(Object source, AsyncQuery _asyncQuery) { if (source == null) { return new ArrayList<VM>(); } return source; } }; Frontend.RunQuery(VdcQueryType.GetVmsRunningOnOrMigratingToVds, new GetVmsRunningOnOrMigratingToVdsParameters(id), aQuery); }
Source:
private boolean managementNetworkModifiedCorrectly(VdsNetworkInterface iface) { START if (!Config.<String> GetValue(ConfigValues.ManagementNetwork).equals(iface.getNetworkName())) { END return true; } if (iface.getBootProtocol() == NetworkBootProtocol.STATIC_IP && vds.getHostName().matches(ValidationUtils.IP_PATTERN)) { return StringUtils.equals(vds.getHostName(), iface.getAddress()); } return true; } I don't think this check should be inside, rather outside in the if that is calling this method. Also, how about extracting this to method in NetworkUtils (there is already a very similar method there isManagementNetwork(Network) that you can extract a method isManagementNetwork(String) method from)?

Target:
private boolean managementNetworkModifiedCorrectly(VdsNetworkInterface iface) { if (iface.getBootProtocol() == NetworkBootProtocol.STATIC_IP && vds.getHostName().matches(ValidationUtils.IP_PATTERN)) { return StringUtils.equals(vds.getHostName(), iface.getAddress()); } return true; }
Source:
protected Guid getUpServerId() { if (brick == null) { START return super.getUpServerId(clusterId); END } VDS brickServer = getVdsDao().get(brick.getServerId()); if (brickServer.getStatus() == VDSStatus.Up) { return brickServer.getId(); } // brick server is down return super.getUpServerId(clusterId); } does super ref needed here?

Target:
protected Guid getUpServerId() { if (brick == null) { return getUpServerId(clusterId); } VDS brickServer = getVdsDao().get(brick.getServerId()); if (brickServer.getStatus() == VDSStatus.Up) { return brickServer.getId(); } // brick server is down return super.getUpServerId(clusterId); }
Source:
private GlusterVolumeAdvancedDetails fetchAdvancedDetails(String volumeName) { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetGlusterVolumeAdvancedDetails, new GlusterVolumeAdvancedDetailsVDSParameters(getUpServerId(), clusterId, START volumeName, END brick.getQualifiedName(), detailRequired)); return (GlusterVolumeAdvancedDetails) returnValue.getReturnValue(); } NPE possible here - as brick could be null. I think if brick is null, null should be passed to the method, so that advanceddetails of all bricks are fetched?

Target:
private GlusterVolumeAdvancedDetails fetchAdvancedDetails(String volumeName) { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetGlusterVolumeAdvancedDetails, new GlusterVolumeAdvancedDetailsVDSParameters(getUpServerId(), clusterId, volumeName, brick == null ? null : brick.getQualifiedName(), detailRequired)); return (GlusterVolumeAdvancedDetails) returnValue.getReturnValue(); }
Source:
private boolean networkRequiredOnVds(VmNetworkInterface vmIface, Map<String, Network> networksByName, boolean onlyRequiredNetworks) { boolean networkRequiredOnVds = true; if (!vmIface.isPlugged()) { networkRequiredOnVds = false; } else if (onlyRequiredNetworks) { Network network = networksByName.get(vmIface.getNetworkName()); START networkRequiredOnVds = network.getCluster().isRequired() && network.isVmNetwork(); END } return networkRequiredOnVds; } How does this make sense? How can you have non-vm network on a vNIC? I think this scenario should be blocked and not allowed to arrive to this state elsewhere.

Target:
private boolean networkRequiredOnVds(VmNetworkInterface vmIface, Map<String, Network> networksByName, boolean onlyRequiredNetworks) { boolean networkRequiredOnVds = true; if (!vmIface.isPlugged()) { networkRequiredOnVds = false; } else if (onlyRequiredNetworks) { networkRequiredOnVds = networksByName.get(vmIface.getNetworkName()).getCluster().isRequired(); } return networkRequiredOnVds; }
Source:
public VdsNotRespondingTreatmentCommand(T parameters) { super(parameters); START mVmList.addAll(getVmDAO().getAllMigratingToHost(getVdsId())); END } is there an option to move this from the ctor to other place? maybe even execute? its not a must but it feels not related to the ctor

Target:
public VdsNotRespondingTreatmentCommand(T parameters) { super(parameters); }
Source:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } List<VmDevice> watchdogs = getVmDeviceDao().getVmDeviceByVmIdAndType(getParameters().getVmId(), VmDeviceType.WATCHDOG.getName()); if (watchdogs.isEmpty()) { return failCanDoAction(VdcBllMessages.WATCHDOG_NOT_FOUND); } START return super.canDoAction(); END } you are calling super.canDoAction twice, i guess here it should be return true

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } List<VmDevice> watchdogs = getVmDeviceDao().getVmDeviceByVmIdAndType(getParameters().getId(), VmDeviceType.WATCHDOG.getName()); if (watchdogs.isEmpty()) { return failCanDoAction(VdcBllMessages.WATCHDOG_NOT_FOUND); } return true; }
Source:
protected void buildVmWatchdog() { START throw new NotImplementedException("not implemented"); END // Not supported in old code } why throwing exception?

Target:
protected void buildVmWatchdog() { // Not supported in old code }
Source:
protected void executeCommand() { List<VmDevice> watchdogs = getWatchdogs(); VmDevice watchdogDevice = watchdogs.get(0); // there must be only one watchdogDevice.setSpecParams(getSpecParams()); getVmDeviceDao().update(watchdogDevice); START setActionReturnValue(watchdogDevice); END setSucceeded(true); } setSucceeded(true) is enough in update command.

Target:
protected void executeCommand() { List<VmDevice> watchdogs = getWatchdogs(); VmDevice watchdogDevice = watchdogs.get(0); // there must be only one watchdogDevice.setSpecParams(getSpecParams()); getVmDeviceDao().update(watchdogDevice); setSucceeded(true); }
Source:
protected WatchDog doPopulate(WatchDog model, VmWatchdog entity) { model.setAction(entity.getAction() == null ? null : entity.getAction().name()); model.setModel(entity.getModel() == null ? null : entity.getModel().name()); model.setId(entity.getId().toString()); START return model; END } doPopulate() is used to execute additional queries to complete the entity, while what you did should reside in the WatchDogMapper.

Target:
protected WatchDog doPopulate(WatchDog model, VmWatchdog entity) { return model; }
Source:
protected <T> boolean matchEntity(VmWatchdog entity, T id) { //since there can be only one START return true; END } even if it's true, why not just ---> return entity.getId().equals(id); why to cut corners?

Target:
protected <T> boolean matchEntity(VmWatchdog entity, T id) { return entity.getId().equals(id); }
Source:
private CommandManager() { executionContextMap = CacheProviderFactory.<NGuid, ExecutionContext>getCacheWrapper(EXECUTION_CONTEXT_MAP_NAME); START commandMap = CacheProviderFactory.<NGuid, CommandEntity>getCacheWrapper(COMMAND_MAP_NAME); END } Bare in mind that for External task injection feature, Eli is going to introduce a map from jobId to ExecutionContext. In addition, if ExecutionContext gets evicted (due to LFU - btw, should this be LFU or LRU? ) - how are we going to restore the context due to "cache miss"? can you please elaborate?

Target:
private CommandManager() { executionContextMap = CacheProviderFactory.<NGuid, ExecutionContext>getCacheWrapper(EXECUTION_CONTEXT_MAP_NAME); }
Source:
private String getFullPath(final String path) { String result = null; if (ServletUtils.isSane(path)) { List<BrandingTheme> brandingPaths = brandingManager. getBrandingThemes(); for (BrandingTheme brandingTheme: brandingPaths) { START if (path.startsWith(brandingTheme.getPath())) { END result = brandingManager.getBrandingRootPath(). getAbsolutePath() + path; } } } else { log.error("The path \"" + path //$NON-NLS-1$ + "\" is not sane"); //$NON-NLS-1$ } return result; } Instead of iterating over List<BrandingTheme> on every request, you can use Map<String, BrandingTheme> - mapping brandingTheme.getPath() to corresponding BrandingTheme instance. This is to avoid O(n) access due to iteration, in favor of O(1) access due to map value access, with regard to appropriate BrandingTheme instance.

Target:
String getFullPath(final String path) { String result = null; if (ServletUtils.isSane(path)) { // Return a result relative to the branding root path. result = brandingManager.getBrandingRootPath().getAbsolutePath() + path; } else { log.error("The path \"" + path + "\" is not sane"); //$NON-NLS-1$ //$NON-NLS-2$ } return result; }
Source:
START protected MessageDigest getMd5Digest(final HttpServletRequest request) END throws NoSuchAlgorithmException { MessageDigest digest = createMd5Digest(); for (MD5Attributes attribute: MD5Attributes.values()) { if (request.getAttribute(attribute.getAttributeKey()) != null) { digest.update(request.getAttribute(attribute.getAttributeKey()). toString().getBytes()); } } return digest; } Excellent change! +1

Target:
protected MessageDigest getMd5Digest(final HttpServletRequest request) throws NoSuchAlgorithmException { MessageDigest digest = createMd5Digest(); for (MD5Attributes attribute: MD5Attributes.values()) { if (request.getAttribute(attribute.getKey()) != null) { digest.update(request.getAttribute(attribute.getKey()). toString().getBytes()); } } return digest; }
Source:
public BrandingManager(final File etcDir) { START brandingRootPath = new File(etcDir + BRANDING_PATH); END } new File(etcDir, BRANDING_PATH) and remove / from BRANDING_PATH

Target:
public BrandingManager(final File etcDir) { brandingRootPath = new File(etcDir, BRANDING_PATH); }
Source:
public KeyMaker(String vmId, ConsoleContext context) { START super(); END this.vmId = vmId; this.context = context; } no need to call super

Target:
public KeyMaker(String vmId, ConsoleContext context) { this.vmId = vmId; this.context = context; }
Source:
protected boolean isVmNotLocked() { return getVmId() != null && START validate(new VmValidator(getVm()).vmNotLocked()); END } even after getVmId() is checked, getVm() can return null here and cause to NPE.

Target:
protected boolean isVmNotLocked() { return getVm() != null && validate(new VmValidator(getVm()).vmNotLocked()); }
Source:
protected boolean canDoAction() { disk = getDiskDao().get(getParameters().getDiskId()); return isVmExist() && isVmInUpPausedDownStatus() && isDiskExist(disk) && checkCanPerformPlugUnPlugDisk() && isVmNotInPreviewSnapshot() && START isVmNotLocked(); END } it's already checked that the vm is up/paused/down in line 45..so you will never reach here with the vm locked.

Target:
protected boolean canDoAction() { disk = getDiskDao().get(getParameters().getDiskId()); return isVmExist() && isVmInUpPausedDownStatus() && isDiskExist(disk) && checkCanPerformPlugUnPlugDisk() && isVmNotInPreviewSnapshot(); }
Source:
protected Version getStoragePoolClusterLevel(Guid StoragePoolId) { START StoragePool storagePool = DbFacade.getInstance().getStoragePoolDao().get(StoragePoolId); END if (storagePool != null) { return storagePool.getcompatibility_version(); } else { log.errorFormat( "IrsBroker::getStoragePoolClusterLevel:: Could not find master domain for pool {0} !!!", getParameters().getStoragePoolId()); return null; } } Would be awesome if you add a method of getStoragePoolDao() that will return DbFacade.getInstance().getStoragePoolDao. I promised you an explanation on why , and I will provide it (it will make mocking life easier, and a better step towards Dependency injection).

Target:
protected Version getStoragePoolClusterLevel(Guid StoragePoolId) { StoragePool storagePool = getStoragePoolDao().get(StoragePoolId); if (storagePool != null) { return storagePool.getcompatibility_version(); } else { log.errorFormat( "IrsBroker::getStoragePoolClusterLevel:: Could not find master domain for pool {0} !!!", getParameters().getStoragePoolId()); return null; } }
Source:
public void edit(final HostBondInterfaceModel object) { super.edit(object); // hide widgets info.setVisible(false); message.setVisible(false); START checkConnectivity.setVisible(false); END commitChanges.setVisible(false); // resize layoutPanel.remove(infoPanel); layoutPanel.setWidgetSize(mainPanel, 300); asPopupPanel().setPixelSize(400, 400); } Redundant, you already did getCheckConnectivity().setIsAvailable(false) in SetupNetworksBondPopupView

Target:
public void edit(final HostBondInterfaceModel object) { super.edit(object); // hide widgets info.setVisible(false); message.setVisible(false); // resize layoutPanel.remove(infoPanel); layoutPanel.setWidgetSize(mainPanel, 300); asPopupPanel().setPixelSize(400, 400); }
Source:
private void checkEntityForRollback(BusinessEntity<?> entity) { if(entity == null) { throw new IllegalArgumentException("Can not create snapshot from a null entity"); } START Class<? extends BusinessEntity> entityClazz = entity.getClass(); END if(DbFacade.getInstance().getDaoForEntity((Class<BusinessEntity<Serializable>>)entityClazz) == null) { throw new IllegalArgumentException("There is no rollback DAO registered for entity type "+entityClazz.getName()); } } I'd call the variable entityClass

Target:
private void checkEntityForRollback(BusinessEntity<?> entity) { if(entity == null) { throw new IllegalArgumentException("Can not create snapshot from a null entity"); } if (DbFacade.getInstance().getDaoForEntity((Class<BusinessEntity<Serializable>>) entity.getClass()) == null) { throw new IllegalArgumentException("There is no rollback DAO registered for entity type " + entity.getClass().getName()); } }
Source:
public Object mapFromContext(Object ctx) { if (ctx == null) { return null; } DirContextAdapter searchResult = (DirContextAdapter) ctx; Attributes attributes = searchResult.getAttributes(); if (attributes == null) { return null; } try { return attributes.get("uid").get(0); } catch (NamingException e) { START System.err.println(ERROR_PREFIX + "Failed getting user GUID"); END return null; } } Please replace this ^ with "log.error(...)".

Target:
public Object mapFromContext(Object ctx) { if (ctx == null) { return null; } DirContextAdapter searchResult = (DirContextAdapter) ctx; Attributes attributes = searchResult.getAttributes(); if (attributes == null) { return null; } try { return attributes.get("uid").get(0); } catch (NamingException e) { log.error(ERROR_PREFIX + "Failed getting user GUID"); return null; } }
Source:
public void setTotalDiskSize(Integer value) { START value = (value == null) ? new Integer(0) : value; END if (!totalDiskSize.equals(value)) { totalDiskSize = value; } } This will produce a Number Constructor FindBugs warning. Please use Integer.valueOf(0)

Target:
public void setTotalDiskSize(Integer value) { value = (value == null) ? Integer.valueOf(0) : value; if (!totalDiskSize.equals(value)) { totalDiskSize = value; } }
Source:
private static Double assignDoubleValueWithNullProtection(XmlRpcStruct input, String name) { Double doubleValue = AssignDoubleValue(input, name); START return (doubleValue == null ? new Double(0.0) : doubleValue); END } Here too - use Double.valueOf(0.0)

Target:
private static Double assignDoubleValueWithNullProtection(XmlRpcStruct input, String name) { Double doubleValue = AssignDoubleValue(input, name); return (doubleValue == null ? Double.valueOf(0.0) : doubleValue); }
Source:
public GetQuotaByQuotaIdQueryParameters(Guid quotaId) { START this(); END this.quotaId = quotaId; } Remove the call to this();

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

Target:
public Guid persistAsyncTaskPlaceHolder(VdcActionType parentCommand) { Guid retValue = Guid.Empty; try { AsyncTasks task = createAsyncTask(new AsyncTaskCreationInfo(), parentCommand); retValue = task.getTaskId(); AsyncTaskUtils.addOrUpdateTaskInDB(task, null, EMPTY_GUID_ARRAY); } catch (RuntimeException ex) { log.errorFormat("Error during persistAsyncTaskPlaceHolders for command: {0}. Exception {1}", getClass().getName(), ex); } return retValue; }
Source:
public void Cluster_SelectedItemChanged() { UpdateDefaultHost(); updateCustomPropertySheet(); UpdateMinAllocatedMemory(); UpdateNumOfSockets(); START if ((VmTemplate) getModel().getTemplate().getSelectedItem() != null) { END VmTemplate template = (VmTemplate) getModel().getTemplate().getSelectedItem(); updateQuotaByCluster(template.getQuotaId(), template.getQuotaName()); } updateCpuPinningVisibility(); } redundant cast

Target:
public void Cluster_SelectedItemChanged() { UpdateDefaultHost(); updateCustomPropertySheet(); UpdateMinAllocatedMemory(); UpdateNumOfSockets(); if (getModel().getTemplate().getSelectedItem() != null) { VmTemplate template = (VmTemplate) getModel().getTemplate().getSelectedItem(); updateQuotaByCluster(template.getQuotaId(), template.getQuotaName()); } updateCpuPinningVisibility(); }
Source:
protected void ExecuteVdsBrokerCommand() { START status = getBroker().desktopLogoff(mVmId.toString(), (Boolean.valueOf(mForce)).toString()); END ProceedProxyReturnValue(); } Instead of using Boolean.valueOf(boolean).toString(), just use String.valueOf(boolean)

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

Target:
protected void ExecuteVdsBrokerCommand() { if (getParameters().getGracefully()) { status = getBroker().shutdown(getParameters().getVmId().toString(), String.valueOf(getParameters().getSecondsToWait()), Config.<String> GetValue(ConfigValues.VmGracefulShutdownMessage)); } else { status = getBroker().destroy(getParameters().getVmId().toString()); } ProceedProxyReturnValue(); }
Source:
private static void addBootOrder(VmDevice vmDevice, Map<String, Object> struct) { START String s = Integer.valueOf(vmDevice.getBootOrder()).toString(); END if (!org.apache.commons.lang.StringUtils.isEmpty(s) && !s.equals("0")) { struct.put(VdsProperties.BootOrder, s); } } Instead of Integer.valueOf(int).toString(), just use String.valueOf(int)

Target:
private static void addBootOrder(VmDevice vmDevice, Map<String, Object> struct) { String s = String.valueOf(vmDevice.getBootOrder()); if (!org.apache.commons.lang.StringUtils.isEmpty(s) && !s.equals("0")) { struct.put(VdsProperties.BootOrder, s); } }
Source:
public void setLunId(String value) { START if (!privateLunId.equals(value)) END { privateLunId = value; onPropertyChanged(new PropertyChangedEventArgs("LUN ID")); //$NON-NLS-1$ } } nullity check here too :)

Target:
public void setLunId(String value) { if (privateLunId != null && !privateLunId.equals(value)) { privateLunId = value; onPropertyChanged(new PropertyChangedEventArgs("LUN ID")); //$NON-NLS-1$ } }
Source:
private boolean isEntityModelEmpty(EntityModel model) { START return !(model.getEntity() != null && !model.getEntity().equals("")); END } Save the null check: !"".equals(model.getEntity())

Target:
private boolean isEntityModelEmpty(EntityModel model) { return !(!"".equals(model.getEntity())); }
Source:
private void handleError(Exception e, VDSStatus status) { log.errorFormat( "Host installation failed for host {0}, {1}.", getVds().getId(), getVds().getName(), e ); setVdsStatus(status); setSucceeded(false); _failureMessage = getErrorMessage(e.getMessage()); START addCustomValue("FailedInstallMessage", _failureMessage); END } Since you already extracted this code, you should notice that this line is redundant and already done on line 80. Also the getError message on the line above is done on line 80 anyway.. For your consideration

Target:
private void handleError(Exception e, VDSStatus status) { log.errorFormat( "Host installation failed for host {0}, {1}.", getVds().getId(), getVds().getName(), e ); setVdsStatus(status); setSucceeded(false); _failureMessage = e.getMessage(); }
Source:
public void setManagementNetwork(String managementNetwork) { START this._managementNetwork = managementNetwork; END } Why do you need "this." ?

Target:
public void setManagementNetwork(String managementNetwork) { _managementNetwork = managementNetwork; }
Source:
public static String combine(String head, List<ParametersSet> params) { START StringBuilder combined_params = new StringBuilder(""); END if (params != null) { for (ParametersSet ps : params) { for (Parameter param : ps.getParameters()) { combined_params.append(String.format(MATRIX_PARAMETER_TEMPLATE, param.getName(), param.getValue())); } } } combined_params.insert(0, head); return combined_params.toString(); } The empty string in the constructor is redundant.

Target:
public static String combine(String head, List<ParametersSet> params) { StringBuilder combined_params = new StringBuilder(); if (params != null) { for (ParametersSet ps : params) { for (Parameter param : ps.getParameters()) { combined_params.append(String.format(MATRIX_PARAMETER_TEMPLATE, param.getName(), param.getValue())); } } } combined_params.insert(0, head); return combined_params.toString(); }
Source:
String getFormattedNote() { StringBuilder formattedNote = new StringBuilder(constants.empty()); for (int i = 0; i < notes.size(); i++) { String note = notes.get(i); formattedNote.append(constants.lineBreak()); formattedNote.append(constants.htmlTab()); START formattedNote.append(note); END } return formattedNote.toString(); } Consider doing this in a single line: formattedNote.append(constants.lineBreak().append(constants.htmlTab().append(note);

Target:
String getFormattedNote() { StringBuilder formattedNote = new StringBuilder(constants.empty()); for (int i = 0; i < notes.size(); i++) { String note = notes.get(i); formattedNote.append(constants.lineBreak()).append(constants.htmlTab()).append(note); } return formattedNote.toString(); }
Source:
public BootSequence getSequence() { START StringBuilder str = new StringBuilder(""); //$NON-NLS-1$ END for (EntityModel a : getItems()) { if (a.getIsChangable()) { BootSequence bs = (BootSequence) a.getEntity(); str.append(bs.toString()); } } return !str.equals("") ? BootSequence.valueOf(str.toString()) : null; //$NON-NLS-1$ } The empty string here is redundent

Target:
public BootSequence getSequence() { StringBuilder str = new StringBuilder(); for (EntityModel a : getItems()) { if (a.getIsChangable()) { BootSequence bs = (BootSequence) a.getEntity(); str.append(bs.toString()); } } return !str.equals("") ? BootSequence.valueOf(str.toString()) : null; //$NON-NLS-1$ }
Source:
private void clearAsyncTasksWithOutVdsmId() { for (Guid asyncTaskId : getReturnValue().getAsyncTaskIdList()) { START AsyncTasks task = DbFacade.getInstance().getAsyncTaskDao().get(asyncTaskId); END if (task.getVdsmTaskId().equals(NGuid.Empty)) { AsyncTaskManager.failTaskWithoutVdsmId(task); } } } /s/DbFacade.getInstance().getAsyncTaskDao()/getAsyncTaskDao

Target:
private void clearAsyncTasksWithOutVdsmId() { for (Guid asyncTaskId : getReturnValue().getAsyncTaskIdList()) { AsyncTasks task = getAsyncTaskDao().get(asyncTaskId); if (task.getVdsmTaskId().equals(NGuid.Empty)) { AsyncTaskManager.failTaskWithoutVdsmId(task); } } }
Source:
public HashCodeBuilder(final int prime) { START super(); END this.prime = prime; } IMHO, the explicit Object constructor is redundant.

Target:
public HashCodeBuilder(final int prime) { this.prime = prime; }
Source:
protected void revertTask() { // Preventing rollback on VmReplicateDiskFinish success // (checks whether the disk moved successfully to the target storage domain) Guid targetStorageDomainId = getEnclosingCommand().getParameters().getTargetStorageDomainId(); Guid destinationImageId = getEnclosingCommand().getParameters().getDestinationImageId(); DiskImage diskImage = getDiskImageDao().get(destinationImageId); START if (diskImage != null && diskImage.getStorageIds().get(0) == targetStorageDomainId) { END getEnclosingCommand().getParameters().setExecutionIndex(0); } } Use equals - there is no guarantee that it's the same Guid instance.

Target:
protected void revertTask() { // Preventing rollback on VmReplicateDiskFinish success // (checks whether the disk moved successfully to the target storage domain) Guid targetStorageDomainId = getEnclosingCommand().getParameters().getTargetStorageDomainId(); Guid destinationImageId = getEnclosingCommand().getParameters().getDestinationImageId(); DiskImage diskImage = getDiskImageDao().get(destinationImageId); if (diskImage != null && targetStorageDomainId.equals(diskImage.getStorageIds().get(0))) { getEnclosingCommand().getParameters().setExecutionIndex(0); } }
Source:
public BootSequence getSequence() { StringBuilder str = new StringBuilder(); for (EntityModel a : getItems()) { if (a.getIsChangable()) { BootSequence bs = (BootSequence) a.getEntity(); str.append(bs.toString()); } } String bootStr = str.toString(); if (!bootStr.equals("")) { //$NON-NLS-1$ return BootSequence.valueOf(bootStr); } START return null; END } Is it just for replacing the ternary if? why is it better?

Target:
public BootSequence getSequence() { StringBuilder str = new StringBuilder(); for (EntityModel a : getItems()) { if (a.getIsChangable()) { BootSequence bs = (BootSequence) a.getEntity(); str.append(bs.toString()); } } return !str.toString().equals("") ? BootSequence.valueOf(str.toString()) : null; //$NON-NLS-1$ }
Source:
public AuditLogType getAuditLogTypeValue() { return getSucceeded() ? (disksLeftInVm.isEmpty() ? AuditLogType.USER_REMOVE_VM_FINISHED : AuditLogType.USER_REMOVE_VM_FINISHED_WITH_ILLEGAL_DISKS) START : AuditLogType.USER_FAILED_REMOVE_VM; END } Remove VM will always take place audit log should be removed

Target:
public AuditLogType getAuditLogTypeValue() { return getSucceeded() ? AuditLogType.USER_REMOVE_VM_FINISHED : AuditLogType.USER_REMOVE_VM_FINISHED_WITH_ILLEGAL_DISKS; }
Source:
public void testMemoryMapping() { VDS vds = new VDS(); vds.setId(Guid.Empty); vds.setPhysicalMemMb(4000); Host host = HostMapper.map(vds, (Host) null); assertNotNull(host.getMemory()); START assertEquals(host.getMemory().longValue(), 4194304000L); END } potential NPE, host.getMemory() can be NULL instead please remove Long.valueOf() from host.getMemory() and make Long from 4194304000L.

Target:
public void testMemoryMapping() { VDS vds = new VDS(); vds.setId(Guid.Empty); vds.setPhysicalMemMb(4000); Host host = HostMapper.map(vds, (Host) null); assertNotNull(host.getMemory()); assertEquals(host.getMemory(), Long.valueOf(4194304000L)); }
Source:
protected void updateModelDataCenterFromVds(ArrayList<StoragePool> dataCenters, VDS vds) { START if (dataCenters != null && vds.getStoragePoolId() != null) END { getDataCenter().setItems(dataCenters); getDataCenter().setSelectedItem(Linq.firstOrDefault(dataCenters, new Linq.DataCenterPredicate(vds.getStoragePoolId()))); if (getDataCenter().getSelectedItem() == null) { getDataCenter().setSelectedItem(Linq.firstOrDefault(dataCenters)); } } } Why do you need to check- vds.getStoragePoolId() != null ?

Target:
protected void updateModelDataCenterFromVds(ArrayList<StoragePool> dataCenters, VDS vds) { if (dataCenters != null) { getDataCenter().setItems(dataCenters); getDataCenter().setSelectedItem(Linq.firstOrDefault(dataCenters, new Linq.DataCenterPredicate(vds.getStoragePoolId()))); if (getDataCenter().getSelectedItem() == null) { getDataCenter().setSelectedItem(Linq.firstOrDefault(dataCenters)); } } }
Source:
protected void executeCommand() { VDSGroup vdsGroup = getVdsGroup(); boolean initSucceeded = true; if (vdsGroup.supportsTrustedService()) { START setSucceeded(initTrustedService()); END } if (vdsGroup.supportsVirtService()) { initSucceeded = initVirtResources(); } if (initSucceeded && vdsGroup.supportsGlusterService()) { initSucceeded = initGlusterHost(); } setSucceeded(initSucceeded); } Done

Target:
protected void executeCommand() { VDSGroup vdsGroup = getVdsGroup(); boolean initSucceeded = true; if (vdsGroup.supportsTrustedService()) { initSucceeded = initTrustedService(); } if (initSucceeded && vdsGroup.supportsVirtService()) { initSucceeded = initVirtResources(); } if (initSucceeded && vdsGroup.supportsGlusterService()) { initSucceeded = initGlusterHost(); } setSucceeded(initSucceeded); }
Source:
public UrlValidation(String[] allowedSchemes) { if (allowedSchemes == null) { this.allowedSchemes.add(new String()); START } else for (String scheme : allowedSchemes) { END this.allowedSchemes.add(scheme.toLowerCase()); } } Please format this code correctly. Enter and { after else.

Target:
public UrlValidation(String[] allowedSchemes) { if (allowedSchemes == null) { this.allowedSchemes.add(new String()); } else { for (String scheme : allowedSchemes) { this.allowedSchemes.add(scheme.toLowerCase()); } } }
Source:
private String getTemplateExclusiveLockMessage() { START if (getVmTemplate() != null) { END return new StringBuilder(VdcBllMessages.ACTION_TYPE_FAILED_TEMPLATE_IS_BEING_REMOVED.name()) .append(String.format("$TemplateName %1$s", getVmTemplate().getName())) .toString(); } return VdcBllMessages.ACTION_TYPE_FAILED_OBJECT_LOCKED.name(); } if the template is null, the can-do-action checks will fail the command. so it might be better to check whether the template is null or not in #getExclusiveLocks(), and in case it is null to return null there, so that we won't even build the engine lock and acquire it.

Target:
private String getTemplateExclusiveLockMessage() { return new StringBuilder(VdcBllMessages.ACTION_TYPE_FAILED_TEMPLATE_IS_BEING_REMOVED.name()) .append(String.format("$TemplateName %1$s", getVmTemplate().getName())) .toString(); }
Source:
START private boolean isIsoVersionSupported(Version isoVersion, OVirtNodeInfo Info) { END boolean result = false; Version supported = new Version(Info.minimumVersion); if (isoVersion.compareTo(supported) > 0) { result = true; } return result; } Why have you removed the static?

Target:
private static boolean isIsoVersionSupported(Version isoVersion, OVirtNodeInfo Info) { boolean result = false; Version supported = new Version(Info.minimumVersion); if (isoVersion.compareTo(supported) > 0) { result = true; } return result; }
Source:
private boolean isNewerVersion(Version isoClusterVersion) { VDS vds = getVdsByVdsId(getParameters().getVdsId()); Version vdsClusterVersion = vds.getVdsGroupCompatibilityVersion(); log.debugFormat( "vdsClusterVersion {0} isoClusterVersion {1}", vdsClusterVersion.toString(), START isoClusterVersion.toString() END ); return (vdsClusterVersion.getMajor() == isoClusterVersion.getMajor() && vdsClusterVersion.getMinor() <= isoClusterVersion.getMinor()); } I think (or want to believe) that the .toString() is implicit when formatting, hence can be removed from here.

Target:
private boolean isNewerVersion(Version isoClusterVersion) { VDS vds = getVdsByVdsId(getParameters().getVdsId()); Version vdsClusterVersion = vds.getVdsGroupCompatibilityVersion(); log.debugFormat( "vdsClusterVersion {0} isoClusterVersion {1}", vdsClusterVersion, isoClusterVersion ); return (vdsClusterVersion.getMajor() == isoClusterVersion.getMajor() && vdsClusterVersion.getMinor() <= isoClusterVersion.getMinor()); }
Source:
public static synchronized OVirtNodeInfo getInstance() { if (instance == null) { START instance = new OVirtNodeInfo(); END } return instance; } please add sync protection, see EngineLocalConfig.

Target:
public static synchronized OVirtNodeInfo getInstance() { if (instance == null) { instance = new OVirtNodeInfo(); } else { if (instance == null) { synchronized(OVirtNodeInfo.class) { if (instance == null) { instance = new OVirtNodeInfo(); } } } } return instance; }
Source:
START private Pattern getIsoPattern(OVirtNodeInfo info) { END log.infoFormat("getIsoPatter - pattern [{0}]", info.pattern); String expectedPattern = info.pattern; if (isoPattern == null || !expectedPattern.equals(isoPattern.toString())) { isoPattern = Pattern.compile(expectedPattern); } return isoPattern; } why have you removed the static?

Target:
private static Pattern getIsoPattern(OVirtNodeInfo info) { String expectedPattern = info.pattern; if (isoPattern == null || !expectedPattern.equals(isoPattern.toString())) { isoPattern = Pattern.compile(expectedPattern); } return isoPattern; }
Source:
public static VmPropertiesUtils getInstance() { START if (vmPropertiesUtils == null) { END synchronized (VmPropertiesUtils.class) { if (vmPropertiesUtils == null) { vmPropertiesUtils = new VmPropertiesUtils(); } } } return vmPropertiesUtils; } While you're at it, fix the initialization here, same way as you did with the singleton for Device Custom Properties.

Target:
public static VmPropertiesUtils getInstance() { return vmPropertiesUtils; }
Source:
protected void executeCommand() { if (!(Guid.isNullOrEmpty(clusterId))) { performActionForServicesOfCluster(); } else if (!(Guid.isNullOrEmpty(serverId))) { performActionForServicesOfServer(); START } END } what if the user provides both cluterId and serverId?. So you could swap the above comparisons.

Target:
protected void executeCommand() { if (!(Guid.isNullOrEmpty(serverId))) { performActionForServicesOfServer(); } else if (!(Guid.isNullOrEmpty(clusterId))) { performActionForServicesOfCluster(); } }
Source:
public void canDoActionFails() { GlusterServiceParameters params = new GlusterServiceParameters(); params.setActionType("InvalidActionType"); cmd = spy(new ManageGlusterServiceCommand(params)); assertFalse(cmd.canDoAction()); params.setServiceType(ServiceType.SMB); cmd = spy(new ManageGlusterServiceCommand(params)); assertFalse(cmd.canDoAction()); START END params.setClusterId(null); params.setServerId(null); assertFalse(cmd.canDoAction()); } You can move these to separate tests. You can also verify the error message returned from canDoAction

Target:
public void canDoActionFails() { GlusterServiceParameters params = new GlusterServiceParameters(); params.setActionType("InvalidActionType"); cmd = spy(new ManageGlusterServiceCommand(params)); assertFalse(cmd.canDoAction()); params.setClusterId(null); params.setServerId(null); assertFalse(cmd.canDoAction()); }
Source:
private void extendDiskImageSize() { lockImageInDb(); START VdcReturnValueBase ret = getBackend().runInternalAction( END VdcActionType.ExtendImageSize, createExtendImageSizeParameters(), ExecutionHandler.createDefaultContexForTasks(getExecutionContext()) ); if (ret.getSucceeded()) { getReturnValue().getTaskIdList().addAll(ret.getInternalTaskIdList()); } else { propagateInternalCommandFailure(ret); unlockImageInDb(); getReturnValue().setFault(ret.getFault()); } setSucceeded(ret.getSucceeded()); } the CDA messages of the extend won't be displayed in the CDA phase.

Target:
private void extendDiskImageSize() { lockImageInDb(); VdcReturnValueBase ret = getBackend().runInternalAction( VdcActionType.ExtendImageSize, createExtendImageSizeParameters(), ExecutionHandler.createDefaultContexForTasks(getExecutionContext()) ); if (ret.getSucceeded()) { getReturnValue().getTaskIdList().addAll(ret.getInternalTaskIdList()); } else { propagateInternalCommandFailure(ret); getReturnValue().setFault(ret.getFault()); } setSucceeded(ret.getSucceeded()); }
Source:
public String[] getCompletion(String wordPart) { if (wordPart == null || wordPart.isEmpty()) { return EMPTY_COMPLETION_LIST; } List<String> list = new ArrayList<String>(); for (String osName : OsRepositoryImpl.INSTANCE.getOsNames().values()) { if (osName.startsWith(wordPart)) { list.add(osName); } } START return list.toArray(new String[]{}); END } well, I would prefer list.toArray(new String[list.size()]) - you save one instance :)

Target:
public String[] getCompletion(String wordPart) { if (wordPart == null || wordPart.isEmpty()) { return EMPTY_COMPLETION_LIST; } List<String> list = new ArrayList<String>(); for (String osName : map.values()) { if (osName.startsWith(wordPart)) { list.add(osName); } } return list.toArray(new String[]{}); }
Source:
public void updateNetworks(final Guid vmId, final List<NicWithLogicalNetworks> nicsWithLogicalNetworks) { ArrayList<VdcActionParametersBase> parameters = createAddVmInterfaceParams(vmId, nicsWithLogicalNetworks); START if (parameters.size() == 0) { END callback.networkCreated(); return; } updateNetworksFromParams(vmId, parameters); } updateNetworksFromParams() has the same code. Why do you also need it here?

Target:
public void updateNetworks(final Guid vmId, final List<NicWithLogicalNetworks> nicsWithLogicalNetworks) { updateNetworksFromParams(vmId, createAddVmInterfaceParams(vmId, nicsWithLogicalNetworks)); }
Source:
private void onSave() { if (!validate()) { return; } flush(); START Frontend.RunAction(action, new ProviderParameters(provider), null, true); END cancel(); } Why do you need this addition? Isn't it the default?

Target:
private void onSave() { if (!validate()) { return; } flush(); Frontend.RunAction(action, new ProviderParameters(provider)); cancel(); }