auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public DataCenter get() { StoragePoolQueryParametersBase params = new StoragePoolQueryParametersBase(guid); params.setFiltered(SessionUtils.isFiltered()); return performGet(VdcQueryType.GetStoragePoolById, params); }

Target:
why this is not in performGet()? it would solve this in generic way...
Source:
public void setOnlyReloadable(String parseOptionKey) { if (Boolean.parseBoolean(parseOptionKey)) { onlyReloadable = true; } else { onlyReloadable = false; } }

Target:
just a matter of taste, maybe you tought about it already: onlyReloadable = Boolean.parseBoolean(parseOptionKey));
Source:
public void removeBrick(Guid brickId) { getCallsHandler().executeModification("DeleteGlusterVolumeBrick", getCustomMapSqlParameterSource().addValue("id", brickId.getUuid())); }

Target:
why its needed to cal getUuid() on guids? i don't remember we need/use it
Source:
private boolean correctStorageDomainFormat() { final Set<StorageFormatType> supportedStorageFormats = getSupportedStorageFormatSet(getVds().getvds_group_compatibility_version()); final StorageFormatType storageFormat = getStorageDomain().getStorageFormat(); final StorageType storageType = getStorageDomain().getstorage_type(); if (!supportedStorageFormats.contains(storageFormat)) { return false; } if ((storageFormat == StorageFormatType.V2) && (storageType != StorageType.ISCSI) && (storageType != StorageType.FCP)) { return false; } return true; }

Target:
storageType can be initialized inside the if command since it is only used for storage type V2
Source:
protected boolean isVersionSupportedForShareable() { return Config.<Boolean> GetValue(ConfigValues.ShareableDiskEnabled, getStoragePool().getcompatibility_version().getValue()); }

Target:
no way for storage pool to be null? (LUN disk, floating..)
Source:
public AbstractDiskVmCommand(T parameters) { super(parameters); if (parameters.getDiskInfo() != null && DiskStorageType.IMAGE == parameters.getDiskInfo().getDiskStorageType()) { setQuotaId(((DiskImage) parameters.getDiskInfo()).getQuotaId()); } if (getVm() != null) { setStoragePoolId(getVm().getstorage_pool_id()); } }

Target:
I don't like an idea to put that query at constarctor, first of all all AddDiskCommand will do an unneeded query, second we don't need a poolId for DetachDiskFromVmCommand and for UpdateVmDiskCommand, HotPlug and UnPlug, so putting at constractor is wrong
Source:
protected boolean isDiskExist(Disk disk) { if (disk == null || isDiskExistInVm(disk)) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_DISK_NOT_EXIST); return false; } return true; }

Target:
there was a NOT ('!') before the check.. i think still relevant, no?
Source:
private void RemoveVdsFromCollection() { // ResourceManager.Instance.removeVds(VdsId); VDSReturnValue returnValue = Backend.getInstance().getResourceManager() .RunVdsCommand(VDSCommandType.RemoveVds, new RemoveVdsVDSCommandParameters(getVdsId())); }

Target:
on your next rebase, returnValue is not needed any more, no point to keep it
Source:
private void RemoveVdsFromCollection() { // ResourceManager.Instance.removeVds(VdsId); VDSReturnValue returnValue = Backend.getInstance().getResourceManager() .RunVdsCommand(VDSCommandType.RemoveVds, new RemoveVdsVDSCommandParameters(getVdsId())); if (!returnValue.getSucceeded()) { errorType = AuditLogType.USER_FAILED_REMOVE_VDS; } }

Target:
this is not good enough, if for some reason the execution will fail before this method is called, or will fail not because of this run, there will be no error for audit log failure.
Source:
protected void addVmPayload() { VmPayload payload = getParameters().getVmPayload(); if (payload != null) { VmDeviceUtils.addManagedDevice(new VmDeviceId(Guid.NewGuid(), getParameters().getVmId()), VmDeviceType.DISK, payload.getType(), payload.getSpecParams(), true, true, ""); } }

Target:
please remove alias setting (should be encapsulated in addManagedDevice
Source:
public static VmDevice addNetworkInterfaceDevice(VmDeviceId id, boolean plugged) { return addManagedDevice(id, VmDeviceType.INTERFACE, VmDeviceType.BRIDGE, null, plugged, false, ""); }

Target:
please remove alias setting (should be encapsulated in addManagedDevice
Source:
private static <T extends VmBase> void addImportedDisks(T entity, List<VmDevice> vmDeviceToUpdate) { final Guid id = entity.getId(); for (BaseDisk disk : getDisks(entity.getImages())) { Guid deviceId = disk.getId(); VmDevice vmDevice = addManagedDevice(new VmDeviceId(deviceId, id), VmDeviceType.DISK, VmDeviceType.DISK, null, true, false, ""); updateVmDevice(entity, vmDevice, deviceId, vmDeviceToUpdate); } }

Target:
please remove alias setting (should be encapsulated in addManagedDevice
Source:
private static <T extends VmBase> void addImportedInterfaces(T entity, List<VmDevice> vmDeviceToUpdate) { final Guid id = entity.getId(); for (VmNetworkInterface iface : entity.getInterfaces()) { Guid deviceId = iface.getId(); VmDevice vmDevice = addManagedDevice(new VmDeviceId(deviceId, id), VmDeviceType.INTERFACE, VmDeviceType.BRIDGE, null, true, false, ""); updateVmDevice(entity, vmDevice, deviceId, vmDeviceToUpdate); } }

Target:
please remove alias setting (should be encapsulated in addManagedDevice
Source:
private static void addUsbSlots(VmBase vm, int numOfSlots) { for (int index = 1; index <= numOfSlots; index++) { VmDeviceUtils.addManagedDevice(new VmDeviceId(Guid.NewGuid(), vm.getId()), VmDeviceType.REDIR, VmDeviceType.SPICEVMC, getUsbSlotSpecParams(), true, false, ""); } }

Target:
please remove alias setting (should be encapsulated in addManagedDevice
Source:
private static void addEmptyCD(Guid dstId) { VmDeviceUtils.addManagedDevice(new VmDeviceId(Guid.NewGuid(), dstId), VmDeviceType.DISK, VmDeviceType.CDROM, Collections.<String, Object> singletonMap(VdsProperties.Path, ""), true, true, ""); }

Target:
please remove alias setting (should be encapsulated in addManagedDevice
Source:
public Response remove(GlusterBricks bricks) { for (GlusterBrick brick : bricks.getGlusterBricks()) { validateParameters(brick, "id"); } return performAction(VdcActionType.GlusterVolumeRemoveBricks, new GlusterVolumeRemoveBricksParameters(asGuid(getVolumeId()), mapBricks(asGuid(getVolumeId()), bricks))); }

Target:
potential NPE on bricks.getGlusterBricks(), check isSet() first
Source:
public void replaceBrick(GlusterBrickEntity oldBrick, GlusterBrickEntity newBrick) { getCallsHandler().executeModification("UpdateGlusterVolumeBrick", getCustomMapSqlParameterSource().addValue("id", oldBrick.getId()) .addValue("new_id", newBrick.getId()) .addValue("new_server_id", newBrick.getServerId()) .addValue("new_brick_dir", newBrick.getBrickDirectory()) .addValue("new_brick_order", oldBrick.getBrickOrder()) .addValue("new_status", EnumUtils.nameOrNull(newBrick.getStatus()))); }

Target:
Since replace brick keeps order of new brick same as old brick, the parameter "new_brick_order" need not be passed to the SP.
Source:
private ArrayList<String> split(String str) { if (StringHelper.isNullOrEmpty(str)) { return null; } return new ArrayList<String>(Arrays.asList(str.split(SEPARATOR))); }

Target:
not needed
Source:
private void setVmTemplateIdParameter() { Map<Boolean, VmTemplate> templateMap = // Direct LUN can not be on template so we can consider the disk as disk image. getDbFacade().getVmTemplateDAO().getAllForImage(((DiskImage) disk).getImageId()); if (!templateMap.values().isEmpty()) { setVmTemplateId(templateMap.values().iterator().next().getId()); } }

Target:
the common way of writing these is !templateMap().isEmpty()
Source:
public static String map(org.ovirt.engine.core.common.businessentities.DisplayType type, String incoming) { if (type==null) { return null; } else { switch(type) { case vnc: return DisplayType.VNC.value(); case qxl: return DisplayType.SPICE.value(); default: return null; } } }

Target:
i think test failed as it was suppose to fail, it shouldn't be NULL, iirc in GUI default display type for host is QXL and for desktop VNC
Source:
public <E extends Enum<E>> List<E> validateEnums(Class<E> clz, List<String> names) { ArrayList<E> enumList = new ArrayList<E>(); String reason = localize(Messages.INVALID_ENUM_REASON); String detail = localize(Messages.INVALID_ENUM_DETAIL); for (String name : names) { enumList.add(EnumValidator.validateEnum(reason, detail, clz, name)); } return enumList; }

Target:
why simply not call BaseBackendResource.validateEnum(Class<E> clz, String name)? (instead of EnumValidator.validateEnum(reason, detail, clz, name), this why we will not have to maintain localization in two places)
Source:
private ValidationResult() { this(null); }

Target:
Please remember this ctor changed.
Source:
public boolean hasVolumeOnServer(Guid vdsId) { if (getGlusterBrickDao().getGlusterVolumeBricksByServerId(vdsId).size() > 0) { return true; } else { return false; } }

Target:
well this is just a matter of style, but the above can be written also like this: return getGlusterBrickDao().getGlusterVolumeBricksByServerId(vdsId).size() > 0
Source:
protected void executeCommand() { vds_spm_id_map newMap = new vds_spm_id_map(getVds().getstorage_pool_id(), getVdsId(), 0); DbFacade.getInstance().getVdsSpmIdMapDAO().save(newMap); if (getParameters().isCompensationEnabled()) { getCompensationContext().snapshotNewEntity(newMap); getCompensationContext().stateChanged(); } setSucceeded(true); }

Target:
please also add a constructor with out spm_id
Source:
public Response head() { appMode = getCurrent().get(ApplicationMode.class); API api = null; if(appMode == ApplicationMode.GlusterOnly) { api = getApi(); } else { api = getGlusterApi(); } return getResponseBuilder(api).build(); }

Target:
not needed, defined in class
Source:
public Map<String, String> getJobMessageProperties() { if (jobProperties == null) { jobProperties = new HashMap<String, String>(); jobProperties.put(VdcObjectType.VDS.name().toLowerCase(), (getVdsName() == null) ? "" : getVdsName()); jobProperties.put(VdcObjectType.Storage.name().toLowerCase(), getStorageDomainName()); } return jobProperties; }

Target:
No one is passing to command a storageDomain, it is usually ""
Source:
private void assertCanDoActionMessage(VdcBllMessages msg) { assertTrue("canDoAction failed for the wrong reason", command.getReturnValue() .getCanDoActionMessages() .contains(msg.toString())); }

Target:
use name() instead. toString() can be overridden
Source:
protected void setActionMessageParameters() { if (getVdsGroup().supportsGlusterService() || getVdsGroup(getParameters().getClusterId()).supportsGlusterService()) { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__MOVE); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__HOST); } }

Target:
Why set the messages only when the cluster supports gluster? This looks like a generic "Move Host" command, and setting corresponding messages (VAR__ACTION__MOVE and VAR__TYPE__HOST) should be ok irrespective of whether the cluster supports gluster or not.
Source:
public MoveOrCopyImageGroupParameters(Guid containerId, Guid imageGroupId, Guid imageId, Guid destImageGroupId, Guid destImageId, Guid storageDomainId, ImageOperation operation) { this(containerId, imageGroupId, imageId, storageDomainId, operation); setEntityId(destImageId); setDestImageGroupId(destImageGroupId); setDestinationImageId(destImageId); }

Target:
I suppose it intention to overwrite entityId, which was set to imageId at constructor? Code becomes illogical
Source:
private void updateDiskVmSnapshotId() { Guid snapshotId = getSnapshotDao().getId(getVmId(), SnapshotType.ACTIVE); if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { DiskImage diskImage = ((DiskImage) disk); getImageDao().updateImageVmSnapshotId(diskImage.getImageId(), snapshotId); diskImage.setvm_snapshot_id(snapshotId); } else { throw new VdcBLLException(VdcBllErrors.StorageException, "update of snapshot id was initiated for unsupported disk type"); } }

Target:
Again what reason for that line. Lets think: line before we update entry at DB, why I need to update an object which is not updated at DB any more. Why? These is example of dead code. Dead code should not be written
Source:
public AddDiskCommand(T parameters) { super(parameters); parameters.getDiskInfo().setId(Guid.NewGuid()); parameters.setEntityId(parameters.getDiskInfo().getId()); isAddToVm = !Guid.Empty.equals(parameters.getVmId()); }

Target:
this should not be a member. A function at most (as it is computed from the value of another member) or just inline it
Source:
public static String map(org.ovirt.engine.core.common.businessentities.gluster.GlusterVolumeType glusterVolumeType, String template) { switch (glusterVolumeType) { case DISTRIBUTE: return GlusterVolumeType.DISTRIBUTE.name(); case REPLICATE: return GlusterVolumeType.REPLICATE.name(); case DISTRIBUTED_REPLICATE: return GlusterVolumeType.DISTRIBUTED_REPLICATE.name(); case STRIPE: return GlusterVolumeType.STRIPE.name(); case DISTRIBUTED_STRIPE: return GlusterVolumeType.DISTRIBUTED_STRIPE.name(); default: return null; } }

Target:
If you use .value() instead of .name(), you won't have to .toLowerCase() it later (same is true for all places below that use .name())
Source:
public boolean validate(ConfigKey key, String value) { // check if value is file path if (StringUtils.isNotBlank(value) && new File(value).exists()) { return true; } // The only valid value is "Interactive" if (StringUtils.isNotBlank(value) && value.equals(INTERACTIVE_MODE)) { return true; } // or if we have the password in --admin-pass-file if (StringUtils.isNotBlank(parser.getAdminPassFile()) && new File(parser.getAdminPassFile()).exists()) { return true; } return false; }

Target:
Use "equalsIgnoreCase" here.
Source:
protected boolean validateImageNotInTemplate() { if (!hasImages()) { return true; } return getVmTemplateDAO().get(getRepresentativeSourceImageId()) == null; }

Target:
you should check hasImages in canDoAction and if not skip all these validations
Source:
protected boolean InitializeVds() { boolean returnValue = true; if (getVds() == null) { List<VDS> runningVdss = getAllRunningVdssInPool(); setVds(runningVdss.isEmpty() ? null : runningVdss.get(0)); if (getVds() == null) { returnValue = false; addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_NO_VDS_IN_POOL); } } return returnValue; }

Target:
don't like this block, it's unreadable. why not try the follwoing: if (runningVDSs.isEmpty) { returnValue = false; addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_NO_VDS_IN_POOL); } else { setVds(runningVdss); }
Source:
public String extractPasswordValue(String value) throws IOException { String password = null; if (StringUtils.isNotBlank(value) && value.equals(INTERACTIVE_MODE)) { password = EngineConfigLogic.startPasswordDialog(null); } else { password = EngineConfigLogic.getPassFromFile((StringUtils.isNotBlank(value)) ? value : parser.getAdminPassFile()); } return password; }

Target:
If you use "equalsIgnoreCase" here it makes it more user friendly.
Source:
private XmlRpcStruct generateOptions() { XmlRpcStruct options = new XmlRpcStruct(); options.add(VdsProperties.connectivityCheck, Boolean.toString(getParameters().isCheckConnectivity())); // VDSM uses the connectivity timeout only if 'connectivityCheck' is set to true if (getParameters().isCheckConnectivity()) { int connectivityTimeout = getParameters().getConectivityTimeout(); if (connectivityTimeout <= 0) { connectivityTimeout = Config.<Integer> GetValue(ConfigValues.NetworkConnectivityCheckTimeoutInSeconds); } options.add(VdsProperties.connectivityTimeout, connectivityTimeout); } return options; }

Target:
Why is this still needed? We don't trust other half of engine? ;)
Source:
private void warnIfNotAllDisksPermitSnapshots() { if (getParameters().getRunAsStateless()) { for (Disk disk : getVm().getDiskMap().values()) { if (!disk.isAllowSnapshot()) { AuditLogDirector.log(this, AuditLogType.USER_RUN_VM_AS_STATELESS_WITH_DISKS_NOT_ALLOWING_SNAPSHOT); break; } } } }

Target:
checking runAsStateless is not needed since called from inside statelessTreatment method
Source:
public Map<String, String> getJobMessageProperties() { if (jobProperties == null) { jobProperties = new HashMap<String, String>(); jobProperties.put(VdcObjectType.StoragePool.toString().toLowerCase(), getStoragePoolName()); jobProperties.put(VdcObjectType.VmTemplate.toString().toLowerCase(), getVmTemplateName()); } return jobProperties; }

Target:
please use VdcObjectType.StoragePool.name() instead of VdcObjectType.StoragePool.toString()
Source:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getGlusterVolume() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_INVALID); return false; } setVdsGroupId(getGlusterVolume().getClusterId()); return true; }

Target:
super.canDoAction() assuming cluster id already set, when checking for up server, so need to overcome this also, please make sure non of the following commands inheriting from this command base doesn't assume the same, specially in getPermissionCheckSubject that is called before canDoAction (this is why usually we initiate params in the ctor)
Source:
private boolean hasSnappableDisks() { getDisksBasedOnImage(); return !disksImages.isEmpty(); }

Target:
You flaged "Done on my suggestion from the previous patchset, but I don't see any change. Is this intentional?
Source:
protected void EndSuccessfully() { EndActionOnAllImageGroups(); VM vm = getVm(); if (vm != null) { VmHandler.UnLockVm(vm.getId()); endDiskRelatedActions(vm); if (getParameters().getCopyCollapse()) { this.endCopyCollapseOperations(vm); } else { this.endDefaultOps(vm); } } else { setCommandShouldBeLogged(false); log.warn("ExportVmCommand::EndMoveVmCommand: Vm is null - not performing full EndAction"); } setSucceeded(true); }

Target:
Not sure if vm can be null, it is already locked.
Source:
private void endDiskRelatedActions(VM vm) { EndActionOnAllImageGroups(); VmHandler.updateDisksFromDb(vm); VmDeviceUtils.setVmDevices(vm.getStaticData()); }

Target:
previously this was run even if vm == null. Is there a situation where we'd have disks to end action on but vm == null? (sounds odd, but need to make sure why code worked as it did).
Source:
protected void RemoveChildren(Guid snapshot) { List<Guid> children = new ArrayList<Guid>(); GetImageChildren(snapshot, children); Collections.reverse(children); for (Guid child : children) { RemoveSnapshot(getDiskImageDao().getSnapshotById(child)); } }

Target:
Why protected?
Source:
public EntitySearchInfo(IAutoCompleter crossRefAutoCompleter, IConditionFieldAutoCompleter conditionFieldAutoCompleter, String relatedTableNameWithOutTags, String relatedTableName, String primeryKeyName, String defaultSort) { super(); this.crossRefAutoCompleter = crossRefAutoCompleter; this.conditionFieldAutoCompleter = conditionFieldAutoCompleter; this.relatedTableNameWithOutTags = relatedTableNameWithOutTags; this.relatedTableName = relatedTableName; this.primeryKeyName = primeryKeyName; this.defaultSort = defaultSort; }

Target:
why call super?
Source:
public Map<String, String> getJobMessageProperties() { if (jobProperties == null) { jobProperties = super.getJobMessageProperties(); jobProperties.put(VdcObjectType.StoragePool.name().toLowerCase(), (getStoragePoolName() == null) ? "" : getStoragePoolName()); jobProperties.put(VdcObjectType.VDS.name().toLowerCase(), (getVdsName() == null) ? "" : getVdsName()); } return jobProperties; }

Target:
but without it the message will appear as: "Connecting Host <UNKOWN> to Storage server"
Source:
protected boolean checkStoragePool() { if (!super.checkStoragePool()) return false; if (getStoragePool().getstatus() == StoragePoolStatus.Uninitialized) { return true; } if (getStoragePool().getstatus() != StoragePoolStatus.Up) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_ACTIVE); return false; } return true; }

Target:
This conflicts with the commit message - either Uninitiazlied is OK, in which case the commit message should reflect it, or it isn't, in which case the check should be removed.
Source:
protected void endActionOnVmConfiguration() { if (getVm() != null) { if (getVm().getstatus() == VMStatus.ImageLocked) { VmHandler.unlockVm(getVm(), getCompensationContext()); } UpdateVmInSpm(getVm().getstorage_pool_id(), Arrays.asList(getVm())); } else { setCommandShouldBeLogged(false); log.warn("VmCommand::EndVmCommand: Vm is null - not performing EndAction on Vm"); } setSucceeded(true); }

Target:
setSucceeded should not have moved out of EndVmAction()
Source:
protected void endActionOnVmConfiguration() { if (getVm() != null) { if (getVm().getstatus() == VMStatus.ImageLocked) { VmHandler.unlockVm(getVm(), getCompensationContext()); } UpdateVmInSpm(getVm().getstorage_pool_id(), Arrays.asList(getVm())); } else { setCommandShouldBeLogged(false); log.warn("VmCommand::EndVmCommand: Vm is null - not performing EndAction on Vm"); } setSucceeded(true); }

Target:
Not sure why we check if vm can be null here, it should be verified in the canDoAction when executed, and if the VM has disks then the VM should not be deleted, so I don't think vm can be null
Source:
private <T> void validateAndAssertResult(List<VdsNetworkInterface> listOfInterfaces, boolean isValid) { NoRepetitiveStaticIpInListContainer container = new NoRepetitiveStaticIpInListContainer(listOfInterfaces); Set<ConstraintViolation<NoRepetitiveStaticIpInListContainer>> validate = validator.validate(container); Assert.assertEquals(isValid, validate.isEmpty()); }

Target:
why <T> is needed ?
Source:
private static void addBondDeviceToHost(VDS vds, VdsNetworkInterface iface, Object[] interfaces) { vds.getInterfaces().add(iface); if (interfaces != null) { for (Object name : interfaces) { for (VdsNetworkInterface tempInterface : vds.getInterfaces()) { if (tempInterface.getName().equals(name.toString())) { tempInterface.setBondName(iface.getName()); } } } } }

Target:
Please return the break
Source:
void initFrontend() { // Set up Frontend event handlers Frontend.initEventsHandler(frontendEventsHandler); Frontend.getFrontendFailureEvent().addListener(frontendFailureEventListener); Frontend.getFrontendNotLoggedInEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { user.logout(); frontendFailureEventListener.hide(); } }); Frontend.setFilterQueries(filterFrontendQueries()); }

Target:
Maybe we don't need to call 'frontendFailureEventListener.hide()' here, since 'CurrentUser.logout()' will invoke 'BaseApplicationInit.onLogout()' by default.
Source:
public Map<String, String> getJobMessageProperties() { if (jobProperties == null) { jobProperties.put(VdcObjectType.VmTemplate.name().toLowerCase(), (getVmTemplateName() == null) ? "" : getVmTemplateName()); } return jobProperties; }

Target:
this will clearly fail - you must to initialize jobProperties first....
Source:
public ManageDomainsResult(ManageDomainsResultEnum enumResult, String... params) { this("Default error.", enumResult, params); }

Target:
Should be blank or null, not "Default error"
Source:
protected <S extends AbstractBackendResource<?, ?>> S inject(S resource) { resource.setBackend(backend); resource.setMappingLocator(mappingLocator); resource.setValidatorLocator(validatorLocator); resource.setSessionHelper(sessionHelper); resource.setMessageBundle(messageBundle); resource.setUriInfo(uriInfo); resource.setHttpHeaders(httpHeaders); resource.setValidatorLocator(validatorLocator); return resource; }

Target:
why do you set it twice?
Source:
protected ValidatorLocator getValidatorLocator() { if (validatorLocator == null) { validatorLocator = new ValidatorLocator(); validatorLocator.populate(); } return validatorLocator; }

Target:
you do not need creating new instance of validatorLocator for every new sub-resource/subcollection, you can reuse instance defined in BackendApplication by adding [resource.setValidatorLocator(X);] in AbstractBackendResource.inject(). - it used to inject context ('backend', etc.) in to every sub-resource/subcollection,
Source:
private List<String> getVdsIps(VDS vds) { List<String> vdsIps = new ArrayList<String>(); for (VdsNetworkInterface iface : getInterfaceDao().getAllInterfacesForVds(vds.getId())) { vdsIps.add(iface.getAddress()); } return vdsIps; }

Target:
iface.getAddress() might be null, therefore the list will include null element. It may result within a false positive in the comparison below (in fetchServers) therefore the list should be filtered out null elements.
Source:
public void refreshLightWeightData() { log.info("Refreshing Gluster Data [lightweight]"); List<VDSGroup> clusters = getClusterDao().getAll(); for (VDSGroup cluster : clusters) { if (cluster.supportsGlusterService()) { log.debugFormat("Refreshing Gluter Data for cluster {0}", cluster.getname()); refreshClusterData(cluster); } } }

Target:
this will be written every 5 sec (by default) i think its better in debug
Source:
public VolumeType getSelectedVolumeType() { if (!(Boolean) collapseSnapshots.getEntity() || selectedVolumeType == null) { return getVolumeType(); } return selectedVolumeType; }

Target:
I figured out what's bugging me about this line. The logic here is in not semantics. it should be: if ((Boolean) collapseSnapshots.getEntity() && selectedVolumeType != null) { return selectedVolumeType; } return getVolumeType(); This way it is clearer that the only case where user can affect the volume type is if collapse is selected and user changed the value.
Source:
public Map<String, String> getJobMessageProperties() { if (jobProperties == null) { jobProperties = super.getJobMessageProperties(); jobProperties.put(VdcObjectType.VM.name().toLowerCase(), (getVmName() == null) ? "" : getVmName()); jobProperties.put(VdcObjectType.VdsGroups.name().toLowerCase(), getVdsGroupName()); jobProperties.put(VdcObjectType.StoragePool.name(), getStoragePoolName()); } return jobProperties; }

Target:
StorageHandlingCommandBase has: jobProperties.put(VdcObjectType.StoragePool.name().toLowerCase(), getStoragePoolName()); jobProperties.put(VdcObjectType.Storage.name().toLowerCase(), getStorageDomainName()); jobProperties.put(VdcObjectType.VDS.name().toLowerCase(), getVdsName()); So either rely on it or remove the super.getJobMessageProperties call above, but right now it looks like you're doing something redundant. Personally I prefer the latter (getting rid of super...)
Source:
private List<StorageQuotaValidationParameter> getStorageQuotaListParameters() { List<StorageQuotaValidationParameter> list = new ArrayList<StorageQuotaValidationParameter>(); for (Disk disk : getParameters().getVm().getDiskMap().values()) { if(disk instanceof DiskImage){ DiskImage diskImage = (DiskImage)disk; list.add(new StorageQuotaValidationParameter(diskImage.getQuotaId(), imageToDestinationDomainMap.get(diskImage.getId()), diskImage.getSizeInGigabytes())); } } return list; }

Target:
is this fixing anything? the constructor already sets the vm to getParameters().getVm() and getVm either gets the one set in the constructor or goes to the parameters as is done here (which seems redundant, but anyway). So i don't understand why we need to go to the params here.
Source:
public void setDiskStorageMap(HashMap<Guid, ArrayList<Guid>> value) { diskStorageMap = value; raiseDiskEvent(); }

Target:
raiseDiskEvent sounds like an exception. should be something else (the name)
Source:
public static boolean isValidVmNetwork(VmNetworkInterface iface, Map<String, Network> networksByName) { String networkName = iface.getNetworkName(); return (networksByName.containsKey(networkName) && networksByName.get(networkName).isVmNetwork()); }

Target:
Would you mind adding a few unit tests for this in VmInterfaceManagerTest?
Source:
public HotPlugUnplgNicVDSParameters(Guid vdsId, VM vm, VmNetworkInterface nic, VmDevice vmDevice) { super(vdsId); this.vmId = vm.getId(); this.nic = nic; this.vmDevice = vmDevice; this.clusterVersion = vm.getvds_group_compatibility_version(); }

Target:
Why not add getter for VM and use it, instead of splitting to two fields?
Source:
DiskImageBase getDisk() { if (_disk == null) { _disk = (DiskImageBase) getDbFacade().getDiskDao().get(getParameters().getObjectId()); } return _disk; }

Target:
why isn't this private?
Source:
protected boolean canDoAction() { // check if SP exist setStoragePoolId(getParameters().getStoragePoolId()); if (getStoragePool() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_EXIST); return false; } // Check if quota exist: if (getQuotaId() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_QUOTA_IS_NOT_VALID); return false; } if (getDbFacade().getQuotaDAO().getById(getQuotaId()) == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_QUOTA_NOT_EXIST); return false; } return true; }

Target:
well it's not a must but i think the above line better be in the ctor
Source:
protected boolean isAllowClusterWithVirtGluster() { Boolean allowVirGluster = Config.<Boolean> GetValue(ConfigValues.AllowClusterWithVirtGlusterEnabled); if (allowVirGluster == null) { allowVirGluster = Boolean.TRUE; } return allowVirGluster; }

Target:
no need for this check, it shouldn't be null
Source:
private VM getVmForNonShareableDiskImage(DiskImage disk) { if (!disk.isShareable()) { List<VM> vms = getVmDAO().getVmsListForDisk(disk.getId()); if (vms != null && !vms.isEmpty()) { return vms.get(0); } } return null; }

Target:
"vms != null is redundent - the DAO ensures it will return an empty list if no vms are available
Source:
public PermissionSubject(Guid objectId, VdcObjectType objectType, ActionGroup actionGroup, VdcBllMessages message) { super(); this.objectId = objectId; this.ObjectType = objectType; this.actionGroup = actionGroup; this.message = message; }

Target:
super of what?
Source:
protected void validateFingerprint(SSHClient client, String fingerprint) { if (!fingerprint.equals(getFingerprint(client))) { throw new AccessControlException("SSH Fingerprint of server " + getParameters().getServerName() + " did not match expected fingerprint " + fingerprint); } }

Target:
Won't String.format will make this nicer?
Source:
private String getTextValue(Element element, String tagName) { NodeList nodes = element.getElementsByTagName(tagName); Element nodeElement = (Element) nodes.item(0); NodeList nodeList = nodeElement.getChildNodes(); return nodeList.item(0).getNodeValue().trim(); }

Target:
return element.getElementByTagName(tagName).item(0).getChildNodes().item(0).getNodeValue.trim(); Looks very long for standard text node extraction...
Source:
protected boolean canDoAction() { if (getVds() == null) { return failCanDoAction(VdcBllMessages.VDS_CANNOT_ACTIVATE_VDS_NOT_EXIST); } if (true && getVds().getstatus() == VDSStatus.Up) { return failCanDoAction(VdcBllMessages.VDS_CANNOT_ACTIVATE_VDS_ALREADY_UP); } return true; }

Target:
why 'true'? Just check for getVds().getstatus()
Source:
protected void executeQueryCommand() { try { VDSReturnValue returnValue = getBackendResourceManager().RunVdsCommand(VDSCommandType.GetGlusterVolumeAdvancedDetails, new GlusterVolumeAdvancedDetailsVDSParameters(getUpServerId(), getParameters().getClusterId(), getParameters().getVolumeName(), getParameters().getBrickName(), getParameters().detailsRequired())); getQueryReturnValue().setReturnValue(returnValue.getReturnValue()); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
What's the point of catching the exception and then throwing it again, without doing anything in the catch block? There is no need to even wrap it inside a RuntimeException, since what is being thrown inside getUpServerId() is already a RuntimeException.
Source:
private Guid getBrickId(List<GlusterBrickEntity> bricksList, String qualifiedBrickName) { String[] brickParts = qualifiedBrickName.split(":", -1); if (brickParts.length != 2) { throw new RuntimeException("Invalid brick representation [" + qualifiedBrickName + "]"); } for (GlusterBrickEntity brick : bricksList) { // Compare the brickname with the existing volume brick if (brick.getQualifiedName().equals(qualifiedBrickName)) { return brick.getId(); } } return null; }

Target:
This validation is not required. You can expect the brick name returned by glusterfs (and consequently vdsm) to be of the correct format.
Source:
private DiskImage getDiskForVolumeInfo(DiskImage disk) { if (getParameters().getCopyCollapse()) { DiskImage ancestor = DbFacade.getInstance().getDiskImageDao().getAncestor(disk.getImageId()); if (ancestor == null) { log.warnFormat("Can't find ancestor of Disk with ID {0}, using original disk for volume info.", disk.getImageId()); ancestor = disk; } return ancestor; } else { return disk; } }

Target:
Hi Sharad, I saw you already changed the code a bit regarding getDiskImageDao - care to refactor and replace DbFacade.getInstance().getDiskImageDao() with a "getDiskImageDao()" call?
Source:
public String toString() { String AddInfo = getAdditionalInformation(); return String.format("%s(%s %s)", super.toString(), (!StringUtils.isEmpty(AddInfo) ? AddInfo + "," : ""), (getParameters() != null ? getParameters().toString() : "null")); }

Target:
No need for string utils. But if you want to use it, I think they have a isNotEmpty method as well.
Source:
public boolean hasSpaceForSnapthosts(VM vm) { Map<storage_domains, Integer> map = mapStorageDomainsToNumOfDisks(vm); Integer minSnapshotSize = Config.<Integer> GetValue(ConfigValues.InitStorageSparseSizeInGB); for (storage_domains domain : map.keySet()) { if (!StorageDomainSpaceChecker.hasSpaceForRequest(domain, minSnapshotSize * map.get(domain))) { log.error("not enough space to create snapshot on domain " + domain.getId()); return false; } } return true; }

Target:
Please iterate using entrySet
Source:
private void logException(RuntimeException ex) { log.errorFormat("Command {0} execution failed. Exception: {1}", getCommandName(), ExceptionUtils.getMessage(ex)); if (!(ex instanceof VDSExceptionBase)) { log.error(ExceptionUtils.getStackTrace(ex)); } }

Target:
I really don't like the user of instanceof. Why not overload the method to recive VDSExceptionBase? In both places this function is used, you already have that information.
Source:
public String render(Boolean valueToRender) { if(valueToRender == null) return ""; if (trueText == null || falseText == null) { return valueToRender.toString(); } return valueToRender.booleanValue() ? trueText : falseText; }

Target:
On rebase, please wrap the 'return' statement with curly braces and format the lines (i.e. a white-space is missing after the 'if').
Source:
protected void executeCommand() { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.StopGlusterVolumeProfile, new GlusterVolumeVDSParameters(upServer.getId(), getGlusterVolumeName())); setSucceeded(returnValue.getSucceeded()); if (!getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_VOLUME_PROFILE_STOP_FAILED, returnValue.getVdsError().getMessage()); return; } }

Target:
the return statement is redundant here.
Source:
public static QuotaDAO getQuotaDAO() { return DbFacade.getInstance() .getQuotaDao(); }

Target:
maybe package protected would work here? It is a commonly accepted practice when writing unit tests.
Source:
private static void assertNotEmptyCanDoActionMessage() { assertTrue(EXPECTED_CAN_DO_MESSAGE, canDoActionMessages.size() > 0); canDoActionMessages.clear(); }

Target:
optional: consider using assertFalse(EXPECTED_CAN_DO_MESSAGE, canDoActionMessages.isEmpty())
Source:
private static void assertEmptyCanDoActionMessage() { assertTrue(EXPECTED_EMPTY_CAN_DO_MESSAGE, canDoActionMessages.size() == 0); }

Target:
Optional: consider using assertTrue(EXPECTED_EMPTY_CAN_DO_MESSAGE, canDoActionMessages.isEmpty())
Source:
private static void assertAuditLogWritten() { assertTrue(EXPECTED_AUDIT_LOG_MESSAGE, auditLogWritten); auditLogWritten = false; }

Target:
This seems like a bit of a workaround - why not use mockito's verify?
Source:
protected void ExecuteVdsBrokerCommand() { status = getBroker().glusterValidateSshConnection(getParameters().getRemoteServer(), getParameters().getFingerprint(), getParameters().getUserName()); ProceedProxyReturnValue(); setReturnValue(getReturnValue()); }

Target:
What is the purpose of this statement?
Source:
public GetConfigurationValuesQuery(P parameters) { super(parameters); configValuesSet = new HashSet<String>(); }

Target:
in addition to moving it, init it in the right size -ConfigValues.values().size()
Source:
public void findMissingEnumNames() { // Find missing ConfigurationValues enum names in ConfigValues enum boolean missingKey = false; for (ConfigurationValues configValue : ConfigurationValues.values()) { if (!configValuesEnumNames.contains(configValue.toString())) { log.error("Found missing key: " + configValue.toString()); missingKey = true; break; } } assertFalse(missingKey); }

Target:
Please add a message here.
Source:
protected VDSExceptionBase createDefaultConcreteException(String errorMessage) { VDSExceptionBase outEx = new IrsOperationFailedNoFailoverException(errorMessage); return outEx; }

Target:
inline the return statement.
Source:
private VDSExceptionBase createException() { VDSExceptionBase outEx; final String errorMessage = String.format("Failed to %1$s, error = %2$s", getCommandName(), getReturnStatus().mMessage); outEx = createDefaultConcreteException(errorMessage); return outEx; }

Target:
inline the return statement.
Source:
public InvalidQuotaParametersException(String errorStr, Throwable cause) { super("InvalidQuotaParametersException: " + errorStr, cause); }

Target:
I'd just call super(message, cause)
Source:
public QuotaConsumptionParametersWrapper clone() { QuotaConsumptionParametersWrapper cloneWrapper = new QuotaConsumptionParametersWrapper(getAuditLogable(), canDoActionMessages); cloneWrapper.setParameters(new ArrayList<QuotaConsumptionParameter>()); for (QuotaConsumptionParameter parameter : getParameters()) { QuotaConsumptionParameter clone = parameter instanceof QuotaStorageConsumptionParameter ? ((QuotaStorageConsumptionParameter)parameter).clone(): ((QuotaVdsGroupConsumptionParameter)parameter).clone(); cloneWrapper.getParameters().add(clone); } return cloneWrapper; }

Target:
Do you see a scenario in which a QutoaConsumptionParameter will not have the ability to be cloned?
Source:
public QuotaDependency getQuotaDependency() { return this.quotaDependency; }

Target:
remove this
Source:
public static boolean IsVersionMatchStorageType(Version version, StorageType type) { return !((type == StorageType.LOCALFS && version.compareTo(new Version(2, 2)) <= 0) || (type == StorageType.POSIXFS && version.compareTo(new Version(3, 0)) <= 0) || (type == StorageType.GLUSTERFS && version.compareTo(new Version(3, 2)) <= 0)); }

Target:
Config file has GLUSTERFS storage enabled in 3.3, should this be changed here too?
Source:
public List<QuotaStorageConsumptionParameter> getQuotaStorageConsumptionParameters() { List<QuotaStorageConsumptionParameter> list = new ArrayList<QuotaStorageConsumptionParameter>(); for (DiskImage disk : getDisksList()) { list.add(new QuotaStorageConsumptionParameter( disk.getQuotaId(), null, QuotaConsumptionParameter.QuotaAction.CONSUME, disk.getstorage_ids().get(0), disk.getActualSize())); } return list; }

Target:
can you please add a helper method for performing it? this code is repeating itself in all of this patch edited classes.
Source:
protected void endWithFailure() { if (getMoveOrCopyImageOperation() == ImageOperation.Copy) { unLockImage(); if (getParameters().getAddImageDomainMapping()) { // remove image-storage mapping getImageStorageDomainMapDao().remove (new image_storage_domain_map_id(getParameters().getImageId(), getParameters().getStorageDomainId())); } revertTasks(); } else { unLockImage(); } setSucceeded(true); }

Target:
UnlockImage is performed anyway, so it can just be removed out of the if-else.
Source:
protected VDS getEntity(int index) { VDS vds = setUpEntityExpectations(control.createMock(VDS.class), control.createMock(RpmVersion.class), index); VdsStatic vdsStatic = control.createMock(VdsStatic.class); expect(vdsStatic.getId()).andReturn(GUIDS[2]).anyTimes(); expect(vds.getStaticData()).andReturn(vdsStatic).anyTimes(); return vds; }

Target:
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)
Source:
protected void setUpGetHostIdExpectations(int idx) throws Exception { VDS host = BackendHostsResourceTest.setUpEntityExpectations(control.createMock(VDS.class), control.createMock(RpmVersion.class), idx); setUpGetEntityExpectations(VdcQueryType.GetVdsByName, GetVdsByNameParameters.class, new String[] { "Name" }, new Object[] { NAMES[idx] }, host); }

Target:
same here (no need to define the version)
Source:
private List<storage_pool> buildStoragePoolsList() { List<storage_pool> pools = new LinkedList<storage_pool>(); pools.add(pool1); pools.add(pool2); pools.add(pool3); return pools; }

Target:
return Arrays.asList (pool1, pool2, pool3);
Source:
private OvfDataUpdater(){ ovfManager = new OvfManager(); proccessedIdsInfo = new LinkedList<Guid>(); proccessedOvfGenerationsInfo = new LinkedList<Long>(); }

Target:
missing space between () and {
Source:
private void removeOvfForTemplatesAndVmsOfStoragePool(Guid poolId) { List<Guid> idsForRemoval = new LinkedList<Guid>(getVmAndTemplatesGenerationsDao().getIdsForOvfDeletion(poolId)); for (Guid id : idsForRemoval){ executeRemoveVmInSpm(poolId, id, Guid.Empty); } getVmAndTemplatesGenerationsDao().deleteOvfGenerations(idsForRemoval); }

Target:
Why create LinkedList?
Source:
public long getDb_generation() { return db_generation; }

Target:
use java conventions.
Source:
protected VmAndTemplatesGenerationsDAO getVmAndTemplatesGenerationsDao() { return DbFacade.getInstance().getVmAndTemplatesGenerationsDAO(); }

Target:
/s/getVmAndTemplatesGenerationsDao/getVmAndTemplatesGenerationDAO
Source:
private void assertGetResult(VM result) { assertNotNull(result); assertTrue("Vm db generation wasn't loaded as expected", result.getDbGeneration() == 1); assertEquals(result, existingVm); }

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

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

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

Target:
Wait, this is worse than the previous version. What happened to the assertEquals()?
Source:
protected void executeCommand() { VDSGroup vdsGroup = getVdsGroup(); if (vdsGroup.supportsVirtService()) { setSucceeded(initVirtResources()); } if (vdsGroup.supportsGlusterService()) { setSucceeded(initGlusterPeerProcess()); } runVdsCommand(VDSCommandType.GetBiosInfo, new VdsIdAndVdsVDSCommandParametersBase(getVds())); }

Target:
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
Source:
public GetBiosInfoVDSCommand(P parameters) { super(parameters, parameters.getVds()); if (getVds() == null) { setVds(DbFacade.getInstance().getVdsDao().get(parameters.getVdsId())); parameters.setVds(getVds()); } }

Target:
Remove these code is useless , you usually pass a vdsm
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()); logable.AddCustomValue("VmName", getVmName()); AuditLogDirector.log(logable, AuditLogType.USER_CREATE_LIVE_SNAPSHOT_FINISHED_FAILURE); }

Target:
why not set these attributes on the command itself?
Source:
public void removeQuotaFromCache(Guid storagePoolId, Guid quotaId) { lock.readLock().lock(); try { if (!storagePoolQuotaMap.containsKey(storagePoolId)) { return; } synchronized (storagePoolQuotaMap.get(storagePoolId)) { storagePoolQuotaMap.get(storagePoolId).remove(quotaId); } } finally { lock.readLock().unlock(); } }

Target:
should call: removeQuotaFromCache(storagePoolId, Arrays.toList(quotaId)); .. btw why we have here read lock and in the other method write lock?
Source:
private boolean isImplementingRecursive(Class commandClass, Class interfaceClass) { if (Arrays.asList(commandClass.getInterfaces()).contains(interfaceClass)) { return true; } else { return commandClass.getSuperclass() != CommandBase.class && isImplementingRecursive(commandClass.getSuperclass(), interfaceClass); } }

Target:
use equals instead of !=
Source:
public VmNetworkInterface get(Guid id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("id", id); VmNetworkInterface entity = getCallsHandler().executeRead("Getvm_interfaceById", mapper, parameterSource); entity.setVmInterfaceDynamic(DbFacade.getInstance().getVmInterfaceDynamic().get(id)); return entity; }

Target:
This should be done as part of mapper logic, and the fields added to the vm_interface_view, no need to double query.
Source:
public void remove(Guid id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("id", id); getCallsHandler().executeModification("Deletevm_interface", parameterSource); DbFacade.getInstance().getVmInterfaceDynamic().remove(id); }

Target:
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)
Source:
public List<PermissionSubject> getPermissionCheckSubjects() { 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())); } }

Target:
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
Source:
private VmNetworkInterface getIfaceWithNetworkName(List<VmNetworkInterface> interfaces) { if (getNetworkName() == null) { return null; } else { return LinqUtils.firstOrNull(interfaces, new Predicate<VmNetworkInterface>() { @Override public boolean eval(VmNetworkInterface vmNetworkInterface) { return getNetworkName().equals(vmNetworkInterface.getName()); } }); } }

Target:
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.
Source:
protected void executeCommand() { final DiskImage newDiskImage = getParameters().getDiskImage(); if (newDiskImage != null) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { addDiskImageToDb(newDiskImage, getCompensationContext()); getReturnValue().setActionReturnValue(newDiskImage.getId()); getReturnValue().setSucceeded(true); return null; } }); } }

Target:
Why a new transaction is needed here?
Source:
protected boolean canDoAction() { List<String> canDoActionMessages = getReturnValue().getCanDoActionMessages(); Map<Guid, storage_domains> domainsMap = new HashMap<Guid, storage_domains>(); if (!canDoAction_beforeCloneVm(canDoActionMessages, domainsMap)) { return false; } if (getParameters().isImportAsNewEntity()) { initImportClonedVm(); } if (!canDoAction_afterCloneVm(canDoActionMessages, domainsMap)) { return false; } return true; }

Target:
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)