auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void scheduleCheckStatus() { scheduledStatusCheckInProgress = true; Scheduler.get().scheduleFixedDelay( new Scheduler.RepeatingCommand() { @Override public boolean execute() { if (retryCount > MAX_RETRY_COUNTS || reportsWebappDeployed) { scheduledStatusCheckInProgress = false; return false; } retryCount++; checkReportsWebAppStatus(); return true; } }, RETRY_INTERVAL); }

Target:
Why did you move the if from here? Should be- if (scheduledStatusCheckInProgress || retryCount > MAX_RETRY_COUNTS || reportsWebappDeployed) { return; } It is better to keep the if here over duplicating it to 'onError' and 'Response.SC_NOT_FOUND'
Source:
protected List<Guid> executeHSMGetStorageDomainsList(HSMGetStorageDomainsListVDSCommandParameters parameters) { return (ArrayList<Guid>) runVdsCommand(VDSCommandType.HSMGetStorageDomainsList, parameters).getReturnValue(); }

Target:
can it be cast to List?
Source:
public void testImportVMFromConfigurationWhenVMDoesNotExists() { initCommand(null); assertFalse(cmd.canDoAction()); Assert.assertTrue(cmd.getReturnValue() .getCanDoActionMessages() .contains(VdcBllMessages.ACTION_TYPE_FAILED_UNSUPPORTED_OVF.toString())); }

Target:
remove 'Assert.' (there's already a static import)
Source:
public void testImportVMFromConfigurationXMLCouldNotGetParsed() { OvfEntityData ovfEntity = getOvfEntityData(); ovfEntity.setOvfData("This is not a valid XML"); initCommand(ovfEntity); when(unregisteredOVFDataDao.getByEntityIdAndStorageDomain(vmId, storageDomainId)).thenReturn(ovfEntity); assertFalse(cmd.canDoAction()); Assert.assertTrue(cmd.getReturnValue() .getCanDoActionMessages() .contains(VdcBllMessages.ACTION_TYPE_FAILED_OVF_CONFIGURATION_NOT_SUPPORTED.toString())); }

Target:
remove 'Assert.' (there's already a static import)
Source:
private void setXmlOvfData() { try { xmlOvfData = new String(Files.readAllBytes(Paths.get(VM_OVF_XML_DATA))); } catch (IOException e) { e.printStackTrace(); } }

Target:
Just throw it upwards.
Source:
protected ImportVmParameters createParametersWhenImagesExistOnTargetStorageDomain() { ImportVmParameters params = new ImportVmParameters(); params.setContainerId(vmId); params.setStorageDomainId(storageDomainId); params.setVdsGroupId(clusterId); params.setImagesExistOnTargetStorageDomain(true); return params; }

Target:
should be private static
Source:
protected boolean canDoAction() { parameter = getParameters(); if (parameter == null || parameter.getVolumeId() == null || parameter.getSlaveNodeIp() == null || parameter.getSlaveVolumeName() == null) { return false; } masterVolume = getGlusterVolumeDao().getById(parameter.getVolumeId()); if (masterVolume.getStatus() == GlusterStatus.DOWN) { return false; } return true; }

Target:
Do we need a null check here for masterVolume ??
Source:
public UpdateGlusterHostPubKeyToSlaveParameters(Guid vdsId, List<String> pubKeys) { this(vdsId, pubKeys, "root"); }

Target:
may want to externalise to constants..in a separate patch maybe? call it GEOREP_ROOT_USER or similar
Source:
public void updataMaxVmsInPool() { AsyncDataProvider.getInstance().getInstance().getMaxVmsInPool(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { VmModelBehaviorBase behavior = (VmModelBehaviorBase) target; behavior.setMaxVmsInPool((Integer) returnValue); behavior.updateMaxNumOfVmCpus(); } } )); }

Target:
getInstance().getInstance() ?
Source:
protected void executeQueryCommand() { // Get the list of authentication profile names: List<ExtensionProxy> extensions = getExtensionsManager().getExtensionsByService(Authz.class.getName()); List<String> names = new ArrayList<>(extensions.size()); for (ExtensionProxy extension : extensions) { names.add(AuthzUtils.getName(extension)); } if (getParameters().getFilterInternalDomain()) { names.remove(INTERNAL); } sort(names); // Return the sorted list: getQueryReturnValue().setReturnValue(names); }

Target:
why do we remove internal? internal should be as any other.
Source:
private List<DiskImage> getAllDisks(List<DiskImage> newDisksList, List<DiskImage> cloneDisksList) { List<DiskImage> disksList = new ArrayList<>(); disksList.addAll(newDisksList); disksList.addAll(cloneDisksList); return disksList; }

Target:
should be static.
Source:
protected MemoryImageBuilder getMemoryImageBuilder() { if (null == memoryBuilder) { memoryBuilder = createMemoryImageBuilder(); } return memoryBuilder; }

Target:
I'd flip the comparison - if (memoryBuilder == null) - seems more readable.
Source:
private VolumeType getVolumeTypeForDomain() { if (null == volumeTypeForDomain) { StorageDomainStatic sdStatic = DbFacade.getInstance().getStorageDomainStaticDao().get(storageDomainId); volumeTypeForDomain = HibernateVmCommand.getMemoryVolumeTypeForStorageDomain(sdStatic.getStorageType()); } return volumeTypeForDomain; }

Target:
here too - why is the null on the left side?
Source:
public void setCommandExecuted() { Transaction transaction = TransactionSupport.suspend(); try { TaskManagerUtil.updateCommandExecuted(getCommandId()); } finally { TransactionSupport.resume(transaction); } }

Target:
Ravi, if the thread is not in transaction, suspend() returns null. Is it safe to pass null to resume?
Source:
public Fails(VdcBllMessages expected, String... variableReplacements) { matcher = CoreMatchers.allOf( not(isValid()), new WithMessage(expected), hasVariableReplacements(variableReplacements)); }

Target:
you should also replace the access to CoreMatchers.allOf with a static import of allOf to be consistent.
Source:
public ValidationResult(VdcBllMessages message, String... variableReplacements) { if (message == null) { throw new IllegalArgumentException("message must not be null"); } this.message = message; this.variableReplacements = variableReplacements == null ? null : Collections.unmodifiableList(Arrays.asList(variableReplacements)); }

Target:
I think it would be more readable if written as: if (variableReplacements != null) { this.variableReplacements = Collections.unmodifiableList(Arrays.asList(variableReplacements)); }
Source:
protected void findGroups(String searchString, AsyncQuery query) { Frontend.getInstance() .runQuery(VdcQueryType.Search, new DirectorySearchParameters("ADGROUP@" + ((ProfileEntry) getProfile().getSelectedItem()).getAuthz() + ": " + searchString, SearchType.DirectoryGroup, (String) getNamespace().getSelectedItem()), query); //$NON-NLS-1$ //$NON-NLS-2$ }

Target:
If you"ll use generics you won't need this cast.
Source:
public List getEmulatedMachinesList() { // List resultList = lst(); List resultList = lst(); resultList.add("vdsmfake"); resultList.add("host25-rack06.scale.openstack.engineering.redhat.com"); resultList.add("pc-0.12"); resultList.add("pc-0.13"); resultList.add("pc-0.14"); resultList.add("pc-0.15"); resultList.add("pc-1.0"); resultList.add("pc-1.0"); resultList.add("rhel6.4.0"); resultList.add("pc"); resultList.add("isapc"); return resultList; }

Target:
please remove this one
Source:
protected static void removeNetworkFromHosts(Network network, CommandContext context, List<VdsNetworkInterface> nics) { RemoveNetworkParametersBuilder builder = new RemoveNetworkParametersBuilder(network, context); ArrayList<VdcActionParametersBase> parameters = builder.buildParameters(nics); if (!parameters.isEmpty()) { NetworkParametersBuilder.updateParametersSequencing(parameters); Backend.getInstance().runInternalMultipleActions(VdcActionType.PersistentSetupNetworks, parameters, context); } }

Target:
Why protected and not private?
Source:
public void onLogout() { AsyncQuery query = new AsyncQuery(); query.setHandleFailure(true); query.setModel(this); query.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object ReturnValue) { Window.Location.reload(); } }; frontend.logoffAsync(frontend.getLoggedInUser(), query); }

Target:
"this" is not a model, rather than a UI infra object (BaseApplicationInit). Original code (in UserPortal ApplicationInit) was presumably copy-pasted from CommonModel#signOut method, where "this" refers to CommonModel. I suggest to remove this line, I don't think it has any effect here.
Source:
private boolean isOptionEnabledOnVolume(GlusterVolumeEntity volume, List<PredicateFilter<GlusterVolumeOptionEntity>> predicates) { List<GlusterVolumeOptionEntity> volumeOptionsEnabled = new ArrayList<GlusterVolumeOptionEntity>(volume.getOptions()); List<GlusterVolumeOptionEntity> filteredOptions = volumeOptionsEnabled; for(PredicateFilter<GlusterVolumeOptionEntity> predicate : predicates) { filteredOptions = ListUtils.filter(volumeOptionsEnabled, predicate); } if(filteredOptions.size() > 0) { return true; } return false; }

Target:
shouldn't this be filteredOptions = ListUtils.filter(filteredOptions, predicate);
Source:
private String generateTokenValueResponse() { byte[] tokenBytes; HttpSession session = getThreadLocalRequest().getSession(); synchronized (session) { if (session.getAttribute(XSRF_TOKEN) == null) { tokenBytes = new byte[TOKEN_SIZE]; //nextBytes is thread safe. random.nextBytes(tokenBytes); session.setAttribute(XSRF_TOKEN, tokenBytes); } else { tokenBytes = (byte[]) session.getAttribute(XSRF_TOKEN); } } return StringUtils.toHexString(tokenBytes); }

Target:
either get this once or get it always... two patterns: sync { tokenBytes = (byte[]) session.getAttribute(XSRF_TOKEN); if (tokenBytes == null) { ... session.setAttribute(XSRF_TOKEN, tokenBytes); } } or: sync { if (session.getAttribute(XSRF_TOKEN) == null) { ... session.setAttribute(XSRF_TOKEN, tokenBytes); } } tokenBytes = (byte[]) session.getAttribute(XSRF_TOKEN);
Source:
public AuditLogType getAuditLogTypeValue() { if (getSucceeded()) { return AuditLogType.USER_VDS_STOP; } else { return skippedDueToFencingPolicy ? AuditLogType.VDS_NOT_STOPPED_DUE_TO_POLICY : AuditLogType.USER_FAILED_VDS_STOP; } }

Target:
From the user point of view the action that failed was restarting the Host. That's true that we are implementing Restart as stop-wait-start-wait but this should be transparent to the user IMO and the log should say that the restart operation had failed I see that the log of the NonRespondingTreatmentCommand does exactly that so IMO this block should remain without any change : @Override public AuditLogType getAuditLogTypeValue() { return getSucceeded() ? AuditLogType.USER_VDS_STOP : AuditLogType.USER_FAILED_VDS_STOP;
Source:
public void discoverNetworks() { ArrayList<Provider<?>> items = new ArrayList<Provider<?>>(); items.add(provider); getProviders().setItems(items); getProviders().setSelectedItem(provider); }

Target:
Please change the left side to Collection.
Source:
public void testGetEntityNameByIdAndTypeForCpuProfile() { CpuProfile cpuProfile = dbFacade.getCpuProfileDao().get(FixturesTool.CPU_PROFILE_1); assertNotNull(cpuProfile); String name = cpuProfile.getName(); assertTrue(name.equals(dbFacade.getEntityNameByIdAndType(FixturesTool.CPU_PROFILE_1, VdcObjectType.CpuProfile))); }

Target:
can you replace with assertEquals?
Source:
protected void updateMemoryBalloon() { if (getModel().getSelectedCluster() != null) { VDSGroup cluster = getModel().getSelectedCluster(); boolean hasMemoryBalloon = (cluster.getcompatibility_version() .compareTo(VmListModel.BALLOON_DEVICE_MIN_VERSION) >= 0 && cluster.getArchitecture() .compareTo(VmListModel.BALLOON_DEVICE_BLACKLISTED_ARCH) != 0); getModel().getMemoryBalloonDeviceEnabled().setIsAvailable(hasMemoryBalloon); } }

Target:
please change to equals()
Source:
private CommandEntity getParentCommandEntity(Guid cmdId, VdcActionType actionType, VdcActionParametersBase parameters) { CommandEntity cmdEntity = Guid.isNullOrEmpty(cmdId) ? null : coco.getCommandEntity(cmdId); if (cmdEntity == null) { cmdEntity = coco.createCommandEntity(cmdId, actionType, parameters); if (!Guid.isNullOrEmpty(cmdId)) { cmdEntity.setCommandStatus(CommandStatus.ACTIVE); coco.persistCommand(cmdEntity); } } return cmdEntity; }

Target:
I think this already appeared before - maybe move the trenary if logic inside coco.getCommandEntity(guid) ?
Source:
private boolean eventExists(String eventName) { for (AuditLogType alt : AuditLogType.values()) { if (alt.name().equals(eventName)) { return true; } } return false; }

Target:
Wouldn't this solution be better rather than traverse through all values and do string comparisons? private boolean eventExists(String eventName) { boolean exists = false; try { AuditLogType.valueOf(eventName); exists = true; } catch (Exception ex) { } return exists; }
Source:
public List<GlusterGeoRepSessionDetails> getSessionDetails() { return sessionDetails; }

Target:
HI, Is this being used by frontend? If so, shouldn't it be a concrete class, and not List? (See many other place in code), as GWT has issues with dynamic types/inheritance?
Source:
public void executeQueryCommand() { IscsiBond iscsiBond = getDbFacade().getIscsiBondDao().get(getParameters().getId()); if (iscsiBond != null) { iscsiBond.getNetworkIds().addAll(getDbFacade().getIscsiBondDao() .getNetworkIdsByIscsiBondId(iscsiBond.getId())); iscsiBond.getStorageConnectionIds().addAll(getDbFacade().getIscsiBondDao() .getStorageConnectionIdsByIscsiBondId(iscsiBond.getId())); getQueryReturnValue().setReturnValue(iscsiBond); } }

Target:
Why make it public?
Source:
boolean isBalloonEnabled() { Boolean balloonEnabled = getParameters().isBalloonEnabled(); return balloonEnabled != null ? balloonEnabled : VmDeviceUtils.isBalloonEnabled(getVmId()); }

Target:
please make method protected
Source:
public void search() { if (getEntity() != null) super.search(); }

Target:
why the braces removed?
Source:
private void closeConfirmationWindow() { if(getConfirmWindow() == null) { return; } else { setConfirmWindow(null); } }

Target:
you could just do setConfirmWindow(null); like above method
Source:
public boolean isCidrFormatValid(String cidr) { return (cidr != null && cidr.matches(ValidationUtils.CIDR_FORMAT_PATTERN)); }

Target:
no need for surrounding brackets
Source:
public boolean isCidrFormatValid(String cidr) { return (cidr == null || !cidr.matches(ValidationUtils.CIDR_FORMAT_PATTERN)) ? false : true; }

Target:
it could be replaced only by: return cidr != null && cidr.matches(ValidationUtils.CIDR_FORMAT_PATTERN);
Source:
public static boolean isCidrFormatValid(String cidr) { return (cidr == null || !cidr.matches(ValidationUtils.CIDR_FORMAT_PATTERN)) ? false : true; }

Target:
can the methods be non-static?
Source:
private static int covnertIpToInt(String ipAdd) { String[] subAdd = ipAdd.split("\\."); int output = 0; int temp; for (int index = 3; index > -1; index--) { temp = Integer.parseInt(subAdd[3 - index]); temp <<= (index * 8); output |= temp; } return output; }

Target:
1. OutOfBoundaries prone. 2. Why do you start from the less significant part?
Source:
public CidrContainer(String cidr) { super(); this.cidr = cidr; }

Target:
the call for the empty c'tor is redundant.
Source:
public ValidationResult validate(Object value) { assert value instanceof String; String cidr = (String) value; ValidationResult result = new ValidationResult(); if (!CidrValidator.isCidrFormatValid(cidr)) { return failWith(result, getThisFieldMustContainCidrInFormatMsg()); } else if (!CidrValidator.isCidrNetworkAddressValid(cidr)) { return failWith(result, getCidrNotNetworkAddress()); } else { result.setSuccess(true); return result; } }

Target:
1. Shouldn't you check assert (value == null || value instanceof String)? 2. Please add some text explaining why this assertion was made in case it fails (e.g. "This validation must be applied to a String").
Source:
public void setCustomEmulatedMachine(String customEmulatedMachine) { this.customEmulatedMachine = ((customEmulatedMachine == null || customEmulatedMachine.length() == 0) ? null : customEmulatedMachine); }

Target:
please use trim().isEmpty() instead of length check
Source:
public void succededToHibernate() { TransactionSupport.executeInNewTransaction( new TransactionMethod<Object>() { @Override public Object runInTransaction() { VmDynamic vmDynamic = db().getVmDynamicDao().get(id); vmDynamic.setStatus(VMStatus.SavingState); update(vmDynamic); return null; } } ); }

Target:
you can just use getVmDynamicDao()
Source:
protected void setActionMessageParameters() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__PAUSE); }

Target:
call super.setActionMessageParameters();
Source:
protected boolean canDoAction() { setGlusterVolumeId(getGeoRepSession().getMasterVolumeId()); if (!super.canDoAction()) { return false; } if (getGeoRepSession().getStatus() == GeoRepSessionStatus.PASSIVE) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GEOREP_SESSION_ALREADY_PAUSED); } return false; }

Target:
Will the volumeId not be set in the constructor from parameters?
Source:
public synchronized ArrayList getStorageDelay() { return storageDelay; }

Target:
Why you synchronized all the getters to Lists?
Source:
public Map getVmStats(String uuid) { final Host host = getActiveHost(); //about to add some changes Map resultMap = getDoneStatus(); List statusList = new ArrayList(); VM vm = host.getRunningVMs().get(uuid); statusList.add(fillVmStatsMap(vm)); resultMap.put("statsList", statusList); Utils.getLatency(); return resultMap; }

Target:
Can vm be null here?
Source:
public static Map getStatusMap(String message, int code) { Map resultMap = new HashMap(); Map statusMap = new HashMap(); statusMap.put("message", message); statusMap.put("code", Integer.valueOf(code)); resultMap.put("status", statusMap); return resultMap; }

Target:
It would be good to use Map<String, Object> to remove suppressed warnings.
Source:
public void testGetAllEntitiesForStorageDomain() { List<OvfEntityData> ovfEntityDataList = dao.getAllForStorageDomainByEntityType(FixturesTool.STORAGE_DOAMIN_NFS2_1, null); assertTrue("There should be entities fetched for the specified storage domain", !ovfEntityDataList.isEmpty()); assertEquals("A Template and a VM should be fetched for the specified storage domain", 2, ovfEntityDataList.size()); }

Target:
There's no point in asserting the list isn't empty - you check its size on the next line. What you should do is assert it's not null
Source:
public void dispose() { log.info("vdsManager::disposing"); SchedulerUtilQuartzImpl.getInstance().deleteJob(onTimerJobId); XmlRpcUtils.shutDownConnection(_vdsProxy.getHttpClient()); if (JsonRpcVdsServer.class.isInstance(_vdsProxy)) { ((JsonRpcVdsServer) _vdsProxy).close(); } }

Target:
do you think its a good idea to perform these steps in the client code? and for both implementations regardless of the instance in hand?
Source:
private void updateCpus(VmNumaNode vmNumaNode, int coresPerNode, Integer cpuCount) { List<Integer> coreList = new ArrayList<Integer>(); for (int j = 0; j < coresPerNode; j++, cpuCount++) { coreList.add(cpuCount); } vmNumaNode.setCpuIds(coreList); }

Target:
I'd say you will not achieve here what you intended - the Integer is immutable so by cpuCount++ you just replace the value which has been passed here and will have no effect on the value outside of this function where it will still be always 0.
Source:
public StatusOnlyReturnForXmlRpc glusterVolumeGeoRepSessionDelete(String volumeName, String remoteHost, String remoteVolumeName) { try { return new StatusOnlyReturnForXmlRpc(vdsServer.glusterVolumeGeoRepSessionDelete(volumeName, remoteVolumeName, remoteVolumeName)); } catch (UndeclaredThrowableException ute) { throw new XmlRpcRunTimeException(ute); } }

Target:
remoteVolumeName passed twice. I feel remoteHost to be passed as second arg
Source:
protected Map<String, Pair<String, String>> getExclusiveLocks() { if (!isInternalExecution()) { return Collections.singletonMap(getGeoRepSession().getId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.GLUSTER_GEOREP, VdcBllMessages.ACTION_TYPE_FAILED_GEOREP_SESSION_LOCKED)); } return super.getExclusiveLocks(); }

Target:
It get lock on the georep session in one case. But in else case, it will get the lock on the cluster level. Is it the expected behavior?
Source:
private ProcessOvfUpdateForStorageDomainCommandParameters createProcessOvfUpdateForDomainParams() { ProcessOvfUpdateForStorageDomainCommandParameters params = new ProcessOvfUpdateForStorageDomainCommandParameters(getParameters().getStoragePoolId(), getParameters().getStorageDomainId()); params.setSkipDomainChecks(getParameters().isSkipDomainChecks()); params.setParentCommand(getParameters().getParentCommand()); params.setSkipDomainChecks(getParameters().isSkipDomainChecks()); params.setParentParameters(getParameters().getParentParameters()); return params; }

Target:
This set was done already in line 115
Source:
protected WebsocketProxyConfig getConfig() { if (config != null) { new WebsocketProxyConfig( (String) AsyncDataProvider.getInstance().getConfigValuePreConverted(ConfigurationValues.WebSocketProxy), getVncHost()); } return config; }

Target:
did you mean config = ... ? :)
Source:
public List<GlusterGeoRepSession> getAllSessions() { return getCallsHandler().executeReadList("GetAllGlusterGeoRepSessions", georepSessionRowMapper, getCustomMapSqlParameterSource().addValue("user_id", null).addValue("is_filtered", false)); }

Target:
user_id and is_filtered parameters not required
Source:
public void setup() { qos = mock(HostNetworkQos.class); validator = new HostNetworkQosValidator(qos); nullValidator = new HostNetworkQosValidator(null); }

Target:
You can add @RunWith(MockitoJUnitRunner.class) to the class, and then you"ll be able to use @mock on the declaration instead of this initialization. But it is just a matter of style, so as you wish.
Source:
protected StorageDomainValidator getStorageDomainValidator(DiskImage diskImage) { if (storageDomainValidator == null) { StorageDomain storageDomain = getStorageDomainDAO().getForStoragePool( diskImage.getStorageIds().get(0), diskImage.getStoragePoolId()); storageDomainValidator = new StorageDomainValidator(storageDomain); } return storageDomainValidator; }

Target:
If you have a parameter, caching the validator doesn't make sense - the API seems as though you can pass a DiskImage and get a validator for it, when in practice you'll get the same validator regardless of the param.
Source:
private boolean isDomainExistAndActive() { if (!validate(getStorageDomainValidator().isDomainExistAndActive())) { return false; } return true; }

Target:
you replace this code with return validate(getStorageDomainValidator().isDomainExistAndActive()).
Source:
public void testJsonNullDiskDescription() throws IOException { String jsonDescription = null; jsonDescription = ImagesHandler.getJsonDiskDescription("DiskAlias", null); assertTrue("Should be map of disk alias and disk description", jsonDescription.equals("{\"DiskDescription\":\"\",\"DiskAlias\":\"DiskAlias\"}")); }

Target:
please just define on the next row.
Source:
private static void checkMessages() { AuditLogType[] values = AuditLogType.values(); if (values.length != messages.size()) { for (AuditLogType value : values) { if (!messages.containsKey(value)) { log.info("AuditLogType: '{}' not exist in string table", value.toString()); } } } }

Target:
drop toString()
Source:
public SubTabVirtualMachineGeneralView(DetailModelProvider<VmListModel, VmGeneralModel> modelProvider, ApplicationConstants constants) { super(modelProvider); this.form = new VmGeneralModelForm(modelProvider, constants); // Inject a reference to the resources: resources = ClientGinjectorProvider.getApplicationResources(); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); clearAlerts(); generateIds(); this.form.setElementIdPrefixes(); }

Target:
Instead of manually invoking form.setElementIdPrefixes(), you could make AbstractModelBoundFormWidget implement HasElementId interface, with implementation doing following: * get widget's DOM element and set ID on it * execute code in setElementIdPrefixes (no need for separate method now) This way, manually invoking form.setElementIdPrefixes() wouldn't be needed anymore, because HasElementId.setElementId() is called as part of generateIds().
Source:
public static PermitType map(ActionGroup entity, PermitType template) { try { return PermitType.valueOf(entity); } catch (IllegalArgumentException e) { log.error("Missing mapping '{}' --> '{}': {}", entity, PermitType.class.getName(), e.getMessage()); log.debug("Exception", e); return null; } }

Target:
The stack trace should use the same level than the message.
Source:
public void discoverGeoRepData() { // get all clusters List<VDSGroup> clusters = getClusterDao().getAll(); // for every cluster that supports geo-rep monitoring for (VDSGroup cluster : clusters) { discoverGeoRepDataInCluster(cluster, null); } }

Target:
Please consider having a method overloading for the case there is no volume name.
Source:
public int hashCode() { int result = Objects.hashCode(id); return result; }

Target:
There's no need for result attribute: @Override public int hashCode() { return Objects.hashCode(id); }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (this == obj) { return true; } if (!(obj instanceof JobSubjectEntityId)) { return false; } JobSubjectEntityId other = (JobSubjectEntityId) obj; return Objects.equals(entityId, other.entityId) && Objects.equals(jobId, other.jobId); }

Target:
repeated twice
Source:
public String getSysprepFileName(int osId, Version version) { return EngineLocalConfig.getInstance().expandString(getValueByVersion(idToUnameLookup.get(osId), "sysprepFileName", version)); }

Target:
remove the use of EngineLocalConfig.getInstance().expandString. just return getValueByVersion...
Source:
protected void fillMacAddressIfMissing(VmNic iface) { if (StringUtils.isEmpty(iface.getMacAddress()) && getMacPool().getAvailableMacsCount() > 0) { iface.setMacAddress(getMacPool().allocateNewMac()); } }

Target:
is it shared? or going to be? if not, probably need to be private
Source:
public GlusterVolumeSnapshotCreatePopupView(EventBus eventBus, ApplicationResources resources, ApplicationConstants constants, ApplicationMessages messages, CommonApplicationTemplates templates) { super(eventBus, resources); this.messages = messages; this.constants = constants; this.templates = templates; initEditors(); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); ViewIdHandler.idHandler.generateAndSetIds(this); localize(); driver.initialize(this); setTitle(constants.newSnapshot()); }

Target:
Please remove initEditors
Source:
public void getVolumeSnapshotSchedule(AsyncQuery aQuery, Guid volumeId) { aQuery.converterCallback = new IAsyncConverter() { @Override public Object Convert(Object source, AsyncQuery asyncQuery) { return source != null ? source : null; } }; Frontend.getInstance().runQuery(VdcQueryType.GetGlusterVolumeSnapshotScheduleByVolumeId, new IdQueryParameters(volumeId), aQuery); }

Target:
This converter does not have any effect
Source:
private void updateActionAvailability() { boolean allowCreateSnapshot = true; if (getEntity() == null || getEntity().getStatus() == GlusterStatus.DOWN) { allowCreateSnapshot = false; } getNewSnapshotCommand().setIsAvailable(allowCreateSnapshot); boolean allowEditSnapshotSchedule = false; if (getEntity() != null && getEntity().getStatus() == GlusterStatus.UP && getEntity().getSnapshotScheduled()) { allowEditSnapshotSchedule = true; } getEditSnapshotScheduleCommand().setIsAvailable(allowEditSnapshotSchedule); }

Target:
can you please this declaration above near boolean allowCreateSnapshot = true;
Source:
public void edit(final GlusterVolumeSnapshotModel object) { driver.edit(object); forceWarningLabel.setVisible(object.getForceCreate().getEntity()); object.getForceCreate().getEntityChangedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { forceWarningLabel.setVisible(object.getForceCreate().getEntity()); } }); }

Target:
View.edit(model) should not add new listeners to model object. This should be the responsibility of associated presenter - for example, in GlusterVolumeSnapshotCreatePopupPresenterWidget: @Override public void init(final GlusterVolumeSnapshotModel model) { super.init(model); model.getForceCreate().getEntityChangedEvent().addListener(...); } View.edit() is responsible for populating UI from model data and can be potentially called multiple times. Model listener registration therefore doesn't belong here, but in AbstractModelBoundPopupPresenterWidget.init(model) method override.
Source:
public void postOnCreateSnapshot(VdcReturnValueBase returnValue, GlusterVolumeSnapshotEntity snapshot, GlusterVolumeSnapshotModel snapshotModel) { getWindow(); if (returnValue != null && returnValue.getSucceeded()) { setWindow(null); } }

Target:
please remove this
Source:
public void checkPrefixFormatValidation() { assertEquals("Failed to validate prefix's Format: " + mask, isMaskValid && isPrefixValid, MaskValidator.getInstance().isPrefixValid(mask)); }

Target:
The isMaskValid parameter is irrelevant here. This test only checks that the input is in valid prefix format.
Source:
public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { { "255.255.255.255", 0xffffffffL }, { "1.1.1.1", 0x01010101 }, { "1.255.4.255", 0x01ff04ff }, { "0.128.0.7", 0x00800007 }, { "1.2.3.4", 0x01020304 }, { "127.63.31.7", 0x7f3f1f07 }, { "0.0.0.1", 0x00000001 }, { "1.1.1.1", 0x01010101 }, }); }

Target:
In my opinion, this test case is useless - there's no way to verify this is valid with a human eye...
Source:
public Collection<Guid> getRoleIds() { if (roleIds == null) { roleIds = Collections.emptyList(); } return new ArrayList<Guid>(roleIds); }

Target:
As written before - not that critical but consider set (just to ensure nobody will be making a mistake of adding twice the same UUID - i mean, if they do add , you still should have only one copy).
Source:
protected void addCanDoActionMessages(VdcBllMessages... messages) { for (VdcBllMessages msg : messages) { addCanDoActionMessage(msg); } }

Target:
final method?
Source:
public static void storeSubTabHeight(ClientStorage clientStorage, IsWidget widget) { clientStorage.setLocalItem(SubTabHelper.SUB_TAB_HEIGHT_KEY, String.valueOf(widget.asWidget().getOffsetHeight())); }

Target:
s/SubTabHelper.SUB_TAB_HEIGHT_KEY/SUB_TAB_HEIGHT_KEY/ :-)
Source:
protected void invokeCommands(ArrayList<VdcReturnValueBase> returnValues) { if (canRunActions(returnValues)) { if (isWaitForResult) { invokeSyncCommands(); } else { invokeCommands(); } } }

Target:
please make this method private
Source:
private void discoverHostName_SelectedItemChanged() { ExternalDiscoveredHost dhost = (ExternalDiscoveredHost) getExternalDiscoveredHosts().getSelectedItem(); ExternalHostGroup dhg = (ExternalHostGroup) getExternalHostGroups().getSelectedItem(); VDS vds = new VDS(); if (dhost != null && dhg != null) { vds.setVdsName(dhost.getName() + "." + dhg.getDomainName()); //$NON-NLS-1$ vds.setHostName(dhost.getIp()); } updateModelFromVds(vds, null, false, null); }

Target:
so the name will be mac.domain? Is it changable?
Source:
private void init() { setMasterVolume(new EntityModel<String>()); setSlaveVolume(new EntityModel<String>()); setSlaveHost(new EntityModel<String>()); setForce(new EntityModel<Boolean>()); setMessage("");//$NON-NLS-1$ getForce().setEntity(false); }

Target:
This is not required since you are checking for null in view
Source:
public void edit(final GlusterVolumeGeoRepActionConfirmationModel object) { driver.edit(object); forceEditor.setLabel(object.getForceLabel() == null ? constants.notAvailableLabel() : object.getMessage()); messageLabel.setText(object.getMessage() == null ? constants.notAvailableLabel() : object.getMessage()); }

Target:
Why is this required? It should bind automatically
Source:
public void getEngineTimeStamp(AsyncQuery aQuery) { aQuery.setHandleFailure(true); Frontend.getInstance().runQuery(VdcQueryType.GetEngineTimestamp, new VdcQueryParametersBase(), aQuery); }

Target:
1. Not sure if its ok to error on failure to get engine time stamp. 2. Failure to touch base with engine might essentially mean that the subsequent commands also fail and there's no use of asking for user intervention or things of that nature and somehow attempting to proceed with normal flow of snapshot creation. 3. Given 1 and 2 I still feel handling the failure manually in code is better atleast in order to close any other previous window(ex: snapshot create window) Let me know what you opine
Source:
private static List<String> getMountPointsFilter() { return Arrays.asList(Config.<String> getValue(ConfigValues.MountPointsToIgoreInGlusterStorageList).split(",")); }

Target:
the static modifier could go away
Source:
private void updateActionAvailability() { VDS vds = getEntity(); getSyncStorageDevicesCommand().setIsExecutionAllowed(VDSStatus.Up.equals(vds.getStatus())); }

Target:
vds.getStatus() == VDSStatus.Up
Source:
private void persistEngineSession(String sessionId) { SessionInfo sessionInfo = getSessionInfo(sessionId); if (sessionInfo != null) { EngineSession engineSession = new EngineSession(getUser(sessionId, false)); engineSession.setEngineSessionId(sessionId); sessionInfo.contentOfSession.put(ENGINE_SESSION_SEQ_ID, getDbFacade().getEngineSessionDao().save(engineSession)); } }

Target:
instead of setEngineSessionId - why not having it at ctor?
Source:
private ValidationResult validateRangePart(String rangePart) { rangePart.toLowerCase(); boolean matches = MAC_ADDRESS_PATTERN.matcher(rangePart).matches(); if (!matches) { return new ValidationResult(false, "The range start/end is an invalid MAC address. " + rangePart + " should be in a format of AA:AA:AA:AA:AA:AA"); } else { return new ValidationResult(true); } }

Target:
no assignment ?? is there any importance to the case sensitivity?
Source:
protected void addMacsFromDbToPool() { List<VmNic> interfaces = getVmNicInterfacesFromDb(); for (VmNic iface : interfaces) { if (iface.getMacAddress() != null) { forceAddMacWithoutLocking(iface.getMacAddress()); } } }

Target:
could this be private ?
Source:
protected boolean canDoAction() { return isImageExist() && checkOperationIsCorrect() && canFindVmOrTemplate() && isDiskUsedAsOvfStore() && isImageNotLocked() && isSourceAndDestTheSame() && validateSourceStorageDomain() && validateDestStorage() && checkTemplateInDestStorageDomain() && validateSpaceRequirements() && checkCanBeMoveInVm() && checkIfNeedToBeOverride() && setAndValidateDiskProfiles() && verifyShareableDisksMoving(); }

Target:
/s/verifyShareableDisksMoving/validateShareableNotMovedToGluserDomain() regardless i think that this check should reside in validateDestStorage() method
Source:
protected boolean canDoAction() { if (getParameters().getParametersList().isEmpty()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_NO_DISKS_SPECIFIED); } else { return verifyShareableDisksMoving(); } }

Target:
The else is redundant - unwrap it (project's style)
Source:
public void canDoActionFailedUpdateReadOnly() { VmDevice device = createVmDevice(diskImageGuid, vmId); // make sure that device is plugged assertEquals(true, device.getIsPlugged()); when(diskDao.get(diskImageGuid)).thenReturn(createDiskImage()); UpdateVmDiskParameters parameters = createParameters(); parameters.getDiskInfo().setReadOnly(true); initializeCommand(parameters, Collections.singletonList(createVm(VMStatus.Up))); CanDoActionTestUtils.runAndAssertCanDoActionFailure(command, VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_NOT_DOWN); }

Target:
So can't we completely remove this device now? It seems unsued
Source:
private void setupVdsNetworkInterfaceDao() { List<VdsNetworkInterface> expectedVdsNetworkInterface = Collections.singletonList(vdsNetworkInterface); InterfaceDao vdsNetworkInterfaceDaoMock = mock(InterfaceDao.class); when(vdsNetworkInterfaceDaoMock.getVdsInterfacesByNetworkId(networkId)).thenReturn(expectedVdsNetworkInterface); when(getDbFacadeMockInstance().getInterfaceDao()).thenReturn(vdsNetworkInterfaceDaoMock); NetworkDao networkDaoMock = mock(NetworkDao.class); when(getDbFacadeMockInstance().getNetworkDao()).thenReturn(networkDaoMock); }

Target:
I would: 1. Put this in a separate method. 2. Create a mock network to be returned by the networkDao - otherwise it doesn't reflect proper behavior... It'll return null for a network, which shouldn't really happen in real-life scenarios. 3. Also mock qosDao (in a separate method). The out-of-sync functionality should already be tested in NetworkUtilsTest, so not necessary to test it here.
Source:
public boolean isNetworkError() { if (getMessage().startsWith(NETWORK_ERROR_MSG) || getMessage().startsWith(CONNECTION_ISSUES_MSG)) { return true; } else { return false; } }

Target:
Consider explaining this change in commit message as well or extract to another patch..
Source:
private static String findActiveNicName(VDS vds, Map<String, Map<String, Object>> bridges) { final String hostIp = NetworkUtils.getHostByIp(vds); // by now, if the host is communicating with engine over a valid interface, // the interface will have the host's engine IP final VdsNetworkInterface activeIface = resolveActiveNic(vds, hostIp); String hostActiveNic = (activeIface == null) ? null : activeIface.getName(); final String activeBridge = findActiveBridge(hostIp, bridges); if (activeBridge != null) { hostActiveNic = activeBridge; } return hostActiveNic; }

Target:
why not to reverse the order of the conditions by their importance ? { if (has bridge with host id) { return bridge name; } activeNic = resolveActiveNic(); return ... }
Source:
private List<DiskImage> initializeListForCopiedImage() { List<DiskImage> clonedDiskImages = (ArrayList)getImages().clone(); ArrayList<Guid> storageDomains = new ArrayList<>(); for (DiskImage clonedDiskImage : clonedDiskImages) { clonedDiskImage.setStorageIds(storageDomains); } return clonedDiskImages; }

Target:
Yikes. Why not just new ArrayList<>(getImages()) ?
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + sessionId.hashCode(); result = prime * result + allowedValues.hashCode(); result = prime * result + super.hashCode(); return result; }

Target:
remove from here as well
Source:
public boolean equals(Object obj) { return obj != null && obj instanceof GlusterGeoRepSessionConfiguration && ObjectUtils.objectsEqual(getId(), ((GlusterGeoRepSessionConfiguration) obj).getId()) && ObjectUtils.haveSameElements(allowedValues, ((GlusterGeoRepSessionConfiguration) obj).getAllowedValues()) && super.equals(obj); }

Target:
Should allowedValues be considered for object equality?
Source:
public void saveOrUpdateDetailsInBatch(List<GlusterGeoRepSessionDetails> geoRepSessionDetailsObjs) { List<GlusterGeoRepSessionDetails> insertList = new ArrayList<>(); List<GlusterGeoRepSessionDetails> updateList = new ArrayList<>(); for (GlusterGeoRepSessionDetails details : geoRepSessionDetailsObjs) if (getGeoRepSessionDetails(details.getSessionId(), details.getMasterBrickId()) == null) insertList.add(details); else updateList.add(details); saveDetailsInBatch(insertList); updateDetailsInBatch(updateList); }

Target:
Apply default formatter
Source:
public AuditLogType getAuditLogTypeValue() { if (getSucceeded()) return AuditLogType.GLUSTER_GEOREP_CONFIG_SET_DEFAULT; else return errorType == null ? AuditLogType.GLUSTER_GEOREP_CONFIG_SET_DEFAULT_FAILED : errorType; }

Target:
the default standard is to use curly braces
Source:
protected boolean canDoAction() { setGlusterVolumeId(getGeoRepSession().getMasterVolumeId()); return super.canDoAction(); }

Target:
Shouldn't the volumeId be set in constructor only?
Source:
private void postCreateBrick(VdcReturnValueBase returnValue) { CreateBrickModel model = (CreateBrickModel) getWindow(); model.stopProgress(); if (returnValue != null && returnValue.getSucceeded()) setWindow(null); }

Target:
This code style might give formatting error. Even if one line statement it should be within curly braces.
Source:
protected boolean bootProtocolDhcp() { String bootProtocol = (String) this.entry.get("BOOTPROTO"); return bootProtocol != null && "dhcp".equalsIgnoreCase(bootProtocol); }

Target:
this. prefix is redundant
Source:
private boolean isDiskValidForStorage(Disk disk, StorageDomain storage) { if (disk.isShareable() && storage.getStorageType().equals(StorageType.GLUSTERFS)) { return false; } return true; }

Target:
StorageType is an enum - it should be compared with ==
Source:
public Guid getId() { return this.id; }

Target:
this. prefix is not required within getters
Source:
public void testGetById(){ StorageDevice storageDevice = dao.getById(EXISTING_STORAGE_DEVICE_ID_1); assertNotNull("Failed to retrive storage device", storageDevice); assertEquals("Failed to retrive corrective storage device", storageDevice.getId(), EXISTING_STORAGE_DEVICE_ID_1); storageDevice = dao.getById(NON_EXISTING_STORAGE_DEVICE_ID); assertNull(storageDevice); }

Target:
expected as the second arg, actual third arg
Source:
public AuditLogType getAuditLogTypeValue() { if (getSucceeded()) { return AuditLogType.SYNC_STORAGE_DEVICES_IN_HOST; } else { return AuditLogType.SYNC_STORAGE_DEVICES_IN_HOST_FAILED; } }

Target:
it's a matter of styling, but this could be written as: return getSucceeded() ? AuditLogType.SYNC_STORAGE_DEVICES_IN_HOST : AuditLogType.SYNC_STORAGE_DEVICES_IN_HOST_FAILED;
Source:
protected boolean isFileDomainInEditState(StorageDomain storageDomain) { return (storageDomain.getStatus() == StorageDomainStatus.Maintenance || storageDomain.getStorageDomainSharedStatus() == StorageDomainSharedStatus.Unattached); }

Target:
This method can (and should be) private
Source:
@Override protected void executeQueryCommand() { if (getParameters().getStorageType() != null) { getQueryReturnValue().setReturnValue( WipeAfterDeleteUtils.getDefaultWipeAfterDeleteFlag(getParameters().getStorageType())); } }

Target:
style - move the '@Override' annotation to a separate line above
Source:
RequestBuilder createKeepAliveRequest() { RequestBuilder builder = createRequest(); // This request shouldn't do anything other than refresh the REST API session builder.setHeader(ENGINE_REFRESH_HEADER, "refresh-only"); //$NON-NLS-1$ return builder; }

Target:
so probably good to check the value at server side and perform refresh only if specific value is provided.
Source:
public ValidationResult canAddRngDevice(VDSGroup cluster, VmRngDevice rngDevice) { VmRngDevice.Source source = rngDevice.getSource(); boolean supported = cluster != null && isFeatureSupported(cluster.getcompatibility_version()) && cluster.getRequiredRngSources().contains(source); if (supported) { return ValidationResult.VALID; } return new ValidationResult(VdcBllMessages.ACTION_NOT_SUPPORTED_FOR_CLUSTER_POOL_LEVEL); }

Target:
suggestion: return the ValidationResult if !supported and by-default return VALID. I think it's better as this validator might be extended in the future by adding additional validations so it will be easier to modify it that way.
Source:
protected GlusterVolumeSnapshotSchedule getSchedule() { return this.schedule; }

Target:
return schedule; - should suffice
Source:
public void setVmNetwork(Boolean vmNetwork) { if (!ObjectUtils.objectsEqual(this.vmNetwork, vmNetwork)) { this.vmNetwork = vmNetwork; onPropertyChanged(new PropertyChangedEventArgs("Vm Network")); //$NON-NLS-1$ } }

Target:
You don't need this, nobody was listening on the "Role" property changed event. Therefore the whole ObjectUtils.objectsEqual() check isn't necessary either, you may just set the member. (the case could have been different if this item wasn't always available in the form, see the different constructors of FormItem)
Source:
public AbstractValidatedWidgetWithLabel(W contentWidget) { this(contentWidget, new VisibilityRenderer.SimpleVisibilityRenderer()); addStateUpdateHandler(); }

Target:
I missed this in my first review - addStateUpdateHandler() is called due to this() (the other constructor above) so calling addStateUpdateHandler() here is not needed, I guess?
Source:
private void enforceNego(HttpServletResponse response) throws IOException { for (String scheme: new HashSet<>(schemes)) { response.setHeader("WWW-Authenticate", scheme); } response.sendError(HttpServletResponse.SC_UNAUTHORIZED); }

Target:
why can't the schemes be hash from starters?
Source:
public AuditLogType getAuditLogTypeValue() { if(getSucceeded()) return AuditLogType.GLUSTER_VOLUME_GEO_REP_PAUSE; else return AuditLogType.GLUSTER_VOLUME_GEO_REP_PAUSE_FAILED; }

Target:
Did you apply a different formatting style in Eclipse?
Source:
public void setValue(String value) { if (value == null) { clearSelections(); } if (value.isEmpty()) { return; } setValue(value, false); }

Target:
Why not in combination with above do this: setValue(value, false);
Source:
private void addCheckBox(T checkBoxValue) { String checkBoxLabel = renderer.render(checkBoxValue); if (checkBoxLabel == null) { throw new IllegalArgumentException("null value is not permited"); //$NON-NLS-1$ } if (checkBoxes.containsKey(checkBoxValue)) { throw new IllegalArgumentException("Duplicate value: " + checkBoxLabel); //$NON-NLS-1$ } final CheckBox newCheckBox = buildCheckbox(checkBoxValue); checkBoxes.put(checkBoxValue, newCheckBox); }

Target:
Since the only two places that call this method already check if there is a duplicate key, you don't have check here again.
Source:
private int getRowForTheDay(int date) { int row = date / DAYS_IN_WEEK; return date % 7 == 0 ? row - 1 : row; }

Target:
DAYS_IN_WEEK
Source:
private void initializeItems() { List<IStorageModel> items = AsyncDataProvider.getIsoStorageModels(); items.addAll(AsyncDataProvider.getInstance().getExportStorageModels()); items.addAll(AsyncDataProvider.getFileDataStorageModels()); items.addAll(AsyncDataProvider.getImportBlockDataStorageModels()); getModel().setItems(items); }

Target:
Are you sure this has been backported? Checkstyle is complaining about it.
Source:
private boolean isHostNetworkUnreacable(VDS vds) { VdsDynamic vdsDynamic = vds.getDynamicData(); return (vdsDynamic.getStatus() == VDSStatus.Down || vdsDynamic.getStatus() == VDSStatus.Reboot || vdsDynamic.getStatus() == VDSStatus.Kdumping || vdsDynamic.getStatus() == VDSStatus.NonResponsive || (vdsDynamic.getStatus() == VDSStatus.NonOperational || (vdsDynamic.getStatus() == VDSStatus.PendingApproval && vdsDynamic.getNonOperationalReason() == NonOperationalReason.NETWORK_UNREACHABLE)); }

Target:
Please fix bracketing
Source:
private double getVdsMemLimit(VDS curVds) { // if single vm on host. Disregard memory over commitment int computedMemoryOverCommit = (curVds.getVmCount() == 0) ? 100 : curVds.getMaxVdsMemoryOverCommit(); double vdsMemLimit = computedMemoryOverCommit * curVds.getPhysicalMemMb() / 100.0; return vdsMemLimit; }

Target:
also here the variable can be left outuua
Source:
public CommandAssociatedEntity(Guid commandId, VdcObjectType entityType, Guid entityId) { this.commandId = commandId; setEntityType(entityType); setEntityId(entityId); }

Target:
this c'tor implies the entity is immutable. Please let have same assumption for SubjectEntity class and introduce a c'tor there which expect both entityType and entityId and use it here instead of the setters.
Source:
public void setGlusterNetwork(ClusterNetworkModel model, boolean value) { if (!isMultiCluster()) { if (value) { // Reset the old gluster network if (getGlusterNetwork() != null) { getGlusterNetwork().setGlusterNetwork(false); } glusterNetwork = model; } else { // Set the management network as gluster getManagementNetwork().setGlusterNetwork(true); } } model.setGlusterNetwork(value); }

Target:
Shouldn't you update the glusterNetwork member here as well?
Source:
public boolean isUsingScsiReservation() { return usingScsiReservation; }

Target:
this should be a Boolean, it can be null (when you don't load the disk as "disk for vm")
Source:
public ValidationResult isUsingScsiReservationValid(VM vm, LunDisk lunDisk) { // this operation is valid only when attaching disk to VMs if (vm == null && Boolean.TRUE.equals(lunDisk.isUsingScsiReservation())) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_SCSI_RESERVATION_NOT_VALID_FOR_FLOATING_DISK); } // reservation is can be enabled only when sgio is unfiltered if (lunDisk.isUsingScsiReservation() != null && lunDisk.isUsingScsiReservation() && lunDisk.getSgio() == ScsiGenericIO.FILTERED) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_SGIO_IS_FILTERED); } return ValidationResult.VALID; }

Target:
you can use here also Boolean.TRUE.equals()