auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static Properties loadProperties(Class<?> clazz, String resource) throws IOException{ try(Reader is = new InputStreamReader(clazz.getResourceAsStream(resource), "UTF-8")) { Properties prop = new Properties(); prop.load(is); return prop; } catch (IOException e) { throw new IOException( String.format("An error occurred while reading properties file: '%1$s'", resource) START ); END } } the io exception you get should be good enough, no? anyway, please always include the cause exception when rethrowing

Target:
public static Properties loadProperties(Class<?> clazz, String resource) throws IOException { Reader is = new InputStreamReader(clazz.getResourceAsStream(resource), "UTF-8"); Properties prop = new Properties(); prop.load(is); return prop; }
Source:
public boolean parseArguments(List<String> argsList) throws Exception { ParametersParser parser = new ParametersParser( CoreUtil.loadProperties(getClass(), "arguments.properties"), CoreUtil.loadProperties(getClass(), "defaults.properties") ); args = parser.parse(argsList); START return args.containsKey("help"); END } Done

Target:
public void parseArguments(List<String> argsList) throws Exception { args = new ParametersParser( CoreUtil.loadProperties(getClass(), "arguments.properties") ).parse(argsList); }
Source:
public void testEvalPositive() { START Mockito.when(mockNetwork.isExternal()).thenReturn(true); END Assert.assertTrue(underTest.eval(mockNetwork)); } Please add static import

Target:
public void testEvalPositive() { when(mockNetwork.isExternal()).thenReturn(true); assertTrue(underTest.eval(mockNetwork)); }
Source:
START @Override protected void prepareConnectionForEditing(StorageServerConnections connection) END just convention - move the annotation to a separate line

Target:
protected void prepareConnectionForEditing(StorageServerConnections connection)
Source:
public void prepareForEdit(StorageDomain storage) { getOverride().setIsChangable(isEditable(storage)); START super.prepareForEdit(storage); END } can super be called first?

Target:
public void prepareForEdit(StorageDomain storage) { super.prepareForEdit(storage); getOverride().setIsChangable(isEditable(storage)); }
Source:
private VDS getAlternateUpServerInCluster(Guid clusterId, Guid vdsId) { List<VDS> vdsList = getVdsDao().getAllForVdsGroupWithStatus(clusterId, VDSStatus.Up); // If the cluster already having Gluster servers, get an up server START if (vdsList != null && vdsList.size() > 0) { END for (VDS vds : vdsList) { if (!vdsId.equals(vds.getId())) { return vds; } } } return null; } vdsList cannot be null by the contract of the dao for fetching collections. Please replace with if (!vdsList.isEmpty())

Target:
private VDS getAlternateUpServerInCluster(Guid clusterId, Guid vdsId) { List<VDS> vdsList = getVdsDao().getAllForVdsGroupWithStatus(clusterId, VDSStatus.Up); // If the cluster already having Gluster servers, get an up server if (vdsList.isEmpty()) { return null; } for (VDS vds : vdsList) { if (!vdsId.equals(vds.getId())) { return vds; } } return null; }
Source:
public static void updateVmLock(final VM vm) { vm.setLockInfo(getLockManager().getLockInfo(String.format("%s%s", vm.getId(), START LockingGroup.VM))); END } you can use here LockingGroup.VM.name() and not worry of some unexpected LockingGroup.toString() future implementation

Target:
public static void updateVmLock(final VM vm) { vm.setLockInfo(getLockManager().getLockInfo(String.format("%s%s", vm.getId(), LockingGroup.VM.name()))); }
Source:
private String formatVolClusterName(String volClusterName) { if (volClusterName == null) { return null; } String[] names = volClusterName.split("\\|"); //$NON-NLS-1$ START return names.length == 2 ? names[0] + " (" + names[1] + ")" : names[0]; //$NON-NLS-1$ //$NON-NLS-2$ END } I feel this might look something like an alias name so why not pass both cluster and volume names to messages and then get a string like " Volume data from {0} of cluster {1} is replicated to this volume " Just a thought

Target:
private String[] formatVolClusterName(String volClusterName) { if (volClusterName == null) { return null; } String[] names = volClusterName.split("\\|"); //$NON-NLS-1$ return names; }
Source:
private void revealDiskPanel(final AbstractDiskModel disk) { boolean isInVm = disk.getVm() != null; // Disk type (internal/external) selection panel is visible only when // 'Attach disk' mode is enabled or new LunDisk creation is enabled diskTypePanel.setVisible(isNewLunDiskEnabled); externalDiskPanel.setVisible(isNewLunDiskEnabled && disk.getDiskStorageType().getEntity() == DiskStorageType.LUN); START diskErrorPolicyEditor.setVisible(disk.getDiskStorageType().getEntity() != DiskStorageType.LUN); END aliasEditor.setFocus(!isInVm); } the editor is bounded to diskErrorPolicy entity, so it's visibility should be altered through the model. See 'AbstractDiskModel -> diskStorageType_EntityChanged()'.

Target:
private void revealDiskPanel(final AbstractDiskModel disk) { boolean isInVm = disk.getVm() != null; // Disk type (internal/external) selection panel is visible only when // 'Attach disk' mode is enabled or new LunDisk creation is enabled diskTypePanel.setVisible(isNewLunDiskEnabled); externalDiskPanel.setVisible(isNewLunDiskEnabled && disk.getDiskStorageType().getEntity() == DiskStorageType.LUN); aliasEditor.setFocus(!isInVm); }
Source:
public ArrayList<DiskErrorPolicy> getDiskErrorPolicyList() { ArrayList<DiskErrorPolicy> diskErrorPolicy = new ArrayList<>( Arrays.asList(new DiskErrorPolicy[] { DiskErrorPolicy.REPORT, DiskErrorPolicy.ENOSPC, DiskErrorPolicy.STOP, DiskErrorPolicy.IGNORE })); START return diskErrorPolicy; END } I think: return Arrays.asList({DiskErrorPolicy.REPORT, DiskErrorPolicy.ENOSPC, DiskErrorPolicy.STOP, DiskErrorPolicy.IGNORE}); Is more concise and doesn't create as many array lists.

Target:
public List<DiskErrorPolicy> getDiskErrorPolicyList() { return Arrays.asList( DiskErrorPolicy.REPORT, DiskErrorPolicy.ENOSPC, DiskErrorPolicy.STOP, DiskErrorPolicy.IGNORE ); }
Source:
public DropdownActionButton(List<ActionButtonDefinition<T>> actions, List selectedItems) { START super(); END initDropdownButton(); initWidget(WidgetUiBinder.uiBinder.createAndBindUi(this)); initMenuPopup(actions, selectedItems); addMouseHandlers(); } implicit

Target:
public DropdownActionButton(List<ActionButtonDefinition<T>> actions, List selectedItems) { initDropdownButton(); initWidget(WidgetUiBinder.uiBinder.createAndBindUi(this)); initMenuPopup(actions, selectedItems); addMouseHandlers(); }
Source:
public MainTabBasicListItemActionButton(String tooltipText, ImageResource enabledImage, ImageResource disabledImage, String additionalStyle) { START super(); END initWidget(WidgetUiBinder.uiBinder.createAndBindUi(this)); setTooltipText(tooltipText); setEnabledHtml(SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(enabledImage).getHTML())); setDisabledHtml(SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(disabledImage).getHTML())); stylableButtonHolder.addStyleName(additionalStyle); } implicit

Target:
public MainTabBasicListItemActionButton(String tooltipText, ImageResource enabledImage, ImageResource disabledImage, String additionalStyle) { initWidget(WidgetUiBinder.uiBinder.createAndBindUi(this)); setTooltipText(tooltipText); setEnabledHtml(SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(enabledImage).getHTML())); setDisabledHtml(SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(disabledImage).getHTML())); stylableButtonHolder.addStyleName(additionalStyle); }
Source:
public Host getActiveHostByName(String serverName) { START final Host host = VdsmManager.getInstance().getHostByName(serverName); END return host; } What about return VdsmManager.getInstance().getHostByName(serverName); host is not needed.

Target:
public Host getActiveHostByName(String serverName) { return VdsmManager.getInstance().getHostByName(serverName); }
Source:
public START synchronized static END Map<String, String> getTasksMap() { return tasksmap; } why synchronized?

Target:
public static Map<String, String> getTasksMap() { return tasksmap; }
Source:
public START synchronized static END void setTasksMap(String hostName, String taskId) { tasksmap.put(hostName, taskId); } can't you use concurrent hash map instead of the synchronized?

Target:
public static void setTasksMap(String hostName, String taskId) { tasksmap.put(hostName, taskId); }
Source:
public static <E extends VmDevice> Map<String, E> vmDevicesByDevice(Collection<E> deviceList) { if (deviceList != null) { START Map<String, E> map = new HashMap<String, E>(); END for (E device : deviceList) { if (device.getDevice() != null) { map.put(device.getDevice(), device); } } return map; } else { return Collections.emptyMap(); } } Isn't it possible to use empty diamond? Map<String, E> map = new HashMap<>();

Target:
public static <E extends VmDevice> Map<String, E> vmDevicesByDevice(Collection<E> deviceList) { if (deviceList != null) { Map<String, E> map = new HashMap<>(); for (E device : deviceList) { if (device.getDevice() != null) { map.put(device.getDevice(), device); } } return map; } else { return Collections.emptyMap(); } }
Source:
public static boolean isSessionValid(HttpServletRequest req) throws NamingException { String sessionId = (String) req.getSession(true).getAttribute(SessionConstants.SSO_TOKEN_KEY); boolean isValid = false; if (StringUtils.isNotEmpty(sessionId)) { try { SSOQueryServiceUtils.getFromSsoQueryService(req, String.format("command=sso-token-validate&sso_token=%s", sessionId)); START isValid = true; END } catch (Exception e) { log.error("Session not valid session id = " + sessionId, e.getMessage()); } } return isValid; } won't it better to have it as args... ? SSOQueryServiceUtils.getFromSsoQueryService("command=sso-token-validate", String.format("sso_token=%s", sessionId); or even as: SSOQueryServiceUtils.getFromSsoQueryService(req, "command=sso-token-validate&sso_token=%s", sessionId);

Target:
public static boolean isSessionValid(HttpServletRequest req) throws NamingException { String sessionId = (String) req.getSession(true).getAttribute(SessionConstants.SSO_TOKEN_KEY); boolean isValid = false; if (StringUtils.isNotEmpty(sessionId)) { try { SSOQueryServiceUtils.getFromSsoQueryService("command=sso-token-validate&sso_token=%s", sessionId); isValid = true; } catch (Exception e) { log.error("Session not valid session id = " + sessionId, e.getMessage()); } } return isValid; }
Source:
private boolean requiresTagsForField(String obj, String fieldName, boolean useTagsInFrom) { if (!useTagsInFrom) { return false; } Boolean result = requiresFullTable.containsKey(obj + "-" + fieldName); if (result != null && result) { return true; } START return false; END } IMO more readable as : private boolean requiresTagsForField(String obj, String fieldName, boolean useTagsInFrom) { if (useTagsInFrom) { return requiresFullTable.containsKey(obj + "-" + fieldName); } return false; }

Target:
private boolean requiresTagsForField(String obj, String fieldName, boolean useTagsInFrom) { if (useTagsInFrom) { return requiresFullTable.containsKey(obj + "-" + fieldName); } return false; }
Source:
START public <T END extends DAO> T getDao(Class<T> daoType) { for (DAO dao : daos) { if (daoType.isAssignableFrom(dao.getClass())) { initBaseDAO((BaseDAODbFacade) dao); return (T) dao; } } log.error("Can't find dao for " + daoType); return null; } 1. Why the method has to be public? It isn't being used out of the class. 2. Is that guaranteed that at time of this method called the context has all daos in it. If not we should find some CDI equivalent for Spring @DependsOn and use that in order to let CDI know that this bean is dependent on all DAOs.

Target:
protected <T extends DAO> T getDao(Class<T> daoType) { for (DAO dao : daos) { if (daoType.isAssignableFrom(dao.getClass())) { initBaseDAO((BaseDAODbFacade) dao); return (T) dao; } } log.error("Can't find dao for " + daoType); return null; }
Source:
private boolean isMasterDomain(StorageDomain domain) { START return domain.getStorageDomainType() == StorageDomainType.Master && domain.getStatus() != null END && domain.getStatus() == StorageDomainStatus.Active; } if the status is Active, by definition it cannot be null - please remove this redundant check.

Target:
private boolean isMasterDomain(StorageDomain domain) { return domain.getStorageDomainType() == StorageDomainType.Master && domain.getStatus() == StorageDomainStatus.Active; }
Source:
public CellWithElementId<C> getCell() { START return (CellWithElementId<C>) getCell(); END } Shouldn't we return "super.getCell()" here?

Target:
public CellWithElementId<C> getCell() { return (CellWithElementId<C>) super.getCell(); }
Source:
public FenceOperationResult getFenceAgentStatus(FenceAgent fenceAgent) { if (fenceAgent == null) { return new FenceOperationResult( Status.ERROR, PowerStatus.UNKNOWN, "Invalid fence agent specified."); } START List<FenceAgent> fenceAgents = new ArrayList<>(); END fenceAgents.add(fenceAgent); return fence(FenceActionType.STATUS, fenceAgents); } why not instead of 3 lines just one? return fence(FenceActionType.STATUS, Arrays.asList(fenceAgent) ) ?

Target:
public FenceOperationResult getFenceAgentStatus(FenceAgent fenceAgent) { if (fenceAgent == null) { return new FenceOperationResult( Status.ERROR, PowerStatus.UNKNOWN, "Invalid fence agent specified."); } return fence(FenceActionType.STATUS, Arrays.asList(fenceAgent)); }
Source:
public void onFailed(Guid cmdId, List<Guid> childCmdIds) { super.onFailed(cmdId, childCmdIds); START getCommand().unlockImageInDb(); END log.error("Failed extending disk. ID: {}", getDiskId()); updateAuditLog(AuditLogType.USER_EXTEND_DISK_SIZE_FAILURE, getCommand().getNewDiskSizeInGB()); getCommand().endAction(); CommandCoordinatorUtil.removeAllCommandsInHierarchy(cmdId); } Why calling this unlock, it should already been done in getCommand().endAction();

Target:
public void onFailed(Guid cmdId, List<Guid> childCmdIds) { super.onFailed(cmdId, childCmdIds); log.error("Failed extending disk. ID: {}", getDiskId()); updateAuditLog(AuditLogType.USER_EXTEND_DISK_SIZE_FAILURE, getCommand().getNewDiskSizeInGB()); getCommand().endAction(); CommandCoordinatorUtil.removeAllCommandsInHierarchy(cmdId); }
Source:
protected VDSReturnValue getStatsForDomain() { VDS spmVds = START LinqUtils.first(getAllRunningVdssInPool()); END return runVdsCommand(VDSCommandType.GetStorageDomainStats, new GetStorageDomainStatsVDSCommandParameters(spmVds.getId(), getParameters().getStorageDomainId())); } please rename - this host isn't neccessarily the spm.

Target:
protected VDSReturnValue getStatsForDomain() { VDS vds = LinqUtils.first(getAllRunningVdssInPool()); return runVdsCommand(VDSCommandType.GetStorageDomainStats, new GetStorageDomainStatsVDSCommandParameters(vds.getId(), getParameters().getStorageDomainId())); }
Source:
private boolean checkLunsInStorageDomain(List<String> lunIds, StorageDomain storageDomain) { // Get LUNs from DB List<LUNs> lunsFromDb = getLunDao().getAllForVolumeGroup(getStorageDomain().getStorage()); START List<String> lunsList = new ArrayList<>(lunIds); END for (LUNs lun : lunsFromDb) { if (lunsList.contains(lun.getLUN_id())) { // LUN is part of the storage domain lunsList.remove(lun.getLUN_id()); } } return lunsList.isEmpty(); } You don't care about the order, and you're doing several remove operations - better use a HashSet

Target:
private boolean checkLunsInStorageDomain(List<String> lunIds, StorageDomain storageDomain) { // Get LUNs from DB List<LUNs> lunsFromDb = getLunDao().getAllForVolumeGroup(getStorageDomain().getStorage()); Set<String> lunsList = new HashSet<>(lunIds); for (LUNs lun : lunsFromDb) { if (lunsList.contains(lun.getLUN_id())) { // LUN is part of the storage domain lunsList.remove(lun.getLUN_id()); } } return lunsList.isEmpty(); }
Source:
protected VDSReturnValue getStatsForDomain() { VDS spmVds = LinqUtils.first(LinqUtils.filter(getAllRunningVdssInPool(), new Predicate<VDS>() { @Override public boolean eval(VDS vds) { return vds.getSpmStatus() == VdsSpmStatus.SPM; } })); return runVdsCommand(VDSCommandType.GetStorageDomainStats, START new GetStorageDomainStatsVDSCommandParameters(spmVds.getId(), getParameters().getStorageDomainId())); END } In 3.6.0 we will not have an SPM. In this case, just take the first host.

Target:
protected VDSReturnValue getStatsForDomain() { VDS spmVds = LinqUtils.first(getAllRunningVdssInPool()); return runVdsCommand(VDSCommandType.GetStorageDomainStats, new GetStorageDomainStatsVDSCommandParameters(spmVds.getId(), getParameters().getStorageDomainId())); }
Source:
private Long resizePV(String lunId) { try { return (Long) runVdsCommand( VDSCommandType.ResizeStorageDomainPV, new ResizeStorageDomainPVVDSCommandParameters(getStoragePoolId(), getStorageDomainId(), lunId)).getReturnValue(); } catch (VdcBLLException e) { START log.error("Failed to resize PV " + lunId, e); END throw e; } } the log doesn't add info to the log, that's unneeded, it's clear from the log that ResizeStorageDomainPV failed

Target:
private Long resizePV(String lunId) { return (Long) runVdsCommand( VDSCommandType.ResizeStorageDomainPV, new ResizeStorageDomainPVVDSCommandParameters(getStoragePoolId(), getStorageDomainId(), lunId)).getReturnValue(); }
Source:
protected void updateVmDeviceAddress(final String address, final VmDevice vmDevice) { vmDevice.setAddress(address); getCompensationContext().snapshotEntity(vmDevice); vmDeviceDao.update(vmDevice); START getCompensationContext().stateChanged(); END } thanks, please replace the order,- stateChanged() should be before the vmDevice update call. otherwise if there's a failure between the calls the changes won't be reverted.

Target:
protected void updateVmDeviceAddress(final String address, final VmDevice vmDevice) { vmDevice.setAddress(address); getCompensationContext().snapshotEntity(vmDevice); getCompensationContext().stateChanged(); vmDeviceDao.update(vmDevice); }
Source:
protected ToStringBuilder appendAttributes(ToStringBuilder tsb) { return super.appendAttributes(tsb) .append("diskId", disk.getId()) START .append("addressMap", addressMap.toString()); END } you should use TostringBuilder.append(final String name, final Map<K, V> value) please replace with .append("addressMap", addressMap);

Target:
protected ToStringBuilder appendAttributes(ToStringBuilder tsb) { return super.appendAttributes(tsb) .append("diskId", disk.getId()) .append("addressMap", addressMap); }
Source:
START protected void setActionMessageParameters() { END addCanDoActionMessage(VdcBllMessages.VAR__ACTION__ADD); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__USER_PROFILE); addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_PROFILE_ALREADY_EXISTS); } this method should only contain the parameters for the generic messages, means var-action-x and var-type-y and it is called automatically inside commandBase, so no need to call it again the specific failure messages should be added inside the canDoAction so in the canDoAction you should only have: if (somethingIsWrong) { result = failCanDoAction(msg); } (just a note - usually we use 'quick-return' in canDoActions, means once you found an issue, return. so it makes the method more readable (no need ti check the value of 'result' or complicated if-else, but here its not a must since its a short one)

Target:
protected void setActionMessageParameters() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__ADD); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__USER_PROFILE); }
Source:
public void testDeleteBackupRelatedAlerts() { START AuditLog entry = dao.getByOriginAndCustomEventId(ORIGIN, CUSTOM_BAKUP_EVENT_ID); END assertFalse(entry.isDeleted()); dao.deleteBackupRelatedAlerts(); entry = dao.getByOriginAndCustomEventId(ORIGIN, CUSTOM_BAKUP_EVENT_ID); assertTrue(entry.isDeleted()); } i'd add first assertNotNull(entry); which is a proper assumption prior to validating the entry data.

Target:
public void testDeleteBackupRelatedAlerts() { AuditLog entry = dao.getByOriginAndCustomEventId(ORIGIN, CUSTOM_BAKUP_EVENT_ID); assertNotNull(entry); assertFalse(entry.isDeleted()); dao.deleteBackupRelatedAlerts(); entry = dao.getByOriginAndCustomEventId(ORIGIN, CUSTOM_BAKUP_EVENT_ID); assertNotNull(entry); assertTrue(entry.isDeleted()); }
Source:
START @Override public void clearAllEvents() { END getCallsHandler().executeModification("ClearAllAuditLogs", getCustomMapSqlParameterSource()); } I am pretty sure the convention is to have the @Override above the method declaration for all of these.

Target:
public void clearAllEvents() { getCallsHandler().executeModification("ClearAllAuditLogs", getCustomMapSqlParameterSource()); }
Source:
public ExceptionAwareTransactionMethod(InvocationContext context) { START super(); END this.context = context; } not needed

Target:
public ExceptionAwareTransactionMethod(InvocationContext context) { this.context = context; }
Source:
protected BackendQuotaLimitsResource(Guid quotaId, Class<N> baseResourcesClass) { START super(baseResourcesClass, Quota.class, SUB_COLLECTIONS); END this.quotaId = quotaId; } The constructor will work without SUB_COLLECTIONS

Target:
protected BackendQuotaLimitsResource(Guid quotaId, Class<N> baseResourcesClass) { super(baseResourcesClass, Quota.class); this.quotaId = quotaId; }
Source:
protected Response performRemove(String id) { QuotaCRUDParameters prms = new QuotaCRUDParameters(); START prms.setQuotaId(GuidUtils.asGuid(id)); END return performAction(VdcActionType.RemoveQuota, prms); } No need for GuidUtils, there's a asGuid(String guid) method in ancestor class.

Target:
protected Response performRemove(String id) { QuotaCRUDParameters prms = new QuotaCRUDParameters(); prms.setQuotaId(asGuid(id)); return performAction(VdcActionType.RemoveQuota, prms); }
Source:
public void setDisableCliSchedule(EntityModel<Boolean> value) { this.disableCliSchedule = value; START this.disableCliSchedule.setIsAvailable(value.getEntity()); END } when would this be of use except for in init which is always false. I mean in line 442 of GlusterVolumeSnapshotListModel you are doing snapshotModel#getDisableCliSchedule#setEntity but that doesn't come here right?

Target:
public void setDisableCliSchedule(EntityModel<Boolean> value) { this.disableCliSchedule = value; }
Source:
public Map<String, String> getCustomValues() { START addCustomValue("ClusterName", getVdsGroupName()); END return super.getCustomValues(); } why not just use vdsGroupName in the message, then the custom value is not required

Target:
public Map<String, String> getCustomValues() { return super.getCustomValues(); }
Source:
START public void cancel() END This doesn't need to be public, it can be protected

Target:
protected void cancel()
Source:
START @Override public END EngineBackupLogId getId() { EngineBackupLogId key = new EngineBackupLogId(); key.setDbName(dbName); key.setDoneAt(doneAt); return key; } Could please put @Override on a separate line?

Target:
public EngineBackupLogId getId() { EngineBackupLogId key = new EngineBackupLogId(); key.setDbName(dbName); key.setDoneAt(doneAt); return key; }
Source:
START @Override public END void setId(EngineBackupLogId id) { dbName = id.getDbName(); doneAt = id.getDoneAt(); } Could please put @Override on a separate line?

Target:
public void setId(EngineBackupLogId id) { dbName = id.getDbName(); doneAt = id.getDoneAt(); }
Source:
public EngineBackupLog getLastSuccessfulEngineBackup(String dbName) { List<EngineBackupLog> logs = multipleResults(entityManager.createNamedQuery("EngineBackupLog.getLatest", EngineBackupLog.class).setParameter("dbName", dbName)); START if (logs != null && logs.size() > 0) { END return logs.get(0); } else { return null; } } there is an assumption that logs cannot be null, so you can replace the entire if with: if (logs.isEmpty()) { return null; } else { return logs.get(0); }

Target:
public EngineBackupLog getLastSuccessfulEngineBackup(String dbName) { List<EngineBackupLog> logs = multipleResults(entityManager.createNamedQuery("EngineBackupLog.getLatest", EngineBackupLog.class).setParameter("dbName", dbName)); if (logs.isEmpty()) { return null; } else { return logs.get(0); } }
Source:
protected void getDowntime() { START if (getVm() != null && getVm().getStatus() == VMStatus.Up) { END try { VDSReturnValue retVal = runVdsCommand(VDSCommandType.MigrateStatus, new MigrateStatusVDSCommandParameters(getDestinationVdsId(), getVmId())); if (retVal != null) { actualDowntime = (Integer) retVal.getReturnValue(); } } catch (VdcBLLException e) { migrationErrorCode = e.getErrorCode(); } } } 1. I don't think it is needed to check the VM is not null - it is locked, no one can remove it 2. why is it important that the status is up? what if it is powering-up?

Target:
protected void getDowntime() { try { VDSReturnValue retVal = runVdsCommand(VDSCommandType.MigrateStatus, new MigrateStatusVDSCommandParameters(getDestinationVdsId(), getVmId())); if (retVal != null) { actualDowntime = (Integer) retVal.getReturnValue(); } } catch (VdcBLLException e) { migrationErrorCode = e.getErrorCode(); } }
Source:
protected void executeImport(ImportVmFromExportDomainModel importVmModel) { importVmModel.importVms( new IFrontendMultipleActionAsyncCallback() { @Override public void executed(FrontendMultipleActionAsyncResult result) { START VmListModel.this.setWindow(null); END } }, cloneObjectMap); } you can probably just call `setWindow(null)` whithout the explicit reference to outer this.

Target:
protected void executeImport(ImportVmFromExportDomainModel importVmModel) { importVmModel.importVms( new IFrontendMultipleActionAsyncCallback() { @Override public void executed(FrontendMultipleActionAsyncResult result) { setWindow(null); } }, cloneObjectMap); }
Source:
VM createDbVm() { VM vm = new VM(); vm.setDynamicData(new VmDynamic()); vm.setId(id); vm.setName(name()); vm.setRunOnVds(SRC_HOST_ID); START vm.setElapsedTime(-1.0d); END return vm; } I don't see any change that is related to elapsed-time, why is this change needed?

Target:
VM createDbVm() { VM vm = new VM(); vm.setDynamicData(new VmDynamic()); vm.setId(id); vm.setName(name()); vm.setRunOnVds(SRC_HOST_ID); return vm; }
Source:
public void SetVmUnknown(VM vm) { RemoveAsyncRunningVm(vm.getId()); START InternalSetVmStatus(vm, VMStatus.Unknown, vm.getStatusUpdatedTime()); END // log VM transition to unknown status AuditLogableBase logable = new AuditLogableBase(); logable.setVmId(vm.getId()); auditLogDirector.log(logable, AuditLogType.VM_SET_TO_UNKNOWN_STATUS); storeVm(vm); } not needed (the value is null and won't be used anyway)

Target:
public void SetVmUnknown(VM vm) { RemoveAsyncRunningVm(vm.getId()); InternalSetVmStatus(vm, VMStatus.Unknown); // log VM transition to unknown status AuditLogableBase logable = new AuditLogableBase(); logable.setVmId(vm.getId()); auditLogDirector.log(logable, AuditLogType.VM_SET_TO_UNKNOWN_STATUS); storeVm(vm); }
Source:
protected void setActionMessageParameters() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__CREATE); addCustomValue(GlusterConstants.VOLUME_SNAPSHOT_NAME, getParameters().getSnapshot().getSnapshotName()); START addCustomValue("ClusterName", END getVdsGroupName()); } use vdsGroupName parameter, the custom variable not required

Target:
protected void setActionMessageParameters() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__CREATE); addCustomValue(GlusterConstants.VOLUME_SNAPSHOT_NAME, getParameters().getSnapshot().getSnapshotName()); }
Source:
public void testThatFilterDoesntRemoveStorageDomainFromList() { List<StorageDomain> filteredDomains = filterStorageDomain(false); START assertEquals(filteredDomains, Arrays.asList(storageDomain)); END } This assumes both collections are the same type. To be on the safe side, you should surround both with your own collection (e.g., new ArrayList<>)

Target:
public void testThatFilterDoesntRemoveStorageDomainFromList() { List<StorageDomain> filteredDomains = new ArrayList<>(filterStorageDomain(false)); assertEquals(filteredDomains, Arrays.asList(storageDomain)); }
Source:
private List<VmTemplate> filterOutBlank(List<VmTemplate> templates) { START final ArrayList<VmTemplate> result = new ArrayList<>(); END for (VmTemplate template : templates) { if (!template.isBlank()) { result.add(template); } } return result; } List<VmTemplate>...

Target:
private List<VmTemplate> filterOutBlank(List<VmTemplate> templates) { final List<VmTemplate> result = new ArrayList<>(); for (VmTemplate template : templates) { if (!template.isBlank()) { result.add(template); } } return result; }
Source:
private SchedulingManager mockScheduler() { SchedulingManager mock = Mockito.mock(SchedulingManager.class); START Mockito.when(mock.getClusterPolicies()).thenReturn(Collections.<ClusterPolicy>emptyList()); END return mock; } please use static import for Mockito

Target:
private SchedulingManager mockScheduler() { SchedulingManager mock = mock(SchedulingManager.class); when(mock.getClusterPolicies()).thenReturn(Collections.<ClusterPolicy>emptyList()); return mock; }
Source:
public VDS getValue(S object) { if (object instanceof VDS){ return (VDS) object; } START if (object instanceof PairQueryable){ END if (((PairQueryable<?, ?>) object).getSecond() instanceof VDS) { return (VDS) ((PairQueryable<?, ?>) object).getSecond(); } } return null; } Why do you need this? Are you planning to add the column to SubTabNetworkHostView?

Target:
public VDS getValue(S object) { if (object instanceof VDS){ return (VDS) object; } return null; }
Source:
START public EventQueue getEventQueue() { END return eventQueue; } you can change that to be protected

Target:
protected EventQueue getEventQueue() { return eventQueue; }
Source:
public static SubjectEntity[] getStorageEntities(List<CinderDisk> cinderDisks) { Set<SubjectEntity> storageSubjects = new HashSet<>(); for START (final CinderDisk END cinderDisk : cinderDisks) { SubjectEntity se = new SubjectEntity(VdcObjectType.Storage, cinderDisk.getStorageIds().get(0)); storageSubjects.add(se); } return storageSubjects.toArray(new SubjectEntity[storageSubjects.size()]); } no need for final...

Target:
public static SubjectEntity[] getStorageEntities(List<CinderDisk> cinderDisks) { Set<SubjectEntity> storageSubjects = new HashSet<>(); for (CinderDisk cinderDisk : cinderDisks) { SubjectEntity se = new SubjectEntity(VdcObjectType.Storage, cinderDisk.getStorageIds().get(0)); storageSubjects.add(se); } return storageSubjects.toArray(new SubjectEntity[storageSubjects.size()]); }
Source:
START public Integer getWarningLowSpaceSize() { END return getWarningLowSpaceIndicator() == null ? 0 : getTotalDiskSize() * getWarningLowSpaceIndicator() / 100; } Given the problems we've had with other properties of StorageDomain with converstion of Integer to int and the NPEs resulting I think it's best that the return type will be int as we never return null either way, please fix and I'll merge

Target:
public int getWarningLowSpaceSize() { return getWarningLowSpaceIndicator() == null ? 0 : getTotalDiskSize() * getWarningLowSpaceIndicator() / 100; }
Source:
private void showCheckBoxes(List<T> seletedItems) { for (Entry<T, CheckBox> currentEntry : checkBoxes.entrySet()) { wrapperPanel.add(currentEntry.getValue()); if (seletedItems.contains(currentEntry.getKey())) { START currentEntry.getValue().setValue(true, false); END } } } you could simply do currentEntry.getValue().setValue(true)

Target:
private void showCheckBoxes(List<T> seletedItems) { for (Entry<T, CheckBox> currentEntry : checkBoxes.entrySet()) { wrapperPanel.add(currentEntry.getValue()); if (seletedItems.contains(currentEntry.getKey())) { currentEntry.getValue().setValue(true); } } }
Source:
START private ExternalStatus(int value) { END intValue = value; } s/value/id

Target:
private ExternalStatus(int value) { id = value; }
Source:
START public int getValue() { END return intValue; } s/getValue/getId

Target:
public int getValue() { return id; }
Source:
public void testUpdateExternalStatus() { VdsDynamic before = dao.get(existingVds.getId()); before.setExternalStatus(ExternalStatus.Error); dao.updateExternalStatus(before.getId(), before.getExternalStatus()); VdsDynamic after = dao.get(existingVds.getId()); START assertEquals(before, after); END } please compare the externalStatus fields explicitly.

Target:
public void testUpdateExternalStatus() { VdsDynamic before = dao.get(existingVds.getId()); before.setExternalStatus(ExternalStatus.Error); dao.updateExternalStatus(before.getId(), before.getExternalStatus()); VdsDynamic after = dao.get(existingVds.getId()); assertEquals(before.getExternalStatus(), after.getExternalStatus()); }
Source:
public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = getPermissionList(getParameters().getEvent()); // check for external host status modification if (hasHostExternalStatus()) { START permissionList.add(new PermissionSubject(new Guid(getParameters().getEvent().getVdsId().toString()), END VdcObjectType.VDS, ActionGroup.EDIT_HOST_CONFIGURATION)); } return permissionList; } this part: new Guid(getParameters().getEvent().getVdsId().toString()) should be replaced with: getParameters().getEvent().getVdsId()

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = getPermissionList(getParameters().getEvent()); // check for external host status modification if (hasHostExternalStatus()) { permissionList.add(new PermissionSubject(getParameters().getEvent().getVdsId(), VdcObjectType.VDS, ActionGroup.EDIT_HOST_CONFIGURATION)); } return permissionList; }
Source:
START protected Object getEntityObject(S object) { END return null; } the return type should be S, then you can avoid casting when this method is called.

Target:
protected S getEntityObject(S object) { return null; }
Source:
public List<RepoImage> getUserRequestForStorageDomainRepoFileList(Guid storageDomainId, ImageFileType imageType, boolean forceRefresh) { // The result list we send back. START List<RepoImage> repoList; END if (!isStorageDomainValid(storageDomainId, imageType, forceRefresh)) { throw new VdcBLLException(VdcBllErrors.GetIsoListError); } // At any case, if refreshed or not, get Iso list from the cache. repoList = getCachedIsoListByDomainId(storageDomainId, imageType); // Return list of repository files. return repoList; } no need for this variable, we can just return the returned value from the call to getCachedIsoListByDomainId

Target:
public List<RepoImage> getUserRequestForStorageDomainRepoFileList(Guid storageDomainId, ImageFileType imageType, boolean forceRefresh) { if (!isStorageDomainValid(storageDomainId, imageType, forceRefresh)) { throw new VdcBLLException(VdcBllErrors.GetIsoListError); } // At any case, if refreshed or not, get Iso list from the cache. return getCachedIsoListByDomainId(storageDomainId, imageType); }
Source:
protected void endWithFailure() { START setSucceeded(true); END } * shuoldn't we call super? * worth adding some log..

Target:
protected void endWithFailure() { super.endWithFailure(); }
Source:
START public void updateVmDataChangedTime() { END vmDataChangedTime = System.nanoTime(); } I would mark it as final. It is not safe to use non-final methods in ctor. Someone could override it and do something foolish.

Target:
public final void updateVmDataChangedTime() { vmDataChangedTime = System.nanoTime(); }
Source:
public void fetch() { START fetchTime = Calendar.getInstance().getTime(); END VDSReturnValue getList = getResourceManager().runVdsCommand( VDSCommandType.List, new VdsIdAndVdsVDSCommandParametersBase(vdsManager.getCopyVds())); if (getList.getSucceeded()) { vdsmVms = (Map<Guid, VmInternalData>) getList.getReturnValue(); onFetchVms(); } else { onError(); } } since we are going to compute this time-stamp a lot, perhaps we should use the more efficient way of System.currentTimeMillis(). See: http://stackoverflow.com/questions/368094/system-currenttimemillis-vs-new-date-vs-calendar-getinstance-gettime

Target:
public void fetch() { VDSReturnValue getList = getResourceManager().runVdsCommand( VDSCommandType.List, new VdsIdAndVdsVDSCommandParametersBase(vdsManager.getCopyVds())); if (getList.getSucceeded()) { vdsmVms = (Map<Guid, VmInternalData>) getList.getReturnValue(); onFetchVms(); } else { onError(); } }
Source:
protected void executeCommand() { Guid secretUuid = getParameters().getLibvirtSecret().getId(); START addCustomValue("LibvirtSecretUUID", secretUuid.toString()); END getReturnValue().setActionReturnValue(secretUuid); } add method : public String getLibvirtSeverUUID() for audit log purposes

Target:
protected void executeCommand() { getReturnValue().setActionReturnValue(getParameters().getLibvirtSecret().getId()); }
Source:
private void printGroupRecord(ExtMap extMap) { if (extMap != null) { do { logger.info( "GroupRecord: ID '{}', name: '{}', namespace: '{}', display name: '{}'", extMap.get(Authz.GroupRecord.ID, ""), extMap.get(Authz.GroupRecord.NAME, ""), extMap.get(Authz.GroupRecord.NAMESPACE, ""), extMap.get(Authz.GroupRecord.DISPLAY_NAME, "") ); START } while((extMap = extMap.get(Authz.GroupRecord.GROUPS)) != null); END } } this should be recursive.

Target:
private void printGroupRecord(ExtMap extMap) { if (extMap != null) { log.info( "GroupRecord: ID '{}', name: '{}', namespace: '{}', display name: '{}'", extMap.get(Authz.GroupRecord.ID, ""), extMap.get(Authz.GroupRecord.NAME, ""), extMap.get(Authz.GroupRecord.NAMESPACE, ""), extMap.get(Authz.GroupRecord.DISPLAY_NAME, "") ); } }
Source:
public VmReplicateDiskParameters(Guid vdsId, Guid vmId, Guid storagePoolId, Guid srcStorageDomainId, Guid targetStorageDomainId, Guid imageGroupId, Guid imageId, String diskType) { super(vdsId, vmId); this.storagePoolId = storagePoolId; this.srcStorageDomainId = srcStorageDomainId; this.targetStorageDomainId = targetStorageDomainId; this.imageGroupId = imageGroupId; this.imageId = imageId; START this.diskType = Optional.ofNullable(diskType); END } It seems cleaner to me to just store the string here and keep this a simple-stupid POJO, and have the optional "logic" where it's used.

Target:
public VmReplicateDiskParameters(Guid vdsId, Guid vmId, Guid storagePoolId, Guid srcStorageDomainId, Guid targetStorageDomainId, Guid imageGroupId, Guid imageId, String diskType) { super(vdsId, vmId); this.storagePoolId = storagePoolId; this.srcStorageDomainId = srcStorageDomainId; this.targetStorageDomainId = targetStorageDomainId; this.imageGroupId = imageGroupId; this.imageId = imageId; }
Source:
public Map<String, Object> prepareGlusterDisk(VM vm, DiskImage diskImage, Map<String, Object> struct) { START this.getNetworkDiskType(vm, END diskImage).ifPresent((diskType) -> struct.put(VdsProperties.DiskType, diskType)); return struct; } As per the project's conventions, I'd drop the "this" here.

Target:
public Map<String, Object> prepareGlusterDisk(VM vm, DiskImage diskImage, Map<String, Object> struct) { getNetworkDiskType(vm, diskImage).ifPresent((diskType) -> struct.put(VdsProperties.DiskType, diskType)); return struct; }
Source:
private void initVisibilities() { errorMsg.setVisible(false); START actionConfirmationMessage.setVisible(false); END geoRepForceHelpIcon.setVisible(false); } Why this needs to be hidden?

Target:
private void initVisibilities() { errorMsg.setVisible(false); geoRepForceHelpIcon.setVisible(false); }
Source:
private Integer getWarningLowSpaceSize(StorageModel storageModel) { START if (!storageModel.isNewStorage()) { END Integer percentageValue = warningLowSpaceIndicatorEditor.asValueBox().getValue(); return percentageValue == null ? 0 : storageModel.getStorage().getTotalDiskSize() * percentageValue / 100; } return 0; // This is mot visible, hence meaningless. } This null check should be done in line 274

Target:
private Integer getWarningLowSpaceSize(StorageModel storageModel) { Integer percentageValue = warningLowSpaceIndicatorEditor.asValueBox().getValue(); return percentageValue == null ? 0 : storageModel.getStorage().getTotalDiskSize() * percentageValue / 100; }
Source:
protected BackendOpenStackVolumeAuthenticationKeyResource(String providerId, String id) { super(id, OpenstackVolumeAuthenticationKey.class, LibvirtSecret.class); this.providerId = providerId; START this.guid = asGuidOr404(id); END } I think that this assignment to "guid" already happens in the base class? Doesn't it?

Target:
protected BackendOpenStackVolumeAuthenticationKeyResource(String providerId, String id) { super(id, OpenstackVolumeAuthenticationKey.class, LibvirtSecret.class); this.providerId = providerId; }
Source:
private void updateActionAvailability() { ArrayList<LibvirtSecretModel> secrets = getSelectedItems() != null ? Linq.<LibvirtSecretModel> cast(getSelectedItems()) : new ArrayList<LibvirtSecretModel>(); START getEditCommand().setIsExecutionAllowed(secrets.size() > 0); END getRemoveCommand().setIsExecutionAllowed(secrets.size() > 0); } Should it be equals to 1? Or editing of multiple secrets is allowed?

Target:
private void updateActionAvailability() { ArrayList<LibvirtSecretModel> secrets = getSelectedItems() != null ? Linq.<LibvirtSecretModel> cast(getSelectedItems()) : new ArrayList<LibvirtSecretModel>(); getEditCommand().setIsExecutionAllowed(secrets.size() == 1); getRemoveCommand().setIsExecutionAllowed(secrets.size() > 0); }
Source:
public void testGetGlusterGeoRepSessionUnSetConfig() { GlusterGeoRepSessionConfiguration sessionConfig = getGlusterGeoRepSessionConfig(); dao.saveConfig(sessionConfig); List<GlusterGeoRepSessionConfiguration> unsetSessionConfig = dao.getGlusterGeoRepSessionUnSetConfig(FixturesTool.GLUSTER_GEOREP_SESSION_ID); START assertEquals(1, unsetSessionConfig.size()); END assertEquals("use_meta_volume", unsetSessionConfig.get(0).getKey()); } would this be 1, or would need to be changed whenever a new master config is added?

Target:
public void testGetGlusterGeoRepSessionUnSetConfig() { GlusterGeoRepSessionConfiguration sessionConfig = getGlusterGeoRepSessionConfig(); dao.saveConfig(sessionConfig); List<GlusterGeoRepSessionConfiguration> unsetSessionConfig = dao.getGlusterGeoRepSessionUnSetConfig(FixturesTool.GLUSTER_GEOREP_SESSION_ID); assertEquals("use_meta_volume", unsetSessionConfig.get(0).getKey()); }
Source:
protected StorageDomain getEntityObject(StorageDomain object) { if (object instanceof START StorageDomain){ END return object; } else { return null; } } won't it always return true if not null? if so, why not just return "object"? See similar findbugs issue for the host patch.

Target:
protected StorageDomain getEntityObject(StorageDomain object) { return object; }
Source:
void scheduleKeepAliveHeartbeat() { Scheduler.get().scheduleFixedDelay(new RepeatingCommand() { @Override public boolean execute() { boolean sessionInUse = restApiSessionId != null; if (sessionInUse && refreshRestApiSession) { // The browser takes care of sending JSESSIONID cookie for this request automatically START sendRequest(createRequest(engineAuthToken), new RestApiRequestCallback()); END // Reset the refresh flag refreshRestApiSession = false; } // Proceed with the heartbeat only when the session is still in use return sessionInUse; } }, SESSION_HEARTBEAT_MS); } this is followup of above, it should not be required.

Target:
void scheduleKeepAliveHeartbeat() { Scheduler.get().scheduleFixedDelay(new RepeatingCommand() { @Override public boolean execute() { boolean sessionInUse = restApiSessionId != null; if (sessionInUse && refreshRestApiSession) { // The browser takes care of sending JSESSIONID cookie for this request automatically sendRequest(createRequest(), new RestApiRequestCallback()); // Reset the refresh flag refreshRestApiSession = false; } // Proceed with the heartbeat only when the session is still in use return sessionInUse; } }, SESSION_HEARTBEAT_MS); }
Source:
public ConnectHostToStoragePoolServerCommandBase() { START super(); END } super() can be spared here.

Target:
public ConnectHostToStoragePoolServerCommandBase() { }
Source:
public ValidationResult provisioningComputeResourceValid(boolean provisioned, ExternalComputeResource computeResource) { return ValidationResult.failWith(VdcBllMessages.VDS_PROVIDER_PROVISION_MISSING_COMPUTERESOURCE) .when(provisioned == true && computeResource == null); START } END no need to compare against 'true'. just: .when(provisioned && computeResource == null);

Target:
public ValidationResult provisioningComputeResourceValid(boolean provisioned, ExternalComputeResource computeResource) { return ValidationResult.failWith(VdcBllMessages.VDS_PROVIDER_PROVISION_MISSING_COMPUTERESOURCE) .when(provisioned && computeResource == null); }
Source:
private void updateVmStatistics() { // check if time for vm statistics refresh - update cache and DB START if (getVdsManager().isTimeToRefreshStatistics()) { END dbVm.updateRunTimeStatisticsData(vdsmVm.getVmStatistics(), dbVm); saveStatistics(); saveVmInterfaces(); updateInterfaceStatistics(); updateVmNumaNodeRuntimeInfo(); for (DiskImageDynamic diskImageDynamic : vdsmVm.getVmDynamic().getDisks()) { vmsMonitoring.addDiskImageDynamicToSave(new Pair<>(dbVm.getId(), diskImageDynamic)); } } } shouldnt this use the vmRefresher.timeToRefresh() ?

Target:
protected void updateVmStatistics() { // check if time for vm statistics refresh - update cache and DB if (vdsmVm.getVmStatistics() != null) { dbVm.updateRunTimeStatisticsData(vdsmVm.getVmStatistics(), dbVm); saveStatistics(); saveVmInterfaces(); updateInterfaceStatistics(); updateVmNumaNodeRuntimeInfo(); for (DiskImageDynamic diskImageDynamic : vdsmVm.getVmDynamic().getDisks()) { vmsMonitoring.addDiskImageDynamicToSave(new Pair<>(dbVm.getId(), diskImageDynamic)); } } }
Source:
private boolean isLibrbdAvailable() { if (!CINDERStorageHelper.isLibrbdAvailable(getVds())) { log.error("Couldn't found librbd1 package on vds (needed for Cinder storage domains).", getVds().getName()); START setNonOperational(NonOperationalReason.LIBRBD_PACKAGE_NOT_AVAILABLE, getVds()); END return false; } return true; } You need to migrate all the VMs when Host becomes non operational. What about Gluster? probably worth to call here: runInternalAction(VdcActionType.SetNonOperationalVds)

Target:
private boolean isLibrbdAvailable() { if (!CINDERStorageHelper.isLibrbdAvailable(getVds())) { log.error("Couldn't found librbd1 package on vds (needed for Cinder storage domains).", getVds().getName()); setNonOperational(NonOperationalReason.LIBRBD_PACKAGE_NOT_AVAILABLE); return false; } return true; }
Source:
private void removeVmStatelessImages() { if (getSnapshotDao().exists(getVmId(), SnapshotType.STATELESS) START && !VmPoolType.Manual.equals(getVmPoolType())) { END log.info("Deleting snapshot for stateless vm '{}'", getVmId()); runInternalAction(VdcActionType.RestoreStatelessVm, new VmOperationParameterBase(getVmId()), ExecutionHandler.createDefaultContextForTasks(getContext(), getLock())); } } same, it is more standard to compare enums using == or != than with 'equals' - although it behaves the same

Target:
private void removeVmStatelessImages() { if (getSnapshotDao().exists(getVmId(), SnapshotType.STATELESS) && getVmPoolType() != VmPoolType.Manual) { log.info("Deleting snapshot for stateless vm '{}'", getVmId()); runInternalAction(VdcActionType.RestoreStatelessVm, new VmOperationParameterBase(getVmId()), ExecutionHandler.createDefaultContextForTasks(getContext(), getLock())); } }
Source:
int determineRealLabelWidth(FormItem item, Integer labelWidth) { List<Integer> sizesList = formSizeMap.get(item); int valueWidth; if (labelWidth != null) { sizesList.set(1, labelWidth); START valueWidth = labelWidth; END } else { valueWidth = sizesList.get(1); } return valueWidth; } Alternatively, this could be a bit shorter: if (labelWidth != null) { sizesList.set(1, labelWidth); } valueWidth = sizesList.get(1);

Target:
int determineRealLabelWidth(FormItem item, Integer labelWidth) { List<Integer> sizesList = formSizeMap.get(item); if (labelWidth != null) { sizesList.set(1, labelWidth); } return sizesList.get(1); }
Source:
private static ImageResource getPoolVmImageResource(VmType vmType, boolean nextRunConfigurationExists) { switch (vmType) { case Desktop: return nextRunConfigurationExists ? resources.manyDesktopsChangesImage() : resources.manyDesktopsImage(); case Server: return nextRunConfigurationExists ? resources.manyServersChangesImage() : resources.manyServersImage(); default: START log.severe("Invalid VmType."); END return null; } } Please add NON-NLS :-)

Target:
private static ImageResource getPoolVmImageResource(VmType vmType, boolean nextRunConfigurationExists) { switch (vmType) { case Server: return nextRunConfigurationExists ? resources.manyServersChangesImage() : resources.manyServersImage(); case Desktop: default: return nextRunConfigurationExists ? resources.manyDesktopsChangesImage() : resources.manyDesktopsImage(); } }