auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected boolean canDoAction() { boolean retValue = true; START if (getParameters().getDescription().trim().length()==0) { END addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_EMPTY_DESCRIPTION); retValue = false; } return retValue; } StringUtils.isEmpty ?

Target:
protected boolean canDoAction() { boolean retValue = true; if (StringUtils.isEmpty(getParameters().getDescription())) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_EMPTY_DESCRIPTION); retValue = false; } return retValue; }
Source:
public TimeZoneType getTimeZoneType() { VmOsType vmOsType = (VmOsType) getModel().getOSType().getSelectedItem(); START return vmOsType == null ? TimeZoneType.GENERAL_TIMEZONE : TimeZoneType.getTimeZoneByOs(vmOsType); END } Yes, this will solve the NPE, but if I may suggest that better place for this null check should actually be inside the TimeZoneType.getTimeZoneByOs method, to avoid similar omissions in the future. It makes sense for getTimeZoneByOs to return GENERAL_TIMEZONE if the osType is unspecified.

Target:
public TimeZoneType getTimeZoneType() { VmOsType vmOsType = (VmOsType) getModel().getOSType().getSelectedItem(); return TimeZoneType.getTimeZoneByOs(vmOsType); }
Source:
public void toFile(String krb5ConfPath, StringBuffer sb) throws FileNotFoundException, IOException { FileOutputStream fos = null; try { fos = new FileOutputStream(krb5ConfPath); fos.write(sb.toString().getBytes()); } finally { if (fos != null) { fos.close(); } START } END } consider doing: try (FileOutputStream fos = new FileOutputStream(krb5ConfPath)) { fos.write(sb.toString().getBytes()); } which is equivalent to the above, with less lines of code :-)

Target:
public void toFile(String krb5ConfPath, StringBuffer sb) throws FileNotFoundException, IOException { try (FileOutputStream fos = new FileOutputStream(krb5ConfPath)) { fos.write(sb.toString().getBytes()); } }
Source:
private void validateGateway(VdsNetworkInterface iface) { if (!FeatureSupported.multipleGatewaysSupported(vds.getVdsGroupCompatibilityVersion()) && !NetworkUtils.isManagementNetwork(iface.getNetworkName()) START && StringUtils.isNotEmpty(iface.getGateway())) { END addViolation(VdcBllMessages.NETWORK_ATTACH_ILLEGAL_GATEWAY, iface.getNetworkName()); } } please revert the order of conditions from static validation to validation which requires fetching value from DB: private void validateGateway(VdsNetworkInterface iface) {if (StringUtils.isNotEmpty(iface.getGateway()) && !NetworkUtils.isManagementNetwork(iface.getNetworkName()) && !FeatureSupported.multipleGatewaysSupported(vds.getVdsGroupCompatibilityVersion()) ) { ... }

Target:
private void validateGateway(VdsNetworkInterface iface) { if (StringUtils.isNotEmpty(iface.getGateway()) && !NetworkUtils.isManagementNetwork(iface.getNetworkName()) && !FeatureSupported.multipleGatewaysSupported(vds.getVdsGroupCompatibilityVersion())) { addViolation(VdcBllMessages.NETWORK_ATTACH_ILLEGAL_GATEWAY, iface.getNetworkName()); } }
Source:
public boolean validateDistributedStripedReplicateRemove(GlusterVolumeType volumeType, List<GlusterBrickEntity> selectedBricks, List<GlusterBrickEntity> brickList, RemoveBrickModel removeBrickModel) { int stripeCount = removeBrickModel.getStripeCount(); int replicaCount = removeBrickModel.getReplicaCount(); if (selectedBricks.size() != stripeCount * replicaCount) { return false; START } END return true; } is it possible to remove multiple distribution groups in a single shot? If yes, then there is problem with the above logic.

Target:
public boolean validateDistributedStripedReplicateRemove(GlusterVolumeType volumeType, List<GlusterBrickEntity> selectedBricks, List<GlusterBrickEntity> brickList, RemoveBrickModel removeBrickModel) { int stripeCount = removeBrickModel.getStripeCount(); int replicaCount = removeBrickModel.getReplicaCount(); if (selectedBricks.size() % (stripeCount * replicaCount) != 0) { return false; } return true; }
Source:
private void cleanConnection(StorageServerConnections connection, Guid hostId) { // if create connection command was the one to fail and didn't create a connection // then the id of connection will be empty, and there's nothing to delete. START if (connection.getid()!=null && !connection.getid().equalsIgnoreCase("")) { END Frontend.RunAction(VdcActionType.RemoveStorageServerConnection, new StorageServerConnectionParametersBase(connection, hostId), null, this); } } there is no point in case sensitive check for an empty string. Also, just use StringUtils.isEmpty(connection.getId())

Target:
private void cleanConnection(StorageServerConnections connection, Guid hostId) { // if create connection command was the one to fail and didn't create a connection // then the id of connection will be empty, and there's nothing to delete. if (connection.getid() != null && !connection.getid().equals("")) { //$NON-NLS-1$ Frontend.RunAction(VdcActionType.RemoveStorageServerConnection, new StorageServerConnectionParametersBase(connection, hostId), null, this); } }
Source:
public UpdateVmCommand(T parameters) { super(parameters); if (getVdsGroup() != null) { setStoragePoolId(getVdsGroup().getStoragePoolId()); } if (isVmExist()) { setCustomDefinedProperties(parameters.getVmStaticData()); setCustomDefinedProperties(getVm().getStaticData()); } START if (parameters.isConsoleEnabled() == null) { END parameters.setConsoleEnabled(false); } } i think on update we should use null as "don't touch device setting" (if its there leave it, if not don't create)

Target:
public UpdateVmCommand(T parameters) { super(parameters); if (getVdsGroup() != null) { setStoragePoolId(getVdsGroup().getStoragePoolId()); } if (isVmExist()) { setCustomDefinedProperties(parameters.getVmStaticData()); setCustomDefinedProperties(getVm().getStaticData()); } }
Source:
public List<AsyncTasks> getTasksByEntity(Guid entityId) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource(); START parameterSource.addValue("entity_id", entityId); END return getCallsHandler().executeReadList("GetAsyncTasksByEntityId", AsyncTaskRowMapper.instance, parameterSource); } I'd inline this - MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("entity_id", entityId);

Target:
public List<AsyncTasks> getTasksByEntity(Guid entityId) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("entity_id", entityId); return getCallsHandler().executeReadList("GetAsyncTasksByEntityId", AsyncTaskRowMapper.instance, parameterSource); }
Source:
START public static String getMessage(final String key) { END return getMessage(key, LocaleFilter.DEFAULT_LOCALE); } Why is this method static? Only singleton access methods like getInstance() should be static.

Target:
public String getMessage(final String key) { return getMessage(key, LocaleFilter.DEFAULT_LOCALE); }
Source:
public static BrandingManager getInstance(final File etcDir) { if (instance == null) { instance = new BrandingManager(etcDir); START } END return instance; } oh behalf of Michael Pasternak: about [1], i'd consider synchronizing writes at getInstance() & getInstance(final File etcDir) or creating the actual instance at instance var. definition.

Target:
public static synchronized BrandingManager getInstance(final File etcDir) { if (instance == null) { instance = new BrandingManager(etcDir); } return instance; }
Source:
public VDS activate() { VDS vds = null; try { refreshHost(vds); START } catch (java.lang.Exception e) { END log.infoFormat("Failed to activate VDS = {0} with error: {1}.", getVdsId(), e.getMessage()); } return vds; } the prefix of full package name java.lang. is redundant.

Target:
public VDS activate() { VDS vds = null; try { refreshHost(vds); } catch (Exception e) { log.infoFormat("Failed to activate VDS = {0} with error: {1}.", getVdsId(), e.getMessage()); } return vds; }
Source:
protected void releaseMonitorLock(EngineLock monitoringLock, String commandName) { START final VDS vds = getVds(); END getLockManager().releaseLock(monitoringLock); log.infoFormat(commandName + " finished. Lock released. Monitoring can run now for host {0} from data-center {1}", vds.getName(), vds.getStoragePoolName()); } This line should come after the lock is released, since it's not actually used until then.

Target:
protected void releaseMonitorLock(EngineLock monitoringLock, String commandName) { getLockManager().releaseLock(monitoringLock); final VDS vds = getVds(); log.infoFormat(commandName + " finished. Lock released. Monitoring can run now for host {0} from data-center {1}", vds.getName(), vds.getStoragePoolName()); }
Source:
public static Guid getGuidValue(Guid id) { START return id == null ? null : id; END } return id;

Target:
public static Guid getGuidValue(Guid id) { return id; }
Source:
private void setNonOperational(VDS server) { Map<String, String> customValues = new HashMap<String, String>(); customValues.put(GlusterConstants.COMMAND, "gluster peer probe"); START customValues.put(GlusterConstants.SERVER, server.getHostName()); END SetNonOperationalVdsParameters nonOpParams = new SetNonOperationalVdsParameters(server.getId(), NonOperationalReason.GLUSTER_COMMAND_FAILED, customValues); nonOpParams.setSaveToDb(true); Backend.getInstance().runInternalAction(VdcActionType.SetNonOperationalVds, nonOpParams, ExecutionHandler.createInternalJobContext()); } I think the message GLUSTER_COMMAND_FAILED can be changed to use vdsName instead of Server. This way you will not need to add custom value for server in other places - like InitVdsOnUpCommand, SetNonOperationalVdsCommand etc.

Target:
private void setNonOperational(VDS server) { Map<String, String> customValues = new HashMap<String, String>(); customValues.put(GlusterConstants.COMMAND, "gluster peer probe"); SetNonOperationalVdsParameters nonOpParams = new SetNonOperationalVdsParameters(server.getId(), NonOperationalReason.GLUSTER_COMMAND_FAILED, customValues); nonOpParams.setSaveToDb(true); Backend.getInstance().runInternalAction(VdcActionType.SetNonOperationalVds, nonOpParams, ExecutionHandler.createInternalJobContext()); }
Source:
START protected static DbFacade getDbFacade() { END return DbFacade.getInstance(); } can'y this be made private?

Target:
private static DbFacade getDbFacade() { return DbFacade.getInstance(); }
Source:
public void setUp() { mappingLocator = new MappingLocator(); mappingLocator.populate(); HashMap<Integer, String> osNames = new HashMap<>(1); START osNames.put(0, "Unassigned"); END } this has no meaning here . the osNames var is local here and not used by anyone

Target:
public void setUp() { mappingLocator = new MappingLocator(); mappingLocator.populate(); }
Source:
START protected VDSCommandType getRevertVDSCommandType() { END return VDSCommandType.DeleteImageGroup; } reminder: remove the VDSCommandType and just return null (perform rollback from previous task handler).

Target:
protected VDSCommandType getRevertVDSCommandType() { return null; // nothing to do }
Source:
START protected VDSParametersBase getRevertVDSParameters() { END DeleteImageGroupVDSCommandParameters parameters = new DeleteImageGroupVDSCommandParameters(); parameters.setStoragePoolId(getEnclosingCommand().getParameters().getStoragePoolId()); parameters.setStorageDomainId(getEnclosingCommand().getParameters().getStorageDomainId()); parameters.setImageGroupId(getEnclosingCommand().getParameters().getImageGroupID()); return parameters; } perhaps perform the revert through RemoveImageCommand in revertTask() - that way the image would be removed completely in that case (also from the DB) i and we will benefit from the additional logic in RemoveImage.

Target:
protected VDSParametersBase getRevertVDSParameters() { return null; // nothing to do }
Source:
public boolean shouldAlertUpgrade(ArrayList<RpmVersion> isos, Version hostOs) { boolean alert = false; for (RpmVersion iso: isos) { if (iso.getMajor() == hostOs.getMajor() && START iso.compareTo(hostOs) != 0) { END alert = true; break; } } return alert; } why have you changed the > to != ?

Target:
public boolean shouldAlertUpgrade(ArrayList<RpmVersion> isos, Version hostOs) { boolean alert = false; for (RpmVersion iso: isos) { if (iso.getMajor() == hostOs.getMajor() && iso.compareTo(hostOs) > 0) { alert = true; break; } } return alert; }
Source:
public void setVds(VDS vds) { _vds = vds; setHost(_vds.getHostName(), _vds.getSSHPort()); START setUser(_vds.getSSHUsername()); END } please move the setUser and setHost to connect (if _vds != null)

Target:
public void setVds(VDS vds) { _vds = vds; if (_vds != null) { setHost(_vds.getHostName(), _vds.getSSHPort()); setUser(_vds.getSSHUsername()); } }
Source:
public Response end(Action action) { return doAction(VdcActionType.EndExternalStep, START new EndExternalStepParameters(guid, action.isSucceeded(), action.isForce()), action); END } The combination of succedded and force is not clear to me, let's discuss this; I believe this API should change.

Target:
public Response end(Action action) { return doAction(VdcActionType.EndExternalStep, new EndExternalStepParameters(guid, action.isSucceeded()), action); }
Source:
protected Snapshot doPopulate(Snapshot model, org.ovirt.engine.core.common.businessentities.Snapshot entity) { START if (isPopulate()) { END VdcQueryReturnValue queryReturnValue = runQuery(VdcQueryType.GetVmOvfConfigurationBySnapshot, new IdQueryParameters(Guid.createGuidFromString(model.getId()))); if (queryReturnValue.getSucceeded() && queryReturnValue.getReturnValue() != null) { return SnapshotMapper.mapSnapshotConfiguration((String) queryReturnValue.getReturnValue(), ConfigurationType.OVF, model); } } return model; } btw same true for fetchCreatedEntity() which is triggers mapEntity()

Target:
protected Snapshot doPopulate(Snapshot model, org.ovirt.engine.core.common.businessentities.Snapshot entity) { VdcQueryReturnValue queryReturnValue = runQuery(VdcQueryType.GetVmOvfConfigurationBySnapshot, new IdQueryParameters(Guid.createGuidFromString(model.getId()))); if (queryReturnValue.getSucceeded() && queryReturnValue.getReturnValue() != null) { return SnapshotMapper.mapSnapshotConfiguration((String) queryReturnValue.getReturnValue(), ConfigurationType.OVF, model); } return model; }
Source:
public boolean isWebSocketProxyDefined() { String wsConfig = (String) AsyncDataProvider.getConfigValuePreConverted(ConfigurationValues.WebSocketProxy); START return wsConfig != null && !"".equals(wsConfig) && !"Off".equals(wsConfig); //$NON-NLS-1$ $NON-NLS-2$ END } does it have to be "Off" with capital? Don't you need to do a case insensitive compare?

Target:
public boolean isWebSocketProxyDefined() { String wsConfig = (String) AsyncDataProvider.getConfigValuePreConverted(ConfigurationValues.WebSocketProxy); return wsConfig != null && !"".equals(wsConfig) && !"Off".equalsIgnoreCase(wsConfig); //$NON-NLS-1$ $NON-NLS-2$ }
Source:
protected void setActionMessageParameters() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__ADD); START addCanDoActionMessage(VdcBllMessages.VAR__TYPE__NETWORK_QOS); END } this line can be pulled into setActionMessageParameters() method in the NetworkQoSCommandBase class since it repeats in any of the NetworkQoS commands.

Target:
protected void setActionMessageParameters() { addCanDoActionMessage(VdcBllMessages.VAR__TYPE__NETWORK_QOS); }
Source:
protected Map<String, Pair<String, String>> getSharedLocks() { if (getDisk() == null) { return null; } START if (getDisk().getVmEntityType() != null) { END switch (getDisk().getVmEntityType()) { case VM: return createSharedLocksForVmDisk(); case TEMPLATE: return createSharedLocksForTemplateDisk(); } } log.warnFormat("No shared locks are taken while removing disk of entity: {0}", getDisk().getVmEntityType()); return null; } yeah, I didn't think about this.. but don't you prefer to add it to the first clause (i mean to check in line 356) that: getDisk() == null || getDisk().getVmEntityType() == null ? it's a matter of style, so as you think..

Target:
protected Map<String, Pair<String, String>> getSharedLocks() { if (getDisk() == null) { return null; } if (getDisk().getVmEntityType() != null) { switch (getDisk().getVmEntityType()) { case VM: return createSharedLocksForVmDisk(); case TEMPLATE: return createSharedLocksForTemplateDisk(); } } return null; }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) START return false; END AsyncTaskEntity other = (AsyncTaskEntity) obj; return ObjectUtils.objectsEqual(taskId, other.taskId) && ObjectUtils.objectsEqual(entityId, other.entityId) && ObjectUtils.objectsEqual(entityType, other.entityType); } please add brackets to all of these ifs

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } AsyncTaskEntity other = (AsyncTaskEntity) obj; return ObjectUtils.objectsEqual(taskId, other.taskId) && ObjectUtils.objectsEqual(entityId, other.entityId) && ObjectUtils.objectsEqual(entityType, other.entityType); }
Source:
public StoragePool getEntity() { START return (StoragePool) ((super.getEntity() instanceof StoragePool) ? super.getEntity() : null); END } do you need this check? Since the setEntity already takes only StoragePool...

Target:
public StoragePool getEntity() { return (StoragePool) super.getEntity(); }
Source:
public VdcActionParametersBase getParameters(Template incoming, VmTemplate entity) { VmTemplate updated = getMapper(modelType, VmTemplate.class).map(incoming, entity); updated.setUsbPolicy(VmMapper.getUsbPolicyOnUpdate(incoming.getUsb(), entity.getUsbPolicy(), lookupCluster(updated.getVdsGroupId()))); UpdateVmTemplateParameters params = new UpdateVmTemplateParameters(updated); if (incoming.isSetConsoleDeviceEnabled()) { params.setConsoleEnabled(incoming.isConsoleDeviceEnabled()); START } END return params; } i'd create a dedicated mapper for the UpdateVmTemplateParameters (see [1]), [1] VmMapper.RunVmOnceParams map(VM vm, RunVmOnceParams template)

Target:
public VdcActionParametersBase getParameters(Template incoming, VmTemplate entity) { VmTemplate updated = getMapper(modelType, VmTemplate.class).map(incoming, entity); updated.setUsbPolicy(VmMapper.getUsbPolicyOnUpdate(incoming.getUsb(), entity.getUsbPolicy(), lookupCluster(updated.getVdsGroupId()))); return getMapper(modelType, UpdateVmTemplateParameters.class).map(incoming, new UpdateVmTemplateParameters(updated)); }
Source:
public boolean shouldVdsBeFenced() { START boolean result = false; END switch (vds.getStatus()) { case Down: case InstallFailed: case Maintenance: case NonOperational: case NonResponsive: result = true; break; default: break; } return result; } If you want to remove not null validation from constructor, it should be added here

Target:
public boolean shouldVdsBeFenced() { boolean result = false; // Not using exists() here in order not to add canDoAction message if (vds == null) { return false; } switch (vds.getStatus()) { case Down: case InstallFailed: case Maintenance: case NonOperational: case NonResponsive: result = true; break; default: break; } return result; }
Source:
public ValidationResult validateStatusForActivation() { ValidationResult existsValidation = exists(); if (!existsValidation.isValid()) { return existsValidation; } if (vds.getStatus().equals(VDSStatus.Up)) { return new ValidationResult(VdcBllMessages.VDS_ALREADY_UP); } START if (vds.getStatus().equals(VDSStatus.NonResponsive)) { END return new ValidationResult(VdcBllMessages.VDS_NON_RESPONSIVE); } return ValidationResult.VALID; } is it better practice to do the following if (VDSStatus.NonResponsive.equals(vds.getStatus())) same for the check above

Target:
public ValidationResult validateStatusForActivation() { ValidationResult existsValidation = exists(); if (!existsValidation.isValid()) { return existsValidation; } if (VDSStatus.Up == vds.getStatus()) { return new ValidationResult(VdcBllMessages.VDS_ALREADY_UP); } if (VDSStatus.NonResponsive == vds.getStatus()) { return new ValidationResult(VdcBllMessages.VDS_NON_RESPONSIVE); } return ValidationResult.VALID; }
Source:
private void validateParameters(Action action) { START String srvcTypeParam = action.getServiceType(); END validateParameters(action, "serviceType"); validateEnum(ServiceType.class, srvcTypeParam); } any reason for this local var?

Target:
private void validateParameters(Action action) { validateParameters(action, "serviceType"); validateEnum(ServiceType.class, action.getServiceType()); }
Source:
private List<VM> getSelectedVms() { List<VM> vms = new ArrayList<VM>(); if (getSelectedItems() == null) { return vms; } for (Object selectedItem : getSelectedItems()) { UserPortalItemModel itemModel = (UserPortalItemModel) selectedItem; VM vm = itemModel.getVM(); if (vm == null) { START continue; END } vms.add(vm); } return vms; } I'd rather avoid using continue and just do: if (vm != null) { vms.add(vm); }

Target:
private List<VM> getSelectedVms() { List<VM> vms = new ArrayList<VM>(); if (getSelectedItems() == null) { return vms; } for (Object selectedItem : getSelectedItems()) { UserPortalItemModel itemModel = (UserPortalItemModel) selectedItem; VM vm = itemModel.getVM(); if (vm != null) { vms.add(vm); } } return vms; }
Source:
public void newNetwork() { if (getWindow() != null) { return; } final NetworkModel networkModel = new NewNetworkModel(this); setWindow(networkModel); START networkModel.startProgress(null); END initDcList(networkModel); } Why do you do it here and not as part of the initDcList()?

Target:
public void newNetwork() { if (getWindow() != null) { return; } final NetworkModel networkModel = new NewNetworkModel(this); setWindow(networkModel); initDcList(networkModel); }
Source:
public void handleTasksOfCommandWithEmptyVdsmId(final List<AsyncTasks> tasks) { ThreadPoolUtil.execute(new Runnable() { @SuppressWarnings("synthetic-access") @Override public void run() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Object>() { @Override public Object runInTransaction() { boolean isPartiallySubmittedCommand = isPartiallySubmittedCommand(tasks); for (AsyncTasks task : tasks) { handleTaskOfCommandWithEmptyVdsmId(isPartiallySubmittedCommand, task); } START irsBrokerLatch.countDown(); END return null; } }); } }); } I think it is better to do this in the finally block, just in case an exception is thrown in the previous methods.

Target:
public void handleTasksOfCommandWithEmptyVdsmId(final List<AsyncTasks> tasks) { ThreadPoolUtil.execute(new Runnable() { @SuppressWarnings("synthetic-access") @Override public void run() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Object>() { @Override public Object runInTransaction() { try { boolean isPartiallySubmittedCommand = isPartiallySubmittedCommand(tasks); for (AsyncTasks task : tasks) { handleTaskOfCommandWithEmptyVdsmId(isPartiallySubmittedCommand, task); } return null; } finally { irsBrokerLatch.countDown(); } } }); } }); }
Source:
private String getVmIsBeingImportedMessage() { StringBuilder builder = new StringBuilder(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_BEING_IMPORTED.name()); START builder.append(String.format("$VmName %1$s", getVmName())); END return builder.toString(); } possible NPE?

Target:
private String getVmIsBeingImportedMessage() { StringBuilder builder = new StringBuilder(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_BEING_IMPORTED.name()); if (getVmName() != null) { builder.append(String.format("$VmName %1$s", getVmName())); } return builder.toString(); }
Source:
public void testGetMasterStorageDomainIdForPool() { START Guid result = dao.getMasterStorageDomainIdForPool(Guid.createGuidFromString("6d849ebf-755f-4552-ad09-9a090cda105d")); END assertNotNull(result); assertEquals(EXISTING_DOMAIN_ID, result); } use new Guid(String) - this literal can't be null

Target:
public void testGetMasterStorageDomainIdForPool() { Guid result = dao.getMasterStorageDomainIdForPool(new Guid("6d849ebf-755f-4552-ad09-9a090cda105d")); assertNotNull(result); assertEquals(EXISTING_DOMAIN_ID, result); }
Source:
public void testGetstorage_domain_by_type_for_storagePoolId() { START StorageDomain result = dao.getStorageDomainByTypeAndPool(Guid.createGuidFromString("6d849ebf-755f-4552-ad09-9a090cda105d"), StorageDomainType.Master); END assertNotNull(result); assertGetResult(result); } use new Guid(String) - this literal can't be null

Target:
public void testGetstorage_domain_by_type_for_storagePoolId() { StorageDomain result = dao.getStorageDomainByTypeAndPool(new Guid("6d849ebf-755f-4552-ad09-9a090cda105d"), StorageDomainType.Master); assertNotNull(result); assertGetResult(result); }
Source:
public void testGetForStoragePool() { START StorageDomain result = dao.getForStoragePool(existingDomain.getId(), Guid.createGuidFromString("6d849ebf-755f-4552-ad09-9a090cda105d")); END assertGetResult(result); } use new Guid(String) - this literal can't be null

Target:
public void testGetForStoragePool() { StorageDomain result = dao.getForStoragePool(existingDomain.getId(),new Guid("6d849ebf-755f-4552-ad09-9a090cda105d")); assertGetResult(result); }
Source:
public void testGetAllForStoragePoolWithPermissionsPrivilegedUser() { START Guid storagePoolId = Guid.createGuidFromString("6d849ebf-755f-4552-ad09-9a090cda105d"); END List<StorageDomain> result = dao.getAllForStoragePool(storagePoolId, PRIVILEGED_USER_ID, true); assertGetAllForStoragePoolResult(result, storagePoolId); } use new Guid(String) - this literal can't be null

Target:
public void testGetAllForStoragePoolWithPermissionsPrivilegedUser() { Guid storagePoolId = new Guid("6d849ebf-755f-4552-ad09-9a090cda105d"); List<StorageDomain> result = dao.getAllForStoragePool(storagePoolId, PRIVILEGED_USER_ID, true); assertGetAllForStoragePoolResult(result, storagePoolId); }
Source:
public void testGetPermittedStorageDomains() { List<StorageDomain> result = dao.getPermittedStorageDomainsByStoragePool(EXISTING_USER_ID, ActionGroup.CONFIGURE_VM_STORAGE, START Guid.createGuidFromString("6d849ebf-755f-4552-ad09-9a090cda105d")); END assertNotNull(result); assertFalse(result.isEmpty()); assertEquals(result.get(0).getId(), existingDomain.getId()); } use new Guid(String) - this literal can't be null

Target:
public void testGetPermittedStorageDomains() { List<StorageDomain> result = dao.getPermittedStorageDomainsByStoragePool(EXISTING_USER_ID, ActionGroup.CONFIGURE_VM_STORAGE, new Guid("6d849ebf-755f-4552-ad09-9a090cda105d")); assertNotNull(result); assertFalse(result.isEmpty()); assertEquals(result.get(0).getId(), existingDomain.getId()); }
Source:
public void testGetNonePermittedStorageDomains() { List<StorageDomain> result = dao.getPermittedStorageDomainsByStoragePool(EXISTING_USER_ID, ActionGroup.CONSUME_QUOTA, START Guid.createGuidFromString("6d849ebf-755f-4552-ad09-9a090cda105d")); END assertNotNull(result); assertTrue(result.isEmpty()); } use new Guid(String) - this literal can't be null

Target:
public void testGetNonePermittedStorageDomains() { List<StorageDomain> result = dao.getPermittedStorageDomainsByStoragePool(EXISTING_USER_ID, ActionGroup.CONSUME_QUOTA, new Guid("6d849ebf-755f-4552-ad09-9a090cda105d")); assertNotNull(result); assertTrue(result.isEmpty()); }
Source:
public void addExternallyManagedVms(List<VmStatic> externalVmList) { for (VmStatic currVm : externalVmList) { AddVmFromScratchParameters params = new AddVmFromScratchParameters(currVm, null, null); VdcReturnValueBase returnValue = Backend.getInstance().runInternalAction(VdcActionType.AddVmFromScratch, params, ExecutionHandler.createInternalJobContext()); if (!returnValue.getSucceeded()) { START log.debugFormat("Failed adding Externally managed VM {0}", params.getVm().getName()); END } } } not so important but i think it would be nicer to use currVm.getName()

Target:
public void addExternallyManagedVms(List<VmStatic> externalVmList) { for (VmStatic currVm : externalVmList) { AddVmFromScratchParameters params = new AddVmFromScratchParameters(currVm, null, null); VdcReturnValueBase returnValue = Backend.getInstance().runInternalAction(VdcActionType.AddVmFromScratch, params, ExecutionHandler.createInternalJobContext()); if (!returnValue.getSucceeded()) { log.debugFormat("Failed adding Externally managed VM {0}", currVm.getName()); } } }
Source:
public void updateAllInBatch(Collection<T> entities) { START if (entities != null && entities.size() > 0) END updateAllInBatch(getProcedureNameForUpdate(), entities, getBatchMapper()); } we use { even for one line in the scope. lets keep it consider a report if null is passed.

Target:
public void updateAllInBatch(Collection<T> entities) { if (entities != null && entities.size() > 0) { updateAllInBatch(getProcedureNameForUpdate(), entities, getBatchMapper()); } }
Source:
START public synchronized VDS getFullVds() { END if (fullVds == null) { fullVds = DbFacade.getInstance().getVdsDao().get(vdsStatic.getId()); } return fullVds; } any reason this should be synced? make the fullVDs variable volatile and you got the visibility problem solved

Target:
public VDS getFullVds() { if (fullVds == null) { synchronized (this) { if (fullVds == null) { fullVds = DbFacade.getInstance().getVdsDao().get(vdsStatic.getId()); } } } return fullVds; }
Source:
protected boolean canDoAction() { VdsValidator vdsValidator = new VdsValidator(getVds()); return validate(vdsValidator.exists()) && validate(vdsValidator.isUp()) START && validate(vdsValidator.validateMinimumVersionSupport(Version.v3_3)); END } Please use FeatureSupported class for the versioning checking, it's the standard way to constrain the feature to a specific version.

Target:
protected boolean canDoAction() { VdsValidator vdsValidator = new VdsValidator(getVds()); return validate(vdsValidator.exists()) && validate(vdsValidator.isUp()) && validate(validateMinimumVersionSupport()); }
Source:
protected void validateParameters(VnicProfile vnicProfile) { validateParameters(vnicProfile, "name"); START if (!vnicProfile.isSetNetwork() || !vnicProfile.getNetwork().isSetId()) { END vnicProfile.setNetwork(new Network()); vnicProfile.getNetwork().setId(networkId); } } this is not a part of the validateParameters() logic

Target:
protected void validateParameters(VnicProfile vnicProfile) { validateParameters(vnicProfile, "name"); }
Source:
protected String getSearchPattern() { String user_defined_pattern = QueryHelper.getConstraint(getUriInfo(), "", modelType); return user_defined_pattern.equals("Users : ") ? user_defined_pattern + USERS_SEARCH_PATTERN : START user_defined_pattern + AND_SEARCH_PATTERN + USERS_SEARCH_PATTERN; END } now when you split, we should not allow seeing AD users in this context.

Target:
private String getSearchPattern() { String user_defined_pattern = QueryHelper.getConstraint(getUriInfo(), "", modelType); return user_defined_pattern.equals("Users : ") ? user_defined_pattern + USERS_SEARCH_PATTERN : user_defined_pattern + AND_SEARCH_PATTERN + USERS_SEARCH_PATTERN; }
Source:
public void ClearTasks() { synchronized (_listTasks) { java.util.ArrayList<CommandAsyncTask> CurrentActionTypeTasks = getCurrentTasks(); for (CommandAsyncTask task : CurrentActionTypeTasks) { if (task.getLastTaskStatus().getStatus() == AsyncTaskStatusEnum.finished) { task.clearAsyncTask(); START if (task.getVdsmTaskId() != null) { END _listTasks.remove(task.getVdsmTaskId()); } } } } } if we already called clearAsyncTask(), wouldn't we want to remove it from the list regardless of vdsmTaskId?

Target:
public void ClearTasks() { synchronized (_listTasks) { java.util.ArrayList<CommandAsyncTask> CurrentActionTypeTasks = getCurrentTasks(); for (CommandAsyncTask task : CurrentActionTypeTasks) { if (task.getLastTaskStatus().getStatus() == AsyncTaskStatusEnum.finished) { task.clearAsyncTask(); _listTasks.remove(task.getVdsmTaskId()); } } } }
Source:
private void initDisplayProtocol() { START ArrayList<EntityModel> displayProtocolOptions = new ArrayList<EntityModel>(); END getDisplayProtocol().setItems(displayProtocolOptions); getDisplayProtocol().getSelectedItemChangedEvent().addListener(this); } can be just inlined as setItems(new ArrayList...)

Target:
private void initDisplayProtocol() { getDisplayProtocol().getSelectedItemChangedEvent().addListener(this); }
Source:
private static boolean hasTaskCompleted(GlusterAsyncTask task) { if (JobExecutionStatus.ABORTED.equals(task.getStatus()) || JobExecutionStatus.FINISHED.equals(task.getStatus()) START || JobExecutionStatus.FAILED.equals(task.getStatus())) { END return true; } return false; } Why "equals" instead of "==". Above method also has same logic, please remove the duplication.

Target:
private static boolean hasTaskCompleted(GlusterAsyncTask task) { if (JobExecutionStatus.ABORTED == task.getStatus() || JobExecutionStatus.FINISHED == task.getStatus() || JobExecutionStatus.FAILED == task.getStatus()) { return true; } return false; }
Source:
protected ValidationResult isVmInterfacesConfigured(VM vm) { for (VmNetworkInterface nic : vm.getInterfaces()) { if (nic.getVnicProfileId() == null) { START return !FeatureSupported.networkLinking(vm.getVdsGroupCompatibilityVersion()) ? END new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_INTERFACE_NETWORK_NOT_CONFIGURED) : ValidationResult.VALID; } } return ValidationResult.VALID; } would you mind reverting the condition into a positive form ? return FeatureSupported.networkLinking(vm.getVdsGroupCompatibilityVersion()) ? ValidationResult.VALID: new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_INTERFACE_NETWORK_NOT_CONFIGURED);

Target:
protected ValidationResult isVmInterfacesConfigured(VM vm) { for (VmNetworkInterface nic : vm.getInterfaces()) { if (nic.getVnicProfileId() == null) { return FeatureSupported.networkLinking(vm.getVdsGroupCompatibilityVersion()) ? ValidationResult.VALID: new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_INTERFACE_NETWORK_NOT_CONFIGURED); } } return ValidationResult.VALID; }
Source:
private boolean isNotSPM(VDSReturnValue returnValue) { START return returnValue != null && returnValue.getVdsError() != null && END returnValue.getVdsError().getCode() == VdcBllErrors.SpmStatusError; } the two last checks can and should be squashed into one check - returnValue.getVdsError() != VdcBllErrors.SpmStatusError, I actually prefer !VdcBllErrors.SpmStatusError.equals(returnValue.getVdsError()) the first check can be removed, but that's up to you..if it's being changed into one check, the whole method call can be replaced with the check :)

Target:
private boolean isNotSPM(VDSReturnValue returnValue) { return returnValue.getVdsError() != null && returnValue.getVdsError().getCode() == VdcBllErrors.SpmStatusError; }
Source:
private static void updateOption(VdcOption option) { Map<String, Object> values = _vdcOptionCache.get(option.getoption_name()); if (values == null) { values = new HashMap<String, Object>(); _vdcOptionCache.put(option.getoption_name(), values); } START log.info("In updateOption decrypting and saving option "+option.getoption_name()+" version = "+option.getversion()); END values.put(option.getversion(), GetValue(option)); } This looks more like a debug to me. Can you please remove this one, or maybe have it as log.debug?

Target:
private static void updateOption(VdcOption option) { Map<String, Object> values = _vdcOptionCache.get(option.getoption_name()); if (values == null) { values = new HashMap<String, Object>(); _vdcOptionCache.put(option.getoption_name(), values); } values.put(option.getversion(), GetValue(option)); }
Source:
public AddBondParameters(Guid vdsId, String bondName, Network network, String[] nics, int vladId) { this(vdsId, bondName, network, nics); setVlanId(vladId); START privateBootProtocol = NetworkBootProtocol.NONE; END } Redundant, the call to this(vdsId, bondName, network, nics) already handles it

Target:
public AddBondParameters(Guid vdsId, String bondName, Network network, String[] nics, int vladId) { this(vdsId, bondName, network, nics); setVlanId(vladId); }
Source:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } START if (getParameters().getRngDevice() == null) { END return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_RNG_NOT_FOUND); } if (!getRngDevices().isEmpty()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_RNG_ALREADY_EXISTS); } return true; } this should be in super as well.. even first

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (!getRngDevices().isEmpty()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_RNG_ALREADY_EXISTS); } return true; }
Source:
public String value() { START return statusMsg.toUpperCase(); END } but it's already defined as upper case - so, do we really need to run "toUpperCase"?

Target:
public String value() { return statusMsg; }
Source:
START public String getCascadedResource(String resourceName) { END List<BrandingTheme> brandingThemes = getBrandingThemes(); // assume these are sorted 00, 01, 02, etc. for (int i = brandingThemes.size() - 1; i >= 0; i--) { String resourcePath = brandingThemes.get(i).getResourcePath(resourceName); if (resourcePath != null) { return resourcePath; } } return null; } The resource name should be gotten from the interface (branding.properties), you cannot relay on file name.

Target:
public String getCascadedResource(String resourceName) { if (resourceName != null) { List<BrandingTheme> brandingThemes = getBrandingThemes(); // assume these are sorted 00, 01, 02, etc. for (int i = brandingThemes.size() - 1; i >= 0; i--) { String resourcePath = brandingThemes.get(i).getResourcePath(resourceName); if (resourcePath != null) { return resourcePath; } } } return null; }
Source:
START private static int isIsoVersionSupported(String isoVersion) { END String supported = Config.<String> GetValue(ConfigValues.OvirtInitialSupportedIsoVersion); return VersionUtils.compareRpmPart(isoVersion, supported); } should not be static, please check.

Target:
private boolean isIsoVersionSupported(String isoVersion) { String supported = Config.<String> GetValue(ConfigValues.OvirtInitialSupportedIsoVersion); return VersionUtils.compareRpmPart(isoVersion, supported) >= 0; }
Source:
private String getDiskIsBeingMigratedMessage() { if (cachedDiskIsBeingMigratedMessage == null) { StringBuilder builder = new StringBuilder(VdcBllMessages.ACTION_TYPE_FAILED_DISK_IS_BEING_MIGRATED.name()); if (getImage() != null) { builder.append(String.format("$DiskName %1$s", getDiskAlias())); } builder.append(String.format("$OperationType %1$s", ImageOperation.Move == getParameters().getOperation() ? "moved" : "copied")); START cachedDiskIsBeingMigratedMessage = builder.toString(); END } return cachedDiskIsBeingMigratedMessage; } where does the caching help u?

Target:
private String getDiskIsBeingMigratedMessage() { if (cachedDiskIsBeingMigratedMessage == null) { StringBuilder builder = new StringBuilder(VdcBllMessages.ACTION_TYPE_FAILED_DISK_IS_BEING_MIGRATED.name()); if (getImage() != null) { builder.append(String.format("$DiskName %1$s", getDiskAlias())); } cachedDiskIsBeingMigratedMessage = builder.toString(); } return cachedDiskIsBeingMigratedMessage; }
Source:
void forceRefresh(M model) { if (model instanceof SearchableListModel) { UICommand lastExecutedCommand = model.getLastExecutedCommand(); if (lastExecutedCommand != null && !lastExecutedCommand.getIsCancel()) { // Refresh the grid using ForceRefresh command SearchableListModel searchableList = (SearchableListModel) model; START searchableList.getForceRefreshCommand().execute(); END } } } for readability/consistency, consider invoking SearchableListModel -> forceRefresh() instead...

Target:
void forceRefresh(M model) { if (model instanceof SearchableListModel) { UICommand lastExecutedCommand = model.getLastExecutedCommand(); if (lastExecutedCommand != null && !lastExecutedCommand.getIsCancel()) { // Refresh grid after invoking non-cancel command SearchableListModel searchableList = (SearchableListModel) model; searchableList.forceRefresh(); } } }
Source:
protected boolean acquireLockInternal() { final boolean acquireLock = super.acquireLockInternal(); START if (!acquireLock && getVm().isAutoStartup()) { END AutoStartVmsRunner.getInstance().addVmToRun(getParameters().getVmId()); } return acquireLock; } add a null check here please

Target:
protected boolean acquireLockInternal() { final boolean acquireLock = super.acquireLockInternal(); if (!acquireLock && getVm() != null && getVm().isAutoStartup()) { AutoStartVmsRunner.getInstance().addVmToRun(getParameters().getVmId()); } return acquireLock; }
Source:
protected void ExecuteVdsBrokerCommand() { glusterTaskReturn = getBroker().glusterVolumeRemoveBricksStart(getParameters().getVolumeName(), getParameters().getBrickDirectories().toArray(new String[0]), getParameters().getReplicaCount(), getParameters().isForceRemove()); task = glusterTaskReturn.getGlusterTask(); setReturnValue(task); START proceedProxyReturnValue(); END } Mostly we call processProxyReturnValue() before setting the return value. The setting of the retunr value should be the last statement.

Target:
protected void ExecuteVdsBrokerCommand() { glusterTaskReturn = getBroker().glusterVolumeRemoveBricksStart(getParameters().getVolumeName(), getParameters().getBrickDirectories().toArray(new String[0]), getParameters().getReplicaCount(), getParameters().isForceRemove()); task = glusterTaskReturn.getGlusterTask(); proceedProxyReturnValue(); setReturnValue(task); }
Source:
public void moveUnpluggedDiskVmDown() { command.getParameters().setParametersList(createMoveDisksParameters()); initDiskImage(diskImageId); initVm(VMStatus.Down, Guid.newGuid(), diskImageId, false); command.updateParameters(); START assertTrue(command.getMoveDiskParametersList().size() == 1); END } use assertEquals

Target:
public void moveUnpluggedDiskVmDown() { command.getParameters().setParametersList(createMoveDisksParameters()); initDiskImage(diskImageId); initVm(VMStatus.Down, Guid.newGuid(), diskImageId, false); command.updateParameters(); assertEquals(command.getMoveDiskParametersList().size(), 1); }
Source:
START public static List<String> getVirtioScsiControllersForEntity(Guid id) { END return VmHelper.getInstance().getEntity(List.class, VdcQueryType.GetVirtioScsiControllers, new IdQueryParameters(id), "GetVirtioScsiControllers", true); } ummm... is this is a singleton, should this simply be an instance method?

Target:
public List<String> getVirtioScsiControllersForEntity(Guid id) { return getEntity(List.class, VdcQueryType.GetVirtioScsiControllers, new IdQueryParameters(id), "GetVirtioScsiControllers", true); }
Source:
protected BaseEditVmInterfaceModel(VmBase vm, START VMStatus vmStatus, Guid dcId, END Version clusterCompatibilityVersion, ArrayList<VmNetworkInterface> vmNicList, VmNetworkInterface nic, EntityModel sourceModel) { super(vm, dcId, clusterCompatibilityVersion, vmNicList, sourceModel, new EditProfileBehavior()); this.nic = nic; this.vmStatus = vmStatus; setTitle(ConstantsManager.getInstance().getConstants().editNetworkInterfaceTitle()); setHashName("edit_network_interface_vms"); //$NON-NLS-1$ } Please format for uniformity, i.e. one argument per line. There's a formatter that's part of the git repository, you can just plug it into an IDE and let it do the job for you.

Target:
protected BaseEditVmInterfaceModel(VmBase vm, VMStatus vmStatus, Guid dcId, Version clusterCompatibilityVersion, ArrayList<VmNetworkInterface> vmNicList, VmNetworkInterface nic, EntityModel sourceModel) { super(vm, vmStatus, dcId, clusterCompatibilityVersion, vmNicList, sourceModel, new EditProfileBehavior()); this.nic = nic; setTitle(ConstantsManager.getInstance().getConstants().editNetworkInterfaceTitle()); setHashName("edit_network_interface_vms"); //$NON-NLS-1$ }
Source:
START public Disk getDisk() { END if (disk == null) { disk = getDiskDao().get(getParameters().getDiskId()); } return disk; } Please use protected here

Target:
protected Disk getDisk() { if (disk == null) { disk = getDiskDao().get(getParameters().getDiskId()); } return disk; }
Source:
public HotPlugDiskToVmCommand(T parameters) { super(parameters); START disk = getDiskDao().get(getParameters().getDiskId()); END } constructors are a bad place to invoke DB operations - it makes it really hard to test this command. Why not use a simple lazy getter?

Target:
public HotPlugDiskToVmCommand(T parameters) { super(parameters); }
Source:
public void cancelRefresh() { if(refresh == null) { return; } else { refresh.cancel(); START } END } This can be simplified as follows if(refresh != null) { refresh.cancel(); }

Target:
public void cancelRefresh() { if(refresh != null) { refresh.cancel(); } }
Source:
public void refresh(final GlusterVolumeEntity volumeEntity) { refresh = new Timer() { @Override public void run() { refreshDetails(volumeEntity); } }; START refresh.schedule(10000); END } The problem still exists You are just cancelling the last timer not the previous one If you see above, after each request has returned you are creating a new timer and scheduling. Can this timer be re-used? May be you can create the time in the constructor and the schedule can be triggered from wherever you want

Target:
public void refresh(final GlusterVolumeEntity volumeEntity) { refresh.schedule(10000); }
Source:
private static long retrieveIsoFileSize(Map.Entry<String, Map<String, String>> isoFileWithMetadata) { // old VDSM versions don't provide the metadata for iso files therefore engine marks size as not available String sizeValue = isoFileWithMetadata.getValue().get("size"); if (sizeValue == null) { return SIZE_IS_NOT_AVAILABLE; } START END try { return Long.valueOf(sizeValue); } catch (NumberFormatException e) { // illegal number is treated as not available, treating exception in UI will be more complicate log.errorFormat("File's '{0}' size is illegal number", isoFileWithMetadata.getKey(), e); return SIZE_IS_NOT_AVAILABLE; } } Lines 578-581 can be removed since Long.valueOf handles null.

Target:
private static long retrieveIsoFileSize(Map.Entry<String, Map<String, String>> isoFileWithMetadata) { String sizeValue = isoFileWithMetadata.getValue().get("size"); try { return Long.valueOf(sizeValue); } catch (NumberFormatException e) { // Illegal number or null are treated as not available, handling // exception in UI will be more complicate log.errorFormat("File's '{0}' size is illegal number", isoFileWithMetadata.getKey(), e); return SIZE_IS_NOT_AVAILABLE; } }
Source:
protected boolean canDoAction() { GlusterVolumeEntity glusterVolume = getGlusterVolume(); if (!super.canDoAction()) { return false; } boolean isVolumeDistributed = glusterVolume.getVolumeType().isDistributedType(); if (!isVolumeDistributed) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_NOT_DISTRIBUTED); START } else if (isVolumeDistributed && glusterVolume.getBricks().size() == 1) { END return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_DISTRIBUTED_AND_HAS_SINGLE_VOLUME); } return true; } redundant clause at the second if , as it's "else if" from the if (!isVolumeDistributed) - this means that else if will be called when isVolumeDestributed == true and no need to include it in the 2nd clause.

Target:
protected boolean canDoAction() { GlusterVolumeEntity glusterVolume = getGlusterVolume(); if (!super.canDoAction()) { return false; } boolean isVolumeDistributed = glusterVolume.getVolumeType().isDistributedType(); if (!isVolumeDistributed) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_NOT_DISTRIBUTED); } else if (glusterVolume.getBricks().size() == 1) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_DISTRIBUTED_AND_HAS_SINGLE_VOLUME); } return true; }
Source:
public int countDownBricks(GlusterVolumeEntity volume) { int downCount = 0; int upCount = 0; START for (int i = 0 ; i < volume.getBricks().size(); i++) { END GlusterBrickEntity brick = volume.getBricks().get(i); if(brick.getStatus() == GlusterStatus.UP) { upCount++; }else { downCount++; } if(upCount > 0 && downCount > 0) { return downCount; } } return downCount; } use foreach style loop

Target:
public int countDownBricks(GlusterVolumeEntity volume) { int downCount = 0; int upCount = 0; for (GlusterBrickEntity brick : volume.getBricks()) { if (brick.getStatus() == GlusterStatus.UP) { upCount++; } else { downCount++; } if (upCount > 0 && downCount > 0) { return downCount; } } return downCount; }