auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected VDS getEntity(int index) { START VDS vds = setUpEntityExpectations(control.createMock(VDS.class), control.createMock(RpmVersion.class), index); END VdsStatic vdsStatic = control.createMock(VdsStatic.class); expect(vdsStatic.getId()).andReturn(GUIDS[2]).anyTimes(); expect(vds.getStaticData()).andReturn(vdsStatic).anyTimes(); return vds; } i'd create rpmversion in dedicated test rather than forcing all other tests defining it (!NULL check in mapper will do the trick for you)

Target:
protected VDS getEntity(int index) { VDS vds = setUpEntityExpectations(control.createMock(VDS.class), index); VdsStatic vdsStatic = control.createMock(VdsStatic.class); expect(vdsStatic.getId()).andReturn(GUIDS[2]).anyTimes(); expect(vds.getStaticData()).andReturn(vdsStatic).anyTimes(); return vds; }
Source:
protected void setUpGetHostIdExpectations(int idx) throws Exception { VDS host = BackendHostsResourceTest.setUpEntityExpectations(control.createMock(VDS.class), control.createMock(RpmVersion.class), START idx); END setUpGetEntityExpectations(VdcQueryType.GetVdsByName, GetVdsByNameParameters.class, new String[] { "Name" }, new Object[] { NAMES[idx] }, host); } same here (no need to define the version)

Target:
protected void setUpGetHostIdExpectations(int idx) throws Exception { VDS host = BackendHostsResourceTest.setUpEntityExpectations(control.createMock(VDS.class), idx); setUpGetEntityExpectations(VdcQueryType.GetVdsByName, GetVdsByNameParameters.class, new String[] { "Name" }, new Object[] { NAMES[idx] }, host); }
Source:
private List<storage_pool> buildStoragePoolsList() { List<storage_pool> pools = new LinkedList<storage_pool>(); pools.add(pool1); pools.add(pool2); pools.add(pool3); START return pools; END } return Arrays.asList (pool1, pool2, pool3);

Target:
private List<storage_pool> buildStoragePoolsList() { return Arrays.asList(pool1,pool2,pool3); }
Source:
START private OvfDataUpdater(){ END ovfManager = new OvfManager(); proccessedIdsInfo = new LinkedList<Guid>(); proccessedOvfGenerationsInfo = new LinkedList<Long>(); } missing space between () and {

Target:
private OvfDataUpdater() { ovfManager = new OvfManager(); }
Source:
START private void removeOvfForTemplatesAndVmsOfStoragePool(Guid poolId) { END List<Guid> idsForRemoval = new LinkedList<Guid>(getVmAndTemplatesGenerationsDao().getIdsForOvfDeletion(poolId)); for (Guid id : idsForRemoval){ executeRemoveVmInSpm(poolId, id, Guid.Empty); } getVmAndTemplatesGenerationsDao().deleteOvfGenerations(idsForRemoval); } Why create LinkedList?

Target:
private void removeOvfForTemplatesAndVmsOfStoragePool(Guid poolId) { List<Guid> idsForRemoval = getVmAndTemplatesGenerationsDao().getIdsForOvfDeletion(poolId); for (Guid id : idsForRemoval){ executeRemoveVmInSpm(poolId, id, Guid.Empty); } getVmAndTemplatesGenerationsDao().deleteOvfGenerations(idsForRemoval); }
Source:
START public long getDb_generation() { END return db_generation; } use java conventions.

Target:
public Long getDb_generation() { return db_generation; }
Source:
protected VmAndTemplatesGenerationsDAO getVmAndTemplatesGenerationsDao() { START return DbFacade.getInstance().getVmAndTemplatesGenerationsDAO(); END } /s/getVmAndTemplatesGenerationsDao/getVmAndTemplatesGenerationDAO

Target:
protected VmAndTemplatesGenerationsDAO getVmAndTemplatesGenerationsDao() { return DbFacade.getInstance().getVmAndTemplatesGenerationsDao(); }
Source:
private void assertGetResult(VM result) { assertNotNull(result); START assertTrue("Vm db generation wasn't loaded as expected", result.getDbGeneration() == 1); END assertEquals(result, existingVm); } Wait, this is worse than the previous version. What happened to the assertEquals()?

Target:
private void assertGetResult(VM result) { assertNotNull(result); assertEquals("Vm db generation wasn't loaded as expected", 1, result.getDbGeneration()); assertEquals(result, existingVm); }
Source:
private static void assertCorrectGetAllResult(List<VM> result) { assertNotNull(result); assertFalse(result.isEmpty()); assertEquals(VM_COUNT, result.size()); for (VM vm : result) { START assertTrue("Vm db generation wasn't loaded as expected", vm.getDbGeneration() == 1); END } } Wait, this is worse than the previous version. What happened to the assertEquals()?

Target:
private static void assertCorrectGetAllResult(List<VM> result) { assertNotNull(result); assertFalse(result.isEmpty()); assertEquals(VM_COUNT, result.size()); for (VM vm : result) { assertEquals("Vm db generation wasn't loaded as expected", 1, vm.getDbGeneration()); } }
Source:
private static void assertGetResult(VmTemplate result) { assertNotNull(result); assertEquals(EXISTING_TEMPLATE_ID, result.getId()); START assertTrue("Template generation wasn't loaded as expected", result.getDbGeneration() == 1); END } Wait, this is worse than the previous version. What happened to the assertEquals()? [it supports primitives, despite what the name may suggest]

Target:
private static void assertGetResult(VmTemplate result) { assertNotNull(result); assertEquals(EXISTING_TEMPLATE_ID, result.getId()); assertEquals("Template generation wasn't loaded as expected", 1, result.getDbGeneration()); }
Source:
private static void assertGetAllResult(List<VmTemplate> result) { assertNotNull(result); assertFalse(result.isEmpty()); for (VmTemplate template : result){ START assertTrue("Template generation wasn't loaded as expected", template.getDbGeneration() == 1); END } } Wait, this is worse than the previous version. What happened to the assertEquals()?

Target:
private static void assertGetAllResult(List<VmTemplate> result) { assertNotNull(result); assertFalse(result.isEmpty()); for (VmTemplate template : result){ assertEquals("Template generation wasn't loaded as expected", 1, template.getDbGeneration()); } }
Source:
protected void executeCommand() { VDSGroup vdsGroup = getVdsGroup(); if (vdsGroup.supportsVirtService()) { setSucceeded(initVirtResources()); } if (vdsGroup.supportsGlusterService()) { setSucceeded(initGlusterPeerProcess()); } START END runVdsCommand(VDSCommandType.GetBiosInfo, new VdsIdAndVdsVDSCommandParametersBase(getVds())); } should be triggered only if we success. Also if it will fail a host will be moved to NonOperational if these is not intention , add a try catch, if it is add appropriate failure reason of failure to AuditLog

Target:
protected void executeCommand() { VDSGroup vdsGroup = getVdsGroup(); if (vdsGroup.supportsVirtService()) { setSucceeded(initVirtResources()); } if (vdsGroup.supportsGlusterService()) { setSucceeded(initGlusterPeerProcess()); } }
Source:
public GetBiosInfoVDSCommand(P parameters) { START super(parameters, parameters.getVds()); END if (getVds() == null) { setVds(DbFacade.getInstance().getVdsDao().get(parameters.getVdsId())); parameters.setVds(getVds()); } } Remove these code is useless , you usually pass a vdsm

Target:
public GetBiosInfoVDSCommand(P parameters) { super(parameters, parameters.getVds()); }
Source:
private void handleVdsLiveSnapshotFailure(VdcBLLException e) { log.warnFormat("Wasn't able to live snpashot due to error: {0}. VM will still be configured to the new created snapshot", ExceptionUtils.getMessage(e)); AuditLogableBase logable = new AuditLogableBase(); logable.AddCustomValue("SnapshotName", getSnapshotName()); START logable.AddCustomValue("VmName", getVmName()); END AuditLogDirector.log(logable, AuditLogType.USER_CREATE_LIVE_SNAPSHOT_FINISHED_FAILURE); } why not set these attributes on the command itself?

Target:
private void handleVdsLiveSnapshotFailure(VdcBLLException e) { log.warnFormat("Wasn't able to live snpashot due to error: {0}. VM will still be configured to the new created snapshot", ExceptionUtils.getMessage(e)); AddCustomValue("SnapshotName", getSnapshotName()); AddCustomValue("VmName", getVmName()); AuditLogDirector.log(this, AuditLogType.USER_CREATE_LIVE_SNAPSHOT_FINISHED_FAILURE); }
Source:
START public void removeQuotaFromCache(Guid storagePoolId, Guid quotaId) { END lock.readLock().lock(); try { if (!storagePoolQuotaMap.containsKey(storagePoolId)) { return; } synchronized (storagePoolQuotaMap.get(storagePoolId)) { storagePoolQuotaMap.get(storagePoolId).remove(quotaId); } } finally { lock.readLock().unlock(); } } should call: removeQuotaFromCache(storagePoolId, Arrays.toList(quotaId)); .. btw why we have here read lock and in the other method write lock?

Target:
public void removeQuotaFromCache(Guid storagePoolId, Guid quotaId) { removeQuotaFromCache(storagePoolId, Arrays.asList(quotaId)); }
Source:
private boolean isImplementingRecursive(Class commandClass, Class interfaceClass) { if (Arrays.asList(commandClass.getInterfaces()).contains(interfaceClass)) { return true; } else { START return commandClass.getSuperclass() != CommandBase.class END && isImplementingRecursive(commandClass.getSuperclass(), interfaceClass); } } use equals instead of !=

Target:
private boolean isImplementingRecursive(Class commandClass, Class interfaceClass) { if (Arrays.asList(commandClass.getInterfaces()).contains(interfaceClass)) { return true; } else { return !commandClass.getSuperclass().equals(CommandBase.class) && isImplementingRecursive(commandClass.getSuperclass(), interfaceClass); } }
Source:
public VmNetworkInterface get(Guid id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("id", id); VmNetworkInterface entity = getCallsHandler().executeRead("Getvm_interfaceById", mapper, parameterSource); START entity.setVmInterfaceDynamic(DbFacade.getInstance().getVmInterfaceDynamic().get(id)); END return entity; } This should be done as part of mapper logic, and the fields added to the vm_interface_view, no need to double query.

Target:
public VmNetworkInterface get(Guid id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("id", id); VmNetworkInterface entity = getCallsHandler().executeRead("Getvm_interfaceById", mapper, parameterSource); return entity; }
Source:
public void remove(Guid id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("id", id); getCallsHandler().executeModification("Deletevm_interface", parameterSource); START DbFacade.getInstance().getVmInterfaceDynamic().remove(id); END } I disagree that this is the right place for it, it's hiding this logic in an unrelated place, I think this call needs to be done explicitly where the remove is called (as is the case for statistics)

Target:
public void remove(Guid id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("id", id); getCallsHandler().executeModification("Deletevm_interface", parameterSource); }
Source:
public List<PermissionSubject> getPermissionCheckSubjects() { START END if (networkExists()) { return Collections.singletonList(new PermissionSubject(getParameters().getVdsGroupId(), VdcObjectType.VdsGroups, ActionGroup.CONFIGURE_CLUSTER_NETWORK)); } else { Guid networkId = getParameters().getNetwork() == null ? null : getParameters().getNetwork().getId(); return Collections.singletonList(new PermissionSubject(networkId, VdcObjectType.Network, getActionType().getActionGroup())); } } I think that if the network exist you should be able to edit the (attach) parameters if you have permission on the network or if you have permission on the cluster

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { Guid networkId = getParameters().getNetwork() == null ? null : getParameters().getNetwork().getId(); return Collections.singletonList(new PermissionSubject(networkId, VdcObjectType.Network, getActionType().getActionGroup())); }
Source:
private VmNetworkInterface getIfaceWithNetworkName(List<VmNetworkInterface> interfaces) { START if (getNetworkName() == null) { END return null; } else { return LinqUtils.firstOrNull(interfaces, new Predicate<VmNetworkInterface>() { @Override public boolean eval(VmNetworkInterface vmNetworkInterface) { return getNetworkName().equals(vmNetworkInterface.getName()); } }); } } I agree with Moti. Changing the order is enough. (getNetworkName().equals(vmNetworkInterface.getName()) instead of vmNetworkInterface.getName().equals(getNetworkName()) ). There is no need to check that the cluster network is not null, cause it can't be null.

Target:
private VmNetworkInterface getIfaceWithNetworkName(List<VmNetworkInterface> interfaces) { return LinqUtils.firstOrNull(interfaces, new Predicate<VmNetworkInterface>() { @Override public boolean eval(VmNetworkInterface vmNetworkInterface) { return getNetworkName().equals(vmNetworkInterface.getName()); } }); }
Source:
protected void executeCommand() { final DiskImage newDiskImage = getParameters().getDiskImage(); if (newDiskImage != null) { START TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { END @Override public Void runInTransaction() { addDiskImageToDb(newDiskImage, getCompensationContext()); getReturnValue().setActionReturnValue(newDiskImage.getId()); getReturnValue().setSucceeded(true); return null; } }); } } Why a new transaction is needed here?

Target:
protected void executeCommand() { final DiskImage newDiskImage = getParameters().getDiskImage(); if (newDiskImage != null) { addDiskImageToDb(newDiskImage, getCompensationContext()); getReturnValue().setActionReturnValue(newDiskImage.getId()); getReturnValue().setSucceeded(true); } }
Source:
protected boolean canDoAction() { List<String> canDoActionMessages = getReturnValue().getCanDoActionMessages(); Map<Guid, storage_domains> domainsMap = new HashMap<Guid, storage_domains>(); START if (!canDoAction_beforeCloneVm(canDoActionMessages, domainsMap)) { END return false; } if (getParameters().isImportAsNewEntity()) { initImportClonedVm(); } if (!canDoAction_afterCloneVm(canDoActionMessages, domainsMap)) { return false; } return true; } Suggestion: I would even consider to remove the canDoActionMessages from here, and instead call it in canDoAction_beforeCloneVm and canDoAction_afterCloneVm. (It can make the CDA be more shorter and I believe it is more performance wise)

Target:
protected boolean canDoAction() { Map<Guid, storage_domains> domainsMap = new HashMap<Guid, storage_domains>(); if (!canDoAction_beforeCloneVm(domainsMap)) { return false; } if (getParameters().isImportAsNewEntity()) { initImportClonedVm(); } return canDoAction_afterCloneVm(domainsMap); }
Source:
public static PmProxyType fromValue(String v) { try { if (v==null) { return null; } if (v.equals("cluster")) { return CLUSTER; } else if (v.equals("dc")) { return DC; } else { START return valueOf(v.toUpperCase()); END } } catch (IllegalArgumentException e) { return null; } } if 'v' is not a member of enum why return it in upper case?

Target:
public static PmProxyType fromValue(String v) { try { if (v==null) { return null; } if (v.equals("cluster")) { return CLUSTER; } else if (v.equals("dc")) { return DC; } else { return null; } } catch (IllegalArgumentException e) { return null; } }
Source:
public void validateEnums(Host host) { if (host.isSetPowerManagement()) { if (host.getPowerManagement().isSetPmProxies()) { for (PmProxy proxy : host.getPowerManagement().getPmProxies().getPmProxy()) { START validateEnum(PmProxyType.class, proxy.getPropietary(), true); END } } } } iiuc "propietary" is a string and enum that you have added is PmProxyType, so you should be adding it to <pm_proxy> and validating it here.

Target:
public void validateEnums(Host host) { if (host.isSetPowerManagement()) { if (host.getPowerManagement().isSetPmProxies()) { for (PmProxy proxy : host.getPowerManagement().getPmProxies().getPmProxy()) { validateEnum(PmProxyType.class, proxy.getType(), true); } } } }
Source:
public void getFCStorageTypeForLun() throws Exception { LUNs lun = new LUNs(); ArrayList<storage_server_connections> connections = new ArrayList<storage_server_connections>(); lun.setLunConnections(connections); START StorageType storageType = command.getLUNStorageType(lun); END assertEquals("Lun disk should be of FC storage type since it does not had connections", storageType, storageType.FCP); } please switch between the assert values, expected value should be second.. /s/disk/storage type /s/had/have

Target:
public void getFCStorageTypeForLun() throws Exception { LUNs lun = new LUNs(); ArrayList<storage_server_connections> connections = new ArrayList<storage_server_connections>(); lun.setLunConnections(connections); StorageType storageType = command.getLUNStorageType(lun); assertEquals("Lun disk should be of FC storage type since it does not had connections", StorageType.FCP, storageType); }
Source:
START protected <T> Response performCreate(VdcActionType task, END VdcActionParametersBase taskParams, IResolver<T, Q> entityResolver, boolean block) { return performCreate(task, taskParams, entityResolver, block, null); } should be final as well?

Target:
protected final <T> Response performCreate(VdcActionType task, VdcActionParametersBase taskParams, IResolver<T, Q> entityResolver, boolean block) { return performCreate(task, taskParams, entityResolver, block, null); }
Source:
protected StorageDomain deprecatedPopulate(StorageDomain model, storage_domains entity) { if (StorageDomainSharedStatus.Unattached.equals(entity.getstorage_domain_shared_status())) { model.setStatus(StatusUtils.create(StorageDomainStatus.UNATTACHED)); } else { model.setStatus(null); } START return model; END } no need to return super.deprecatedPopulate() ?

Target:
protected StorageDomain deprecatedPopulate(StorageDomain model, storage_domains entity) { if (StorageDomainSharedStatus.Unattached.equals(entity.getstorage_domain_shared_status())) { model.setStatus(StatusUtils.create(StorageDomainStatus.UNATTACHED)); } else { model.setStatus(null); } return super.deprecatedPopulate(model, entity); }
Source:
protected File determineActualFile(final HttpServletRequest request, Locale locale) { File file = ServletUtils.makeFileFromSanePath(request.getPathInfo(), base); // Check if file is found. If not found go ahead and try and look up the English US locale version. START if (null != file && !ServletUtils.canReadFile(file)) { END file = ServletUtils.makeFileFromSanePath(replaceLocaleWithUSLocale(request.getPathInfo(), locale), base); } return file; } Please use "something <operator> null" convention

Target:
protected File determineActualFile(final HttpServletRequest request, Locale locale) { File file = ServletUtils.makeFileFromSanePath(request.getPathInfo(), base); // Check if file is found. If not found go ahead and try and look up the English US locale version. if (file != null && !ServletUtils.canReadFile(file)) { file = ServletUtils.makeFileFromSanePath(replaceLocaleWithUSLocale(request.getPathInfo(), locale), base); } return file; }
Source:
protected Locale getLocaleFromRequest(final HttpServletRequest request) { String localeString = getLocaleStringFromReferer(request); //Unable to determine locale string from referer (preferred way) START if (null == localeString) { END //Note this fails if the is something like /menu.css localeString = getLocaleStringFromPath(request.getPathInfo()); } //Validate that the locale string is valid. Locale locale = LocaleUtils.getLocaleFromString(localeString, true); return locale; } Please use "something <operator> null" convention

Target:
protected Locale getLocaleFromRequest(final HttpServletRequest request) { String localeString = getLocaleStringFromReferer(request); //Unable to determine locale string from referer (preferred way) if (localeString == null) { //Note this fails if the is something like /menu.css localeString = getLocaleStringFromPath(request.getPathInfo()); } //Validate that the locale string is valid. Locale locale = LocaleUtils.getLocaleFromString(localeString, true); return locale; }
Source:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Locate the requested file: File file = ServletUtils.makeFileFromSanePath(request.getPathInfo(), base); file = checkForIndex(request, response, file, request.getPathInfo()); START if (null == file) { END response.sendError(HttpServletResponse.SC_NOT_FOUND); } else { // Send the content of the file: // type is the default MIME type of the Servlet. ServletUtils.sendFile(request, response, file, type); } } Please use "something <operator> null" convention

Target:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Locate the requested file: File file = ServletUtils.makeFileFromSanePath(request.getPathInfo(), base); file = checkForIndex(request, response, file, request.getPathInfo()); if (file == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } else { // Send the content of the file: // type is the default MIME type of the Servlet. ServletUtils.sendFile(request, response, file, type); } }
Source:
private List<String> getListOfIpAddresses(String ipAddressesAsString) { if (ipAddressesAsString == null) { START return Collections.emptyList(); END } return Arrays.asList(StringUtils.split(ipAddressesAsString,DELIMITER)); } Why not return null?

Target:
private List<String> getListOfIpAddresses(String ipAddressesAsString) { return ipAddressesAsString == null ? null : Arrays.asList(StringUtils.split(ipAddressesAsString, DELIMITER)); }
Source:
public void setUp() throws Exception { super.setUp(); START when(getQuery().getDbFacade()).thenReturn(dbFacade); END when(dbFacade.getVmGuestAgentInterfaceDao()).thenReturn(vmGuestAgentInterfaceDao); } You can use getDbFacadeMockInstance() instead of mocking it yourself

Target:
public void setUp() throws Exception { super.setUp(); }
Source:
public boolean runForSingleConnectionInHost(storage_domains storageDomain, Guid storagePoolId, int type) { storage_pool pool = DbFacade.getInstance().getStoragePoolDao().get(storagePoolId); if (pool.getspm_vds_id() != null) { return runConnectionStorageToDomain(storageDomain, pool.getspm_vds_id().getValue(), type); START } else { END log.errorFormat("Pool {0} does not have spm vds id to connect storage to domain.", pool.getname()); return false; } } The return terminates the if - you should remove the else

Target:
public boolean runForSingleConnectionInHost(storage_domains storageDomain, Guid storagePoolId, int type) { storage_pool pool = DbFacade.getInstance().getStoragePoolDao().get(storagePoolId); if (pool.getspm_vds_id() == null) { log.errorFormat("Pool {0} does not have spm vds id to connect storage to domain.", pool.getname()); return false; } return runConnectionStorageToDomain(storageDomain, pool.getspm_vds_id().getValue(), type); }
Source:
public VM getVm() { VM vm = super.getVm(); if (vm != null) { return vm; } START vm = getVmDAO().get(getParameters().getVmId()); END if (vm != null) { setVm(vm); setVmId(vm.getId()); } return vm; } super.getVm() will do dao call...

Target:
public VM getVm() { VM vm = super.getVm(); if (vm != null) { setVm(vm); } return vm; }
Source:
private boolean isVmRunning(VM vm) { START return vm != null && vm.getStatus() == VMStatus.Up && END vm.getRunOnVds() != null && !vm.getRunOnVds().equals(Guid.Empty); } you can't get here with vm == null, so it should be removed from here.

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

Target:
private boolean isVmDown(VM vm) { return vm.getStatus() == VMStatus.Down; }
Source:
private List<LiveMigrateDisksParameters> getLiveMigrateDisksParametersList() { List<LiveMigrateDisksParameters> liveMigrateDisksParametersList = new ArrayList<LiveMigrateDisksParameters>(); for (Guid vmId : vmsLiveMigrateParametersMap.keySet()) { START List<LiveMigrateDiskParameters> parametersList = vmsLiveMigrateParametersMap.get(vmId); END LiveMigrateDisksParameters liveMigrateDisksParameters = new LiveMigrateDisksParameters(parametersList, vmId); liveMigrateDisksParameters.setParentCommand(VdcActionType.MoveDisks); liveMigrateDisksParameters.setSessionId(getParameters().getSessionId()); liveMigrateDisksParametersList.add(liveMigrateDisksParameters); } return liveMigrateDisksParametersList; } You're iterating over the keyset, and calling get from the map in the first line. Just iterate over the entrySet instead

Target:
private List<LiveMigrateDisksParameters> getLiveMigrateDisksParametersList() { List<LiveMigrateDisksParameters> liveMigrateDisksParametersList = new ArrayList<LiveMigrateDisksParameters>(); for (Map.Entry<Guid, List<LiveMigrateDiskParameters>> entry : vmsLiveMigrateParametersMap.entrySet()) { LiveMigrateDisksParameters liveMigrateDisksParameters = new LiveMigrateDisksParameters(entry.getValue(), entry.getKey()); liveMigrateDisksParameters.setParentCommand(VdcActionType.MoveDisks); liveMigrateDisksParameters.setSessionId(getParameters().getSessionId()); liveMigrateDisksParametersList.add(liveMigrateDisksParameters); } return liveMigrateDisksParametersList; }
Source:
START public synchronized void removeQuotaFromCache(Guid storagePoolId, List<Guid> quotaList) { END lock.writeLock().lock(); try { if (!storagePoolQuotaMap.containsKey(storagePoolId)) { return; } synchronized (storagePoolQuotaMap.get(storagePoolId)) { Map<Guid, Quota> map = storagePoolQuotaMap.get(storagePoolId); for (Guid quotaId : quotaList) { map.remove(quotaId); } } } finally { lock.writeLock().unlock(); } } Please check if really needed.

Target:
public void removeQuotaFromCache(Guid storagePoolId, List<Guid> quotaList) { lock.writeLock().lock(); try { if (!storagePoolQuotaMap.containsKey(storagePoolId)) { return; } synchronized (storagePoolQuotaMap.get(storagePoolId)) { Map<Guid, Quota> map = storagePoolQuotaMap.get(storagePoolId); for (Guid quotaId : quotaList) { map.remove(quotaId); } } } finally { lock.writeLock().unlock(); } }
Source:
private boolean canDoSnapshot(VM vm) { //if version is 3.0 - live snapshot is not available, thus if vm is up snapshot is not possible so it needs to be //checked if it's up or not //if version is 3.1, there is no need to check if vm is up since in any case snapshot is possible START boolean canSnapshot = true; END if(!isLiveSnapshotEnabled() && !ImagesHandler.isVmDown(vm)) { //if there is no live snapshot and the vm is up - snapshot is not possible addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_DATA_CENTER_VERSION_DOESNT_SUPPORT_LIVE_SNAPSHOT); canSnapshot = false; } return canSnapshot; } I agree with Vered

Target:
private boolean canDoSnapshot(VM vm) { // if live snapshot is not available, then if vm is up - snapshot is not possible so it needs to be // checked if vm up or not // if live snapshot is enabled, there is no need to check if vm is up since in any case snapshot is possible if (!isLiveSnapshotEnabled() && !ImagesHandler.isVmDown(vm)) { // if there is no live snapshot and the vm is up - snapshot is not possible addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_DATA_CENTER_VERSION_DOESNT_SUPPORT_LIVE_SNAPSHOT); return false; } return true; }
Source:
START private Guid getDisksStorageDomainId() { END Disk disk = getVm().getDiskMap().values().iterator().next(); if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { return ((DiskImage) disk).getstorage_ids().get(0); } else { return Guid.Empty; } } This is obviously only relevant to Images. So why are we even getting here if we're hadnling a LUN disk?

Target:
private Guid getDisksStorageDomainId() { for (Disk disk : getVm().getDiskMap().values()) { if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { return ((DiskImage) disk).getstorage_ids().get(0); } } return Guid.Empty; }
Source:
private void executeAndSetReturnValue(String volumeName) { VDSReturnValue returnValue = executeCommand(volumeName); getQueryReturnValue().setReturnValue(returnValue.getReturnValue()); START return; END } this "return;" statement is of no use.

Target:
private void executeAndSetReturnValue(String volumeName) { VDSReturnValue returnValue = executeCommand(volumeName); getQueryReturnValue().setReturnValue(returnValue.getReturnValue()); }
Source:
protected boolean canDoAction() { if (getVm() == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_FOUND); } if (getVm().isDeleteProtected()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DELETE_PROTECTION_ENABLED); } if (!(super.canDoAction() && canRemoveVm())) { return false; } START return true; END } You can remove all the following code: if (!(.... return false; } return true; With simply : return super.canDoAction() && canRemoveVm()

Target:
protected boolean canDoAction() { if (getVm() == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_FOUND); } if (getVm().isDeleteProtected()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DELETE_PROTECTION_ENABLED); } return (super.canDoAction() && canRemoveVm()); }
Source:
private void removeGlusterVolumesFromDb() { START List<GlusterVolumeEntity> volumes = getGlusterVolumeDao().getByClusterId(getVdsGroupId()); END if (volumes.size() > 0) { getGlusterVolumeDao().removeByClusterId(getVdsGroupId()); } } The check for volumes count doesn't add any value. You'll execute one query all the time, and two when there are volumes. Directly invoking the removeByClusterId() will mean only one query in all cases. When there are no volumes, it won't delete anything, but still succeed. So it should work.

Target:
private void removeGlusterVolumesFromDb() { getGlusterVolumeDao().removeByClusterId(getVdsGroupId()); }
Source:
public static <V> ExecutorCompletionService<V> createCompletionService() { START ExecutorCompletionService<V> ecs = new ExecutorCompletionService<V>(es); END return ecs; } you forgot to inline into one liner method as moti suggested on patch #1 .. :-) other than that - looks good to me.

Target:
public static <V> ExecutorCompletionService<V> createCompletionService() { return new ExecutorCompletionService<V>(es); }
Source:
private Network getNetworkByName(List<Network> networks) { START return LinqUtils.firstOrNull(networks, new Predicate<Network>() { END @Override public boolean eval(Network network) { return network.getname().equals(getNetworkName()); } }); } LinqUtils could be replaced with for loop and return statement which will simplify the reading and reduce the need of creating new anonymous class.

Target:
private Network getNetworkByName(List<Network> networks) { return LinqUtils.firstOrNull(networks, new Predicate<Network>() { @Override public boolean eval(Network network) { return network.getName().equals(getNetworkName()); } }); }
Source:
private void applyModeCustomizations() { if (ApplicationModeHelper.getUiMode() == ApplicationMode.GlusterOnly) { optimizationTab.setVisible(false); resiliencePolicyTab.setVisible(false); START clusterPolicyTab.setVisible(true); END dataCenterPanel.addStyleName(style.generalTabTopDecoratorEmpty()); } } please make the policy tab hidden in Gluster mode.

Target:
private void applyModeCustomizations() { if (ApplicationModeHelper.getUiMode() == ApplicationMode.GlusterOnly) { optimizationTab.setVisible(false); resiliencePolicyTab.setVisible(false); clusterPolicyTab.setVisible(false); dataCenterPanel.addStyleName(style.generalTabTopDecoratorEmpty()); } }
Source:
public boolean hasConflicts() { START return this.conflictStatus > 0; END } I guess we need a null check as well.

Target:
public boolean hasConflicts() { return conflictStatus != null && conflictStatus > 0; }
Source:
public void testRemoveAll() { List<Guid> hookIds = new ArrayList<Guid>(); hookIds.add(HOOK_ID); hookIds.add(HOOK_ID2); dao.removeAll(hookIds); List<GlusterHookEntity> hooks = dao.getByClusterId(CLUSTER_ID); START assertNotNull(hooks); END } Also check if result is empty?

Target:
public void testRemoveAll() { List<Guid> hookIds = new ArrayList<Guid>(); hookIds.add(HOOK_ID); hookIds.add(HOOK_ID2); dao.removeAll(hookIds); List<GlusterHookEntity> hooks = dao.getByClusterId(CLUSTER_ID); assertNotNull(hooks); assertTrue(hooks.isEmpty()); }
Source:
public void testUpdateGlusterHookStatus() { START dao.updateGlusterHookStatus(FixturesTool.HOOK_ID, null, GlusterHookStatus.ENABLED); END GlusterHookEntity hook = dao.getById(FixturesTool.HOOK_ID); assertNotNull(hook); assertEquals(GlusterHookStatus.ENABLED, hook.getStatus()); } i think you need to pass the SERVER_ID which you want to update the status.

Target:
public void testUpdateGlusterHookStatus() { dao.updateGlusterHookStatus(FixturesTool.HOOK_ID, GlusterHookStatus.ENABLED); GlusterHookEntity hook = dao.getById(FixturesTool.HOOK_ID); assertNotNull(hook); assertEquals(GlusterHookStatus.ENABLED, hook.getStatus()); }
Source:
public ValidationResult clusterNetworkNotUsedByTemplates() { List<VmTemplate> templatesUsingNetwork = new ArrayList<VmTemplate>(); for (VmTemplate template : getVmTemplateDAO().getAllForVdsGroup(networkCluster.getClusterId())) { START for (VmNetworkInterface nic : getVmNetworkInterfaceDao().getAllForTemplate(networkCluster.getClusterId())) { END if (nic.getNetworkName() == network.getName()) { templatesUsingNetwork.add(template); } } } return networkNotUsed(templatesUsingNetwork, VdcBllMessages.VAR__ENTITIES__VM_TEMPLATES); } I think you meant: getVmNetworkInterfaceDao().getAllForTemplate(*template.getId()*)

Target:
public ValidationResult clusterNetworkNotUsedByTemplates() { List<VmTemplate> templatesUsingNetwork = new ArrayList<VmTemplate>(); for (VmTemplate template : getVmTemplateDAO().getAllForVdsGroup(networkCluster.getClusterId())) { for (VmNetworkInterface nic : getVmNetworkInterfaceDao().getAllForTemplate(template.getId())) { if (nic.getNetworkName().equals(network.getName())) { templatesUsingNetwork.add(template); } } } return networkNotUsed(templatesUsingNetwork, VdcBllMessages.VAR__ENTITIES__VM_TEMPLATES); }
Source:
private void internalFreeMac(String mac) { if (allocatedMacs.containsKey(mac)) { removeMacFromMap(allocatedMacs, mac); START availableMacs.add(mac); END } else if (allocatedCustomMacs.containsKey(mac)) { removeMacFromMap(allocatedCustomMacs, mac); } } I'm troubled about this line: Since the AllowDuplicateMacAddress configuration variable is reloadable, this code won't serve well in case we moved from permissive to restrictive mode: returning a MAC address to the available mac address pool should be done only if it no longer in use by the allocatedMacs

Target:
private void internalFreeMac(String mac) { if (allocatedMacs.containsKey(mac)) { removeMacFromMap(allocatedMacs, mac); if (!allocatedMacs.containsKey(mac)) { availableMacs.add(mac); } } else if (allocatedCustomMacs.containsKey(mac)) { removeMacFromMap(allocatedCustomMacs, mac); } }
Source:
private boolean addMacToMap(Map<String, Integer> macMap, String mac) { START boolean returnValue = false; END if (!macMap.containsKey(mac)) { macMap.put(mac, 1); // First time this mac is used returnValue = true; } else if (allowDuplicate()) { incrementMacInMap(macMap, mac); returnValue = true; } return returnValue; } I wouldn't use a variable for this but just return on the spot, this method is not that complicated that you would need a variable to track it's return value.

Target:
private boolean addMacToMap(Map<String, Integer> macMap, String mac) { if (!macMap.containsKey(mac)) { macMap.put(mac, 1); return true; } else if (allowDuplicate()) { incrementMacInMap(macMap, mac); return true; } return false; }
Source:
public static void InitDictionaries() { log.info("Start initializing dictionaries"); _managersDictionary.clear(); for (Version ver : Config.<HashSet<Version>> GetValue(ConfigValues.SupportedClusterLevels)) { _managersDictionary.put(ver, new CpuFlagsManager(ver)); } START log.info("Finished initializing dictionaries" + CpuFlagsManagerHandler.class.getSimpleName()); END } why "+ CpuFlagsManagerHandler.class.getSimpleName() "? if you do leave it..space is missing between "dictionaries" and it.

Target:
public static void InitDictionaries() { log.info("Start initializing dictionaries"); _managersDictionary.clear(); for (Version ver : Config.<HashSet<Version>> GetValue(ConfigValues.SupportedClusterLevels)) { _managersDictionary.put(ver, new CpuFlagsManager(ver)); } log.info("Finished initializing dictionaries"); }
Source:
protected void endVmCommand() { super.endVmCommand(); // if we got here, the target snapshot exists for sure START getSnapshotDao().updateStatus(getParameters().getDstSnapshotId(), SnapshotStatus.OK); END } seems to be like this should be before the vm is unlocked in super.endVmCommand();

Target:
protected void endVmCommand() { // if we got here, the target snapshot exists for sure getSnapshotDao().updateStatus(getParameters().getDstSnapshotId(), SnapshotStatus.OK); super.endVmCommand(); }
Source:
protected Map<String, String> getExclusiveLocks() { if (getVdsGroup().supportsGlusterService() && !isInternalExecution()) { return Collections.singletonMap(getVdsGroupId().toString(), LockingGroup.GLUSTER.name()); START } END return super.getExclusiveLocks(); } You don't need call to super method

Target:
protected Map<String, String> getExclusiveLocks() { if (getVdsGroup().supportsGlusterService() && !isInternalExecution()) { return Collections.singletonMap(getVdsGroupId().toString(), LockingGroup.GLUSTER.name()); } return null; }
Source:
START public Map<String, String> getJobMessageProperties() { END if (volume != null) { if (jobProperties == null) { jobProperties = super.getJobMessageProperties(); } jobProperties.put(GlusterConstants.VOLUME, volume.getName()); } return jobProperties; } there is a potential NPE here since jobProperties might not be initialized. I'd suggest changing it to: @Override public Map<String, String> getJobMessageProperties() { if (jobProperties == null) { jobProperties = super.getJobMessageProperties(); if (volume != null) { jobProperties.put(GlusterConstants.VOLUME, volume.getName()); } } return jobProperties; }

Target:
public Map<String, String> getJobMessageProperties() { if(volume == null) { return super.getJobMessageProperties(); } if (jobProperties == null) { jobProperties = super.getJobMessageProperties(); } jobProperties.put(GlusterConstants.VOLUME, volume.getName()); return jobProperties; }
Source:
protected List<Network> getNetworks() { if (networks == null) { networks = getDbFacade().getNetworkDao().getAllForDataCenter(network.getDataCenterId()); START if (networks == null) { END networks = Collections.<Network> emptyList(); } } return networks; } This code is not necessary, it's the DAO responsibility to return empty list if there are no networks. That is the de-facto contract in the system.

Target:
protected List<Network> getNetworks() { if (networks == null) { networks = getDbFacade().getNetworkDao().getAllForDataCenter(network.getDataCenterId()); } return networks; }
Source:
public void networkExists() throws Exception { START assertEquals(ValidationResult.VALID.getMessage(), validator.networkExists().getMessage()); END } Since using assertEquals to compare objects, you can compare the ValidationResult objects: assertEquals(ValidationResult.VALID, validator.networkExists()); here and elsewhere in the file.

Target:
public void networkExists() throws Exception { assertEquals(ValidationResult.VALID, validator.networkExists()); }
Source:
public void dataCenterDoesntExist() throws Exception { START doReturn(null).when(validator).getDataCenter(); // replace default mock data center with null data center END assertEquals(new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_EXIST).getMessage(), validator.dataCenterExists().getMessage()); } Please replace the doReturn() with when() around the entire file, i.e. when(validator.getDataCenter()).thenReturn(null);

Target:
public void dataCenterDoesntExist() throws Exception { doReturn(null).when(validator).getDataCenter(); // replace default mock data center with null data center assertEquals(new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_EXIST), validator.dataCenterExists()); }
Source:
public SubTabProviderGeneralView(DetailModelProvider<ProviderListModel, ProviderGeneralModel> modelProvider) { super(modelProvider); // Init formPanel formPanel = new GeneralFormPanel(); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); START Driver.driver.initialize(this); END // Build a form using the FormBuilder formBuilder = new FormBuilder(formPanel, 1, 1); formBuilder.addFormItem(new FormItem(constants.nameProvider(), name, 0, 0)); } Done

Target:
public SubTabProviderGeneralView(DetailModelProvider<ProviderListModel, ProviderGeneralModel> modelProvider) { super(modelProvider); // Init formPanel formPanel = new GeneralFormPanel(); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); driver.initialize(this); // Build a form using the FormBuilder formBuilder = new FormBuilder(formPanel, 1, 1); formBuilder.addFormItem(new FormItem(constants.nameProvider(), name, 0, 0)); }
Source:
public void setMainTabSelectedItem(Provider selectedItem) { START Driver.driver.edit(getDetailModel()); END formBuilder.update(getDetailModel()); } Done

Target:
public void setMainTabSelectedItem(Provider selectedItem) { driver.edit(getDetailModel()); formBuilder.update(getDetailModel()); }
Source:
public static synchronized void addToCache(AttestationValue value){ START if (!attestationValues.containsKey(value.getHostName())) END attestationValues.putIfAbsent(value.getHostName(), value); } This "if" is not needed, the "putIfAbsent" method already performs the check, and it doees it in a atomic way, so the "synchronized" modifier is not required.

Target:
public void addToCache(AttestationValue value) { attestationValues.putIfAbsent(value.getHostName(), value); }
Source:
START public static synchronized void removeFromCache(String key){ END if (key != null){ attestationValues.remove(key); } } The remove method of the ConcurrentHashMap already performs its own synchronization, so the "synchronized" modifier is not required.

Target:
public void removeFromCache(String key) { if (key != null) { attestationValues.remove(key); } }
Source:
public static AttestationValue getValueFromCache(String key){ AttestationValue value = attestationValues.get(key); START return value; END } return statement can be one line: return attestationValues.get(key);

Target:
public AttestationValue getValueFromCache(String key) { return attestationValues.get(key); }
Source:
public static synchronized void removeFromCache(String key){ if (attestationValues.containsKey(key)){ attestationValues.remove(key); START } END } Won't "attestationValues.remove(...)" be enough?

Target:
public static synchronized void removeFromCache(String key){ if (key != null){ attestationValues.remove(key); } }
Source:
protected boolean canDoAction() { boolean returnValue = super.canDoAction(); // the condition allows to get only user and password which are both set (even with empty string) or both aren't // set (null), the action will fail if only one of those parameters is null. if (returnValue && (getParameters().getSysPrepUserName() == null ^ getParameters().getSysPrepPassword() == null)) { addCanDoActionMessage(VdcBllMessages.VM_CANNOT_RUN_ONCE_WITH_ILLEGAL_SYSPREP_PARAM); returnValue = false; } // only administrator can specify destination host START if(getParameters().getDestinationVdsId() != null && !getCurrentUser().isAdmin()) { END addCanDoActionMessage(VdcBllMessages.VM_CANNOT_RUN_ONCE_NOT_ADMIN_FOR_DESTINATION_VDS_PARAM); returnValue = false; } return returnValue; } the action shouldn't fail if: the above & getParam().getDestHost == getVm().getDestHost()

Target:
protected boolean canDoAction() { boolean returnValue = super.canDoAction(); // the condition allows to get only user and password which are both set (even with empty string) or both aren't // set (null), the action will fail if only one of those parameters is null. if (returnValue && (getParameters().getSysPrepUserName() == null ^ getParameters().getSysPrepPassword() == null)) { addCanDoActionMessage(VdcBllMessages.VM_CANNOT_RUN_ONCE_WITH_ILLEGAL_SYSPREP_PARAM); returnValue = false; } return returnValue; }
Source:
public final static String encrypt(String source, String certificateFile, String passwd, String alias) throws Exception { try { String result = ""; START if (!StringHelper.isNullOrEmpty(source.trim())) { END KeyStore store = EncryptionUtils.getKeyStore(certificateFile, passwd, certType); result = encrypt(source, store.getCertificate(alias)); } return result; } catch (Exception e) { log.error("Error doing the encryption", e); throw e; } } StringUtils.isNotEmpty(source)

Target:
public final static String encrypt(String source, String certificateFile, String passwd, String alias) throws Exception { try { String result = ""; if (source.trim().length() > 0) { KeyStore store = EncryptionUtils.getKeyStore(certificateFile, passwd, certType); result = encrypt(source, store.getCertificate(alias)); } return result; } catch (Exception e) { log.error("Error doing the encryption", e); throw e; } }
Source:
public String getMessage() { START return ("done".equalsIgnoreCase(_message.toLowerCase())) ? "" : _message; END } Not related to your change, but isn't there anywhere some enum instead of using hardcoded "done"?

Target:
public String getMessage() { return ("done".equalsIgnoreCase(_message)) ? "" : _message; }
Source:
protected void executeCommand() { final DiskImage newDiskImage = getParameters().getDiskImage(); START if (newDiskImage != null) { END addDiskImageToDb(newDiskImage, getCompensationContext()); getReturnValue().setActionReturnValue(newDiskImage.getId()); getReturnValue().setSucceeded(true); } } The null check should be in the canDoAction(), not the executeCommand()

Target:
protected void executeCommand() { final DiskImage newDiskImage = getParameters().getDiskImage(); addDiskImageToDb(newDiskImage, getCompensationContext()); getReturnValue().setActionReturnValue(newDiskImage.getId()); getReturnValue().setSucceeded(true); }
Source:
public static boolean isManagementNetwork(Network net) { START return Config.<String> GetValue(ConfigValues.ManagementNetwork).equalsIgnoreCase(net.getName()); END } please use case-sensitive comparison

Target:
public static boolean isManagementNetwork(Network net) { return Config.<String> GetValue(ConfigValues.ManagementNetwork).equals(net.getName()); }
Source:
START protected storage_domains createStorageDomain(int availableSpace, Guid storageDomainId) { END storage_domains sd = new storage_domains(); sd.setstorage_domain_type(StorageDomainType.Master); sd.setstatus(StorageDomainStatus.Active); sd.setavailable_disk_size(availableSpace); sd.setused_disk_size(USED_SPACE_GB); sd.setId(storageDomainId); return sd; } should be private static.

Target:
private static storage_domains createStorageDomain(int availableSpace, Guid storageDomainId) { storage_domains sd = new storage_domains(); sd.setstorage_domain_type(StorageDomainType.Master); sd.setstatus(StorageDomainStatus.Active); sd.setavailable_disk_size(availableSpace); sd.setused_disk_size(USED_SPACE_GB); sd.setId(storageDomainId); return sd; }
Source:
public Hosts list() { // Filtered users are not allowed to view hosts if (isFiltered()) { START throw new WebApplicationException(Response.Status.FORBIDDEN); END } ApplicationMode appMode = getCurrent().get(ApplicationMode.class); if (appMode == ApplicationMode.GlusterOnly) { return listGlusterOnly(); } else { return listAll(); } } 1. this error is not needed as you removed (VdcQueryAuthType.User) from GetAllHosts query 2. please also remove this exception from BackendHostResource.get() after you make GetVdsByVdsId admin-only as well thanks.

Target:
public Hosts list() { ApplicationMode appMode = getCurrent().get(ApplicationMode.class); if (appMode == ApplicationMode.GlusterOnly) { return listGlusterOnly(); } else { return listAll(); } }
Source:
private static int compDigitSequence(String seq1, String seq2) { int compRes = ((Integer) Integer.parseInt(seq1)).compareTo(Integer.parseInt(seq2)); START return compRes != 0 ? compRes : compNonDigitSequence(seq1, seq2); END } Perhaps it would be easier to read a positive check than a negative one?

Target:
private static int compDigitSequence(String seq1, String seq2) { int compRes = ((Integer) Integer.parseInt(seq1)).compareTo(Integer.parseInt(seq2)); return compRes == 0 ? compNonDigitSequence(seq1, seq2) : compRes; }