auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void updateActionAvailability() { NetworkView network = getEntity(); getNewCommand().setIsExecutionAllowed(network != null && network.isExternal()); getRemoveCommand().setIsExecutionAllowed((getSelectedItems() != null && getSelectedItems().size() > 0)); }

Target:
I thought the subtab wasn't supposed to even be visible if the network wasn't external?... And without this check you could just inline the getEntity().
Source:
public void executeCommand(UICommand command) { super.executeCommand(command); if (command == getNewCommand()) { newSubnet(); } else if (command == getRemoveCommand()) { remove(); } else if ("Cancel".equals(command.getName())) { //$NON-NLS-1$ cancel(); } }

Target:
Formatting.
Source:
public void setName(EntityModel<String> name) { this.name = name; }

Target:
I see no reason for the setters to be public.
Source:
public void flush() { if (subnet == null) { subnet = new ExternalSubnet(); } subnet.setName(getName().getEntity()); Network network = getNetwork().getSelectedItem(); subnet.setExternalNetwork(network != null ? network.getProvidedBy() : null); subnet.setCidr(getCidr().getEntity()); subnet.setIpVersion(getIpVersion().getSelectedItem()); }

Target:
Why not initiate the subnet to new ExternalSubnet() and get rid of this check?
Source:
protected void initLineModel(KeyValueLineModel keyValueLineModel, String key) { keyValueLineModel.getValue().setIsAvailable(false); keyValueLineModel.getValues().setIsAvailable(false); }

Target:
Actually, I think initLineModel() should be no-op too; the semantics of it are what happens when a different key is picked, but in this case nothing should change when a different key is picked, right? Both value boxes (constrained value and free text) are hidden all along. So I would hide them originally, say by extending the createNewLineModel() method, and implement this as no-op.
Source:
public void setVms(ListModel<Pair<String, VM>> vms) { this.vms = vms; }

Target:
I think this could be private.
Source:
public Object deepCopy(Object val) throws HibernateException { if (val == null) return null; if (val instanceof byte[]) { return new Guid((byte[]) val, true); } if (val instanceof UUID) return new Guid((UUID) val); if (val instanceof Guid) return new Guid(((Guid) val).getUuid()); throw new UnsupportedOperationException("Can't convert " + val.getClass() + " to GUID"); }

Target:
Shouldn't this be HibernateException?
Source:
public List<Network> getAllByLabelForCluster(String label, Guid clusterId) { List<Network> networksInCluster = getAllForCluster(clusterId, null, false); List<Network> labeledNetworks = new ArrayList<>(); for (Network network : networksInCluster) { if (StringUtils.equals(network.getLabel(), label)) { labeledNetworks.add(network); } } return labeledNetworks; }

Target:
Why not call just with id?
Source:
protected void onExportChanged() { boolean externalNetwork = (Boolean) getExport().getEntity(); getQos().setIsChangable(!externalNetwork); getAddQosCommand().setIsExecutionAllowed(!externalNetwork); String label = getNetworkLabel().getSelectedItem(); if (externalNetwork) { getNetworkLabel().setItems(new HashSet<String>()); } else { getNetworkLabel().setItems(dcLabels); } getNetworkLabel().setSelectedItem(label); }

Target:
consider 'ternary if' here
Source:
private List<VM> getMigrableVmsRunningOnVds(final Guid hostId, Map<Guid, List<VM>> hostId2HaVmMapping) { List<VM> vms = hostId2HaVmMapping.get(hostId); vms = LinqUtils.filter(vms, new Predicate<VM>() { @Override public boolean eval(VM v) { return v.getMigrationSupport() == MigrationSupport.MIGRATABLE && !hostId.equals(v.getDedicatedVmForVds()); } }); return vms; }

Target:
Migratable is enough.
Source:
private Map<Guid, BrickProperties> getBrickPropertiesMap(GlusterVolumeAdvancedDetails volumeDetails) { Map<Guid, BrickProperties> brickStatusMap = new HashMap<Guid, BrickProperties>(); for (BrickDetails brickDetails : volumeDetails.getBrickDetails()) { brickStatusMap.put(brickDetails.getBrickProperties().getBrickId(), brickDetails.getBrickProperties()); } return brickStatusMap; }

Target:
brickDetails.getBrickProperties().getBrickId() could be null if the brick is not present in DB
Source:
private boolean isMatchPath(String[] linkPathSegments, List<PathSegment> uriPathSegments) { for (int i = 0; i < linkPathSegments.length; i++) { String uriPathSegment = uriPathSegments.get(i).getPath(); if (isUUID(uriPathSegment) || uriPathSegment.equals(linkPathSegments[i])) { continue; } else { return false; } } return true; }

Target:
Maybe invert the condition and return false: if (!isUUID(uriPathSegment) && !uriPathSegment.equals(linkPathSegments[i])) { return false; } That way you don't need the else branch.
Source:
public EventsManager() throws NotificationServiceException { try { ds = new StandaloneDataSource(); } catch (SQLException e) { throw new NotificationServiceException("Failed to obtain database connectivity", e); } }

Target:
Why do we want to have runtime exception in the signature of the constructor?
Source:
public OneUuidReturnForXmlRpc glusterSnapshotCreate(String volumeName, String snapshotName, String description, boolean force) { JsonRpcRequest request = new RequestBuilder("GlusterSnapshot.create").withOptionalParameter("volumeName", volumeName) .withParameter("snapName", snapshotName) .withParameter("description", description) .withParameter("force", force) .build(); Map<String, Object> response = new FutureMap(this.client, request).withIgnoreResponseKey(); return new OneUuidReturnForXmlRpc(response); }

Target:
is volumeName optional parameter?
Source:
private void removeMemoryVolumes(String memoryVolume, Guid vmId) { VdcReturnValueBase retVal = getBackend().runInternalAction( VdcActionType.RemoveMemoryVolumes, new RemoveMemoryVolumesParameters(memoryVolume, vmId), ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); if (!retVal.getSucceeded()) { log.errorFormat("Failed to remove memory volumes: {0}", memoryVolume); } }

Target:
seems like we don't need "createDefaultContexForTasks"
Source:
private void volumeType_SelectedItemChanged() { if (getVolumeType().getSelectedItem() == null || getDataCenter().getSelectedItem() == null) { return; } VolumeType volumeType = (VolumeType) getVolumeType().getSelectedItem(); StorageType storageType = ((StorageDomain) getStorageDomain().getSelectedItem()).getStorageType(); updateVolumeFormat(volumeType, storageType); updateShareable(volumeType, storageType); }

Target:
please check getStorageDomain().getSelectedItem() for nullity - iirc, can be null in case storage domain is in maintenance.
Source:
public synchronized HashSet<Guid> getDomainProblematicVdsList(Guid domainId) { HashSet<Guid> vdsList = new HashSet<>(); Map<Guid, Status> domainVdsStatus = domainsVisibility.get(domainId); for (Entry<Guid, Status> status : domainVdsStatus.entrySet()) { if (status.getValue().isProblematic()) vdsList.add(status.getKey()); } return vdsList; }

Target:
please surround the block with
Source:
private SSLEngine createSSLEngine(boolean clientMode) { final SSLContext ctx = this.sslContext; if (ctx == null) { return null; } final SSLEngine engine = ctx.createSSLEngine(); engine.setUseClientMode(clientMode); return engine; }

Target:
Why use a local variable?
Source:
protected DataCenter postPopulate(DataCenter model) { model.setLocal(new Random().nextBoolean()); model.setStorageFormat(MappingTestHelper.shuffle(StorageFormat.class).value()); return model; }

Target:
This shouldn't be needed. The model is already randomly populated in the "populate" method. Enum types need this special treatment, but not booleans.
Source:
public static boolean isVersionMatchStorageType(Version version, boolean isLocalType) { if (isLocalType) { return version.compareTo(new Version(3, 0)) >= 0; } else { return version.compareTo(new Version(3, 0)) >= 0; } }

Target:
I still don't see why we need the 'if..else' here? both cases are the same
Source:
public boolean isLocal() { return getStorageType() == StorageType.LOCALFS; }

Target:
I'd add an isLocal() method to the StorageType enum and have this return getStorageType.isLocal()
Source:
public Boolean getHighlyAvailableLocalMaintenance() { return this.mVdsStatistics.getHighlyAvailableLocalMaintenance(); }

Target:
is there a special reason to use wrapped classes?
Source:
private void setGlobalHaMaintenance(boolean enabled) { VM vm = (VM) getSelectedItem(); if (vm == null) { return; } if (!vm.isHostedEngine()) { return; } SetHaMaintenanceParameters params = new SetHaMaintenanceParameters(vm.getRunOnVds(), HaMaintenanceMode.GLOBAL, enabled); Frontend.getInstance().runAction(VdcActionType.SetHaMaintenance, params, null, this); }

Target:
minor: you can use runAction overload with type and params.
Source:
public void setRefreshRate(int interval) { if (getRefreshRate() == interval) { return; } reset(); logger.fine("GridTimer[" + name + "]: Refresh Rate set to: " + interval); //$NON-NLS-1$ //$NON-NLS-2$ // set the NORMAL interval normalInterval = interval; ValueChangeEvent.fire(this, String.valueOf(getRefreshRate())); }

Target:
Hm, just a nit-picky question: shouldn't GridTimer implement HasValueChangeHandlers<Integer> instead of current HasValueChangeHandlers<String> ?
Source:
public static boolean canVmsBePaused(List<VM> items) { boolean result = true; for (VM vm : items) { result &= AsyncDataProvider.isSuspendSupportedByArchitecture(vm.getClusterArch(), vm.getVdsGroupCompatibilityVersion()); } return result; }

Target:
Please check the result here and break if false , since all values are with AND , there is no point to continue if we got false
Source:
public FilterEntry(String eventName, boolean exclude, String transport, String name) { this.eventName = eventName; this.exclude = exclude; this.recipient = new Recipient(transport, name); }

Target:
just a question... is there a rule in the styles not to: public FilterEntry(String messageName, boolean exclude, Recipient recipient) { this.messageName = messageName; this.exclude = exclude; this.recipient = recipient; } public FilterEntry(String messageName, boolean exclude, String transport, String name) { this(messageName, exclude, new Recipient(transport, name)); }
Source:
public FilterEntry(String eventName, boolean exclude, String transport, String name) { this.eventName = eventName; this.exclude = exclude; if (transport != null){ recipient = new Recipient(transport, name); } else { recipient = null; } }

Target:
I sent you alternate cleaner solution for this. once again, please separate between the parsing and the data.
Source:
public AuditLogType getAuditLogTypeValue() { switch (getActionState()) { case EXECUTE: if (getDisk().getDiskStorageType() == DiskStorageType.LUN) { return getSucceeded() ? AuditLogType.USER_FINISHED_REMOVE_DISK_NO_DOMAIN : AuditLogType.USER_FINISHED_FAILED_REMOVE_DISK_NO_DOMAIN; } else { return getSucceeded() ? AuditLogType.USER_FINISHED_REMOVE_DISK : AuditLogType.USER_FINISHED_FAILED_REMOVE_DISK; } default: return AuditLogType.UNASSIGNED; } }

Target:
lun disks removal can't fail actually in the execute part, as it's a simple removal from the db..but i don't mind having it for the future in case we'll add ops that might fail.
Source:
protected void endStepJobCommitted() { endStepJob(JobExecutionStatus.FINISHED, getStepMessageMap(JobExecutionStatus.FINISHED, " "), true); }

Target:
why sending space?
Source:
public List<File> getExtensionsDirectories() { String path = getProperty("ENGINE_EXTENSION_PATH"); if (path == null) { log.warn("No extension configurations directories were provided"); return Collections.emptyList(); } List<File> results = new ArrayList<File>(); for (String currentPath : path.split(":")) { if (StringUtils.isNotBlank(currentPath)) { results.add(new File(currentPath)); } } return results; }

Target:
the need of warning is up to caller not this infrastructure component.
Source:
public String getProfileName() { Properties config = (Properties) context.get(ExtensionProperties.CONFIGURATION); return config.getProperty("ovirt.engine.aaa.authz.profile.name"); }

Target:
why do you need config temp variable?
Source:
private DbUserCacheManager() { for (AuthenticationProfile profile : AuthenticationProfileRepository.getInstance().getProfiles()) { directoriesMap.put(profile.getDirectory().getName(), profile.getDirectory()); } }

Target:
I am unsure why you need to cache yet another instance of this map... just query the repository at each iteration.
Source:
private static void createOutputDirectory(String outputDirectory) { File outputDir = new File(outputDirectory); if (!outputDir.exists()) { outputDir.mkdirs(); } }

Target:
I think we should reuse this File object, returning it, for example, and then pass it to the copy medhod, instead of the string.
Source:
public NotificationService(NotificationProperties prop) throws NotificationServiceException { this.prop = prop; this.eventsManager = new EventsManager(); this.firstMatchSimpleFilter = new FirstMatchSimpleFilter(); Smtp smtp = new Smtp(prop); smtp.addObserver(this.eventsManager); addTransport(smtp); this.firstMatchSimpleFilter.registerTransport(smtp); configurationFilters = FirstMatchSimpleFilter.parse(prop.getProperty(NotificationProperties.FILTER)); markOldEventsAsProcessed(); }

Target:
if transports is private, there is not really need for a method that wraps list add.
Source:
protected java.util.ArrayList<Guid> getTemplatesList() { return getParameters().getEntitiesId(); }

Target:
please import java.util instead of explicitly writing here
Source:
private boolean networkExists() { List<NetworkCluster> networks = getNetworkClusterDAO().getAllForCluster(getVdsGroupId()); for (NetworkCluster networkCluster : networks) { if (networkCluster.getNetworkId().equals( getNetworkCluster().getNetworkId())) { return true; } } return false; }

Target:
Why not just use the get method that accepts NetworkClusterId?
Source:
public VdsManager GetVdsManager(Guid vdsId) { return GetVdsManager(vdsId, true); }

Target:
true=>false
Source:
public VdsIdVDSCommandBase(P parameters) { this(parameters, true); }

Target:
true=>false
Source:
public boolean isEmpty(){ return getItems() == null || getItems().size() == 0; }

Target:
Don't think items can be null, and ArrayList (as well as List and Collection) has an isEmpty() method itself...
Source:
public static Map<Integer, Map<Version, Boolean>> getBalloonSupportMap() { return balloonSupportMap; }

Target:
no need to have this getter public
Source:
protected Permit addParents(Permit permit) { if (permit == null) { System.out.println("permit is null"); } if (parent == null) { System.out.println("parent is null"); } return parent.addParents(permit); }

Target:
Sorry wrong patch, will fix these
Source:
public static EventNotificationMethod valueOfString(String value) { return valueOf(value != null ? value.toUpperCase() : null); }

Target:
valueOf does not support nulls - this will cause an NPE, just like the code before the patch. I'm guessing you meant to do something like this: return value != null ? valueOf(value.toUpperCase()) : null;
Source:
public void testDoGet_NotFound_MissingFile() throws IOException, ServletException { final IConfigUtilsInterface configUtils = Mockito.mock(IConfigUtilsInterface.class); Config.setConfigUtils(configUtils); // The file should not exist, and thus return a 404. testServlet.doGet(mockRequest, mockResponse); verify(mockResponse).sendError(HttpServletResponse.SC_NOT_FOUND); }

Target:
are you sure this is required?
Source:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Locate the requested file: File file = ServletUtils.makeFileFromSanePath(request.getPathInfo(), base); file = checkForIndex(request, response, file, request.getPathInfo()); // Send the content of the file: // type is the default MIME type of the Servlet. ServletUtils.sendFile(request, response, file, type, cache, file == base && required); }

Target:
remove file==base as the entire tree should be effected.
Source:
protected boolean isGhost(EntityModel<String> value) { String text = value.getEntity(); return text == null || text.isEmpty(); }

Target:
Please use StringHelper.isNullOrEmpty()
Source:
void onWindowFocusChange(boolean inFocus) { GridTimer modelTimer = getModelTimer(); // Change refresh rate only when the model timer is currently active and not paused if (modelTimer.isActive() && !modelTimer.isPaused()) { if (inFocus) { modelTimer.stop(); modelTimer.setRefreshRate(readRefreshRate()); } else { modelTimer.stop(); modelTimer.setRefreshRate(OUT_OF_FOCUS_REFRESH_RATE); } modelTimer.start(); } }

Target:
Hm, any reason why not add: modelTimer.stop(); before the if block, which is analogous to having: modelTimer.start(); after the if block?
Source:
public void setComment(String value) { if (value == null) { this.comment = ""; } else { this.comment = value; } }

Target:
this.comment = (value == null) ? "" : value;
Source:
public void authenticate(String user, String password) { String adminUser = ((Properties)context.get(ExtensionProperties.CONFIGURATION)).getProperty("config.authn.user.name"); String adminPassword = ((Properties)context.get(ExtensionProperties.CONFIGURATION)).getProperty("config.authn.user.password"); if (!ObjectUtils.equals(user, adminUser) || !ObjectUtils.equals(password, adminPassword)) { throw new AAAExtensionException(AAAExtensionException.AAAExtensionError.INCORRECT_CREDENTIALS, ""); } }

Target:
hmmm... why not: !(equals && equals) :)
Source:
public ExtensionEntry(Properties props) { this.file = null; context = new EnumMap<>(ExtensionProperties.class); load(props); }

Target:
no need for this.file = null as it will be null.
Source:
private BrokerCommandBase CreateCommand(AdActionType action, LdapBrokerBaseParameters parameters) { Class type; try { type = Class.forName(GetCommandTypeName(action)); Constructor info = ReflectionUtils.findConstructor(type, parameters.getClass()); Object tempVar = info.newInstance(parameters); return (BrokerCommandBase) ((tempVar instanceof BrokerCommandBase) ? tempVar : null); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { log.errorFormat("LdapBrokerCommandBase: Failed to get type information using reflection for Action: {0}", action); return null; } }

Target:
Why not simply catch Exception, since you don't do special handling for each exception class?
Source:
public void runMultipleActions(final List<VdcActionType> actionTypes, final List<VdcActionParametersBase> parameters, final List<IFrontendActionAsyncCallback> callbacks, final IFrontendActionAsyncCallback failureCallback, final Object state) { runMultipleActions(actionTypes, parameters, callbacks, failureCallback, state, false, null, null); }

Target:
you can call runMultipleActions(actionTypes, parameters, callbacks, failureCallback, state, false);
Source:
public void runMultipleActions(final List<VdcActionType> actionTypes, final List<VdcActionParametersBase> parameters, final List<IFrontendActionAsyncCallback> callbacks, final IFrontendActionAsyncCallback failureCallback, final Object state) { runMultipleActions(actionTypes, parameters, callbacks, failureCallback, state, false, null); }

Target:
I agree, however the question is, how will this change (aggregate error messages by default) affect existing code using this method.
Source:
protected void executeQueryCommand() { Integer numOfVms = getDbFacade().getVdsGroupDao().getVmsCountByClusterId(getParameters().getId()); getQueryReturnValue().setReturnValue(numOfVms); }

Target:
why integer and not int? i dont think this can return null
Source:
protected LockProperties getLockingPropertiesSettings() { return new LockProperties().setObtainLock(false); }

Target:
I expect this should be false by default... return new LockProperties(); And if you want to lock you: return new LockProperties.setObtainLock(true);
Source:
protected boolean verifySnapshotsStatus(List<Snapshot> snapshots) { for (Snapshot snapshot : snapshots) { if (snapshot.getStatus() != SnapshotStatus.OK && snapshot.getStatus() != SnapshotStatus.BROKEN) { return false; } } return true; }

Target:
not sure why broken is considered valid - btu, note the broken status might be removed
Source:
protected void updateOriginalTemplate(VmStatic vmStatic) { vmStatic.setOriginalTemplateGuid(getParameters().getVmStaticData().getOriginalTemplateGuid()); vmStatic.setOriginalTemplateName(getParameters().getVmStaticData().getOriginalTemplateName()); }

Target:
it looks a bit weird to get getParameters().getVmStaticData() again since it is the same as the method argument vmStatic.. in other places, not in ovirt-engine, I would suggest to use the argument instead, but in order to comply with the standards in our commands infrastructure I would suggest to remove the argument (and change AddVmCommand accordingly). anyway, those two solution will be fine by me
Source:
public static VdcActionParametersBase getParameters(CommandEntity commandEntity) { return commandEntity.getData() != null ? (VdcActionParametersBase) commandEntity.getData().get(PARAMETERS_KEY) : null; }

Target:
how about initialize CommandEntity#data to empty map in CommandEntity instead of all those null checks?
Source:
private static void AddEventNotificationEntry(EventNotificationEntity entity, AuditLogType auditLogType) { HashSet<AuditLogType> entry; if (!_eventNotificationTypeMap.containsKey(entity)) { _eventNotificationTypeMap.put(entity, new HashSet<AuditLogType>()); } entry = _eventNotificationTypeMap.get(entity); entry.add(auditLogType); }

Target:
In order not to use contains and get methods, I would prefer following code: HashSet<AuditLogType> entry = _eventNotificationTypeMap.get(entity); if (entry == null) { entry = new HashSet<AuditLogType>(); _eventNotificationTypeMap.put(entity, entry); } entry.add(auditLogType);
Source:
public void testGetWithEntityId() { dao = dbFacade.getUnregisteredOVFDataDao(); OvfEntityData ovfEntityData = dao.getByEntityIdAndStorageDomain(FixturesTool.VM_RHEL5_POOL_50, FixturesTool.STORAGE_DOAMIN_NFS2_1); assertNotNull("VM should exists in the UnregisteredOVFData", ovfEntityData); }

Target:
Should be done in the setup. Note this re-occurs in all your test methods
Source:
public boolean testConnection() { try { getClient().execute(new OpenStackRequest<>(getClient(), HttpMethod.GET, "", null, null)); return true; } catch (RuntimeException e) { throw new VdcBLLException(VdcBllErrors.PROVIDER_FAILURE, e); } }

Target:
why do you need it as a boolean? I don't mind, but not sure it is needed.
Source:
static private List<DiskImage> generateDisksList(int size) { List<DiskImage> disksList = new ArrayList<>(); for (int i = 0; i < size; ++i) { DiskImage diskImage = new DiskImage(); diskImage.setImageId(Guid.newGuid()); disksList.add(diskImage); } return disksList; }

Target:
private static
Source:
protected void mockGetAllSnapshots(AddVmFromTemplateCommand<AddVmFromTemplateParameters> command) { doAnswer(new Answer<List<DiskImage>>() { @Override public List<DiskImage> answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); DiskImage arg = (DiskImage) args[0]; List<DiskImage> list = createDiskSnapshot(arg.getId(), 3); return list; } }).when(command).getAllImageSnapshots(any(DiskImage.class)); }

Target:
should be private
Source:
public void testInitCanBeCalledTwice() throws Exception { MacPoolPerDc pool = new MacPoolPerDc(); pool.initialize(); Mockito.verify(dbFacadeMock).getMacPoolDao(); Mockito.verify(macPoolDaoMock).getAll(); Mockito.verifyNoMoreInteractions(storagePoolDaoMock, vmNicDaoMock, macPoolDaoMock, dbFacadeMock); pool.initialize(); //should not fail. }

Target:
I believe that this should come after the second call, not before.. Or even better, both here and there..
Source:
protected void fillMacAddressIfMissing(VmNic iface) { final MacPoolManagerStrategy pool = getMacPool(); if (StringUtils.isEmpty(iface.getMacAddress()) && (pool.getAvailableMacsCount() >= 1)) { iface.setMacAddress(pool.allocateNewMac()); } }

Target:
No need to extract to variable
Source:
protected boolean canRunActionOnNonManagedVm() { ValidationResult nonManagedVmValidationResult = VmHandler.canRunActionOnNonManagedVm(getVm(), getActionType()); if (!nonManagedVmValidationResult.isValid()) { return failCanDoAction(nonManagedVmValidationResult.getMessage()); } return true; }

Target:
Although a nice change, it's unrelated to this patch and should go in a separate one.
Source:
public void removeAll(Guid vmId) { List<VmNic> interfaces = getVmNicDao().getAllForVm(vmId); if (interfaces != null) { removeFromExternalNetworks(interfaces); final MacPoolManagerStrategy macPool = getMacPoolManager(vmId); for (VmNic iface : interfaces) { macPool.freeMac(iface.getMacAddress()); getVmNicDao().remove(iface.getId()); getVmNetworkStatisticsDao().remove(iface.getId()); } } }

Target:
No need to extract to variable.
Source:
public Guid getVmtGuid() { return vmtGuid; }

Target:
Although a nice change, it's unrelated to this patch and should go in a separate one.
Source:
public void setVmtGuid(Guid value) { vmtGuid = value; }

Target:
Although a nice change, it's unrelated to this patch and should go in a separate one.
Source:
public Object getData(String key, boolean refresh) { return getData(ThreadLocalParamsContainer.getHttpSessionId(), key, refresh); }

Target:
put all getData() at same place?
Source:
private void refresh(SessionInfo sessionInfo) { Date now = new Date(); Date softLimit = (Date) sessionInfo.contentOfSession.get(SOFT_LIMIT_PARAMETER_NAME); if (softLimit == null) { softLimit = now; } int softLimitValue = Config.<Integer> getValue(ConfigValues.UserSessionTimeOutInterval); if (softLimitValue > 0) { sessionInfo.contentOfSession.put(SOFT_LIMIT_PARAMETER_NAME, DateUtils.addMinutes(now, softLimitValue)); } }

Target:
on the 10th time... why do you need to get the soft limit at refresh?!?!?
Source:
private SessionInfo getSessionInfo(String sessionId) { SessionInfo sessionInfo = null; for (SessionInfo currentSessionInfo : sessionInfoMap.values()) { if (currentSessionInfo.sessionId.equals(sessionId)) { sessionInfo = currentSessionInfo; break; } } return sessionInfo; }

Target:
why the key cannot be session id?
Source:
public final void removeSession(String sessionId) { Iterator<Entry<String, SessionInfo>> iterator = sessionInfoMap.entrySet().iterator(); while (iterator.hasNext()) { if (iterator.next().getKey().equals(sessionId)) { iterator.remove(); break; } } }

Target:
I still don't understand why the key cannot be the session id
Source:
protected void addCanDoActionMessageVariable(String varName, Object varValue) { String message = String.format("$%s %s", varName, varValue); getReturnValue().getCanDoActionMessages().add(message); }

Target:
feel free to inline this. No need for String message temp variable.
Source:
private boolean verifyDisksIfNeeded() { boolean verified = true; if (!getParameters().isImportAsNewEntity() && !isImagesAlreadyOnTarget()) { verified = checkIfDisksExist(imageList); } return verified; }

Target:
ok, so if we keep this method, can you please remove the 'verified' variable? it is not really needed, and then people will add more logic into this method and we'll end-up with complicated methods like the old canDoAction methods..
Source:
public LoggerHandler() { update(null, null); ExtensionsManager.getInstance().addObserver(this); }

Target:
switch order to avoid race?
Source:
public void publish(LogRecord record) { initRefreshThread(); ExtMap publishInputMap = new ExtMap() .mput(Base.InvokeKeys.COMMAND, Logger.InvokeCommands.PUBLISH); ExtMap publishOutputMap = new ExtMap(); for (ExtensionProxy extension : getExtensions()) { try { extension.invoke( publishInputMap.mput(Logger.InvokeKeys.LOG_RECORD, record), publishOutputMap); } catch(Exception ex) } }

Target:
please put record above as well.
Source:
public ValidationResult isReadOnlyPropertyCompatibleWithLunInterface() { if (Boolean.TRUE.equals(disk.getReadOnly()) && disk.getDiskInterface() == DiskInterface.VirtIO_SCSI && disk.getDiskStorageType() == DiskStorageType.LUN) { return new ValidationResult( VdcBllMessages.ACTION_TYPE_FAILED_VIRT_IO_SCSI_INTERFACE_FOR_LUN_DISKS_DOES_NOT_SUPPORT_READ_ONLY_ATTR); } return ValidationResult.VALID; }

Target:
any reason not to combine this method with isReadOnlyPropertyCompatibleWithInterface ?
Source:
public GlusterVolumeProfileParameters(Guid clusterId, Guid volumeId) { super(clusterId, volumeId); this.nfs = false; }

Target:
should be : this( clusterId, volumenId, false);
Source:
public void testConvertSecondsToMinutes() { long seconds = 1800L; Pair<Long, TimeUnit> expectedResults = TimeConverter.autoConvert(seconds, TimeUnit.SECONDS); assertEquals(expectedResults.getFirst().longValue() , 30L); assertEquals(expectedResults.getSecond(), TimeUnit.MINUTES); }

Target:
Reorder expected and actual as per this patch - http://gerrit.ovirt.org/#/c/27775/
Source:
public void showNfsProfileStats(GlusterVolumeProfileInfo entity) { List<GlusterVolumeProfileStats> nfsProfileDetails = entity.getNfsProfileDetails(); getNfsServers().setItems(nfsProfileDetails); getNfsServers().setSelectedItem(nfsProfileDetails.get(0)); }

Target:
you may want to check the size of the list
Source:
public Guid getVmTemplateId() { if (isImagesAlreadyOnTarget()) { return getParameters().getContainerId(); } else { return super.getVmTemplateId(); } }

Target:
can remove the 'else' clause...
Source:
private List<ExternalDiscoveredHost> runDiscoveredHostListMethod(HttpMethod httpMethod) { try{ runHttpMethod(httpClient, httpMethod); ForemanDiscoveredHostWrapper fdw = objectMapper.readValue(httpMethod.getResponseBody(), ForemanDiscoveredHostWrapper.class); return mapDiscoveredHosts(Arrays.asList(fdw.getResults())); } catch (JsonParseException e) { handleException(e); } catch (JsonMappingException e) { handleException(e); } catch (IOException e) { handleException(e); } return null; }

Target:
I think here it is the same as doing only catch (IOException e) { handleException(e); } because the other two are IOExceptions two and you handle all the same. please apply to other blocks as well
Source:
private void addSELinuxModes(VersionCaps version, SELinuxMode[] values) { if (VersionUtils.greaterOrEqual(version, VERSION_3_5)) { version.setSelinuxModes(new SELinuxModes()); for (SELinuxMode mode: values) { version.getSelinuxModes().getSELinuxModes().add(mode.toString().toLowerCase()); } } }

Target:
This should be as it used to be, no need to convert to lower case as that should already be part of the "value()" implementation of SELinuxMode.
Source:
private void copyDiskDevicesFromTemplate() { List<VmDevice> disks = DbFacade.getInstance().getVmDeviceDao().getVmDeviceByVmIdAndType(getVmTemplateId(), VmDeviceGeneralType.DISK); VmDeviceUtils.copyVmDevices( vmDisksSource.getId(), getVmId(), getVm(), getVm().getStaticData(), true, disks, getSrcDeviceIdToTargetDeviceIdMapping(), false, false, false, false, false ); }

Target:
please use vmDisksSource here as well
Source:
private void updatePosixProperties(IStorageModel storageModel) { PosixStorageModel posixModel = (PosixStorageModel) storageModel; connection.setVfsType(posixModel.getVfsType().getEntity().toString()); if (posixModel.getMountOptions().getEntity() != null) { connection.setMountOptions(posixModel.getMountOptions().getEntity()); } }

Target:
This change, while it may be true, is unrealted to NFS Mount Options. Please publish it in a separate fix.
Source:
public void testKDCLocator() { KDCLocator locator = new KDCLocator(); String[] recordsList = { "0 100 88 example.com.", "0 100 88 comp1.example.com", "1 100 88 comp1.example.com." }; DnsSRVResult result = locator.getKdc(recordsList, "example.com"); int numOfEntries = result.getNumOfValidAddresses(); Assert.assertEquals(3, numOfEntries); }

Target:
omit Assert class notation ?
Source:
public void useDefaultMTU() { Set<ConstraintViolation<MtuContainer>> validate = validate(new MtuContainer(0)); Assert.assertEquals(0, validate.size()); }

Target:
following the change above, i'd expect this one to look as: assertTrue(validate.isEmpty())
Source:
public void testCompareTo() { Guid guid1 = new Guid("5b411bc1-c220-4421-9abd-cfa484aecb6e"); Guid guid2 = new Guid("5b411bc1-c220-4421-9abd-cfa484aecb6f"); assertTrue(guid1.compareTo(guid2) < 0); Assert.assertEquals(0, guid1.compareTo(guid1)); assertTrue(guid2.compareTo(guid1) > 0); }

Target:
please omit class notation.
Source:
public synchronized String load(Properties configuration) { return loadImpl(configuration, null); }

Target:
won't it better to sync the loadImpl?
Source:
public void setMainTabSelectedItem(VDS selectedItem) { // TODO(vszocs) possible performance optimization: don't create HostInterfaceForm upon each selection hostInterfaceForm = new HostInterfaceForm(getDetailModel()); contentPanel.remove(contentPanel.getWidgetCount() - 1); contentPanel.add(hostInterfaceForm); contentPanel.getParent().getElement().getStyle().setOverflowX(Overflow.AUTO); }

Target:
This should work if you put it in the constructor after initWidget(), shouldn't it? It shouldn't be invoked upon selection of a main tab item.
Source:
protected void executeCommand() { // add user session setActionReturnValue(getCurrentUser()); getReturnValue().setLoginResult(LoginResult.Autheticated); getReturnValue().setSessionId(engineSessionId); // Permissions for this user might been changed since last login so // update his isAdmin flag accordingly updateUserData(); ApplicationMode appMode = ApplicationMode.from(Config.<Integer> getValue(ConfigValues.ApplicationMode)); SessionDataContainer.getInstance().setData("app_mode", appMode); setSucceeded(true); }

Target:
What is the point of putting the application mode in the session? Anywhere we would read that information can't we simply read the configuration?
Source:
public VdcActionParametersBase(String engineSessionId) { shouldbelogged = true; transctionOption = TransactionScopeOption.Required; setTaskGroupSuccess(true); setParentCommand(VdcActionType.Unknown); executionReason = CommandExecutionReason.REGULAR_FLOW; compensationEnabled = false; parentCommand = VdcActionType.Unknown; commandType = VdcActionType.Unknown; imagesParameters = new ArrayList<VdcActionParametersBase>(); sessionid = engineSessionId; }

Target:
Why not simply make the constructor like this: public VdcActionParametersBase(String engineSessionId) { this(); sessionId = engineSessionId; } No code duplication and much shorter.
Source:
public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain) throws IOException, ServletException { // If there are no authentication profiles supporting negotiation then we don't do anything, as there is no // authentication to perform: findNegotiatingProfiles(req); if (!profiles.isEmpty()) { // Perform the authentication: doAuth((HttpServletRequest) req, (HttpServletResponse) rsp, chain); } chain.doFilter(req, rsp); }

Target:
else is missing here... every time you perform doAuth you also process the request into the webapp, this should not happen as long as you are nego. just add else here.
Source:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpSession session = req.getSession(false); if ((req.getHeader("Authorization") != null)) { // No need to pass credentials again - if passed, login should be called if (session != null) { session.invalidate(); session = null; } } chain.doFilter(request, response); }

Target:
why do you get the session here? move into condition where you actually use them.
Source:
public BalanceResource getSubResource(String id) { return inject(new BackendBalanceResource(id, getPolicyUnit(id))); }

Target:
getSubResource --> getBalanceSubResource, for consistency
Source:
protected boolean isCustomMtu() { return MtuSelector.customMtu.equals(getMtuSelector().getSelectedItem()); }

Target:
Note that enums can be used with ==, but as you prefer.
Source:
protected void executeVdsBrokerCommand() { String volumeName = getParameters().getVolumeName(); result = getBroker().glusterVolumeRebalanceStop(volumeName); GlusterVolumeTaskStatusEntity entity = result.getStatusDetails(); entity.setStatusTime(new Date()); entity.setStopTime(new Date()); proceedProxyReturnValue(); setReturnValue(entity); }

Target:
why did you move this line? basically proceedProxyReturnValue should be called before using the result, because in case of error it might be null or not as expected, and NPE will hide the real error message from vdsm
Source:
public void testSaveOrUpdateExisting() { int sizeBeforeSave = dao.getAll().size(); existingUser.setFirstName("changedname"); existingUser.setLastName("changedsurname"); int sizeAfterSave = dao.getAll().size(); dao.saveOrUpdate(existingUser); DbUser result = dao.get(existingUser.getId()); assertEquals(existingUser, result); assertEquals(0, sizeAfterSave - sizeBeforeSave); }

Target:
Shouldn't this be executed after dao.saveOrUpdate()?
Source:
public boolean equals(Object obj) { if (obj == null) { return false; } super.equals(obj); BrickProfileDetails brickDetails = (BrickProfileDetails) obj; if (brickDetails.getBrickId() == null) { return false; } if (!(ObjectUtils.objectsEqual(getBrickId(), brickDetails.getBrickId()))) { return false; } return true; }

Target:
you're not using the return value shouldn't it be... if (!super.equals(obj)) { return false }
Source:
public ValidationResult isInProcess() { StoragePoolIsoMap domainIsoMap = storageDomain.getStoragePoolIsoMapData(); if (domainIsoMap.getStatus() != null && domainIsoMap.getStatus().isStorageDomainInProcess()) { new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2, String.format("$status %1$s", StorageDomainStatus.Locked)); } return ValidationResult.VALID; }

Target:
the status in the message is now wrong (as you check more statuses), let's put the domain status.
Source:
protected void addStoragePoolToDb() { final StoragePool storagePool = getStoragePool(); storagePool.setId(Guid.newGuid()); storagePool.setStatus(StoragePoolStatus.Uninitialized); Guid requestedMacPoolId = storagePool.getMacPoolId(); Guid macPoolIdToUse = requestedMacPoolId == null ? getMacPoolDao().getDefaultPool().getId() : requestedMacPoolId; storagePool.setMacPoolId(macPoolIdToUse); getStoragePoolDAO().save(storagePool); }

Target:
No need to extract to variable
Source:
private static void convertAAAProfilesResult(AsyncQuery aQuery) { aQuery.converterCallback = new IAsyncConverter() { @Override public Object Convert(Object source, AsyncQuery _asyncQuery) { List<String> results = new ArrayList<String>(); for (ProfileEntry profileEntry : source != null ? (Collection<ProfileEntry>) source : new ArrayList<ProfileEntry>()) { results.add(profileEntry.getProfile()); } return results; } }; }

Target:
Backend does not return null, why do we need a null check here for source?
Source:
private String extractAuthorizationProvider(ProfileEntry profileEntry) { return profileEntry == null ? "" : profileEntry.getAuthz(); }

Target:
if it is null how come we search or even return ""?
Source:
public DiskProfile getProfile() { if (profile == null) { if (getParameters().getProfile() != null) { profile = getParameters().getProfile(); } else if (getParameters().getProfileId() != null) { profile = getProfileDao().get(getParameters().getProfileId()); } else { log.error("couldn't find disk profile"); } } return profile; }

Target:
please move the else a line up
Source:
public boolean equalValues(QosBase other) { // no extra values return true; }

Target:
true for every other QOS, even if they are not from the same type?
Source:
public static String getUniqueHostName(VDS host) { return host.getHostName() + "-" + new String(DigestUtils.md5Hex(host.getId().toByteArray())).substring(0, 6); }

Target:
if md5Hex returns string, why do you need new String? but if you use new String on byte array... you should use explicit encoding.
Source:
public CommandContext resetExecutionContext() { setExecutionContext(new ExecutionContext()); return this; }

Target:
return setExecution ...
Source:
public VdcReturnValueBase endAction(VdcActionType actionType, VdcActionParametersBase parameters, CommandContext context) { CommandBase<?> command = context != null ? CommandsFactory.createCommand(actionType, parameters, context.duplicate()) : CommandsFactory.createCommand(actionType, parameters); return command.endAction(); }

Target:
context must be non null
Source:
private void updateAvailabilitByDatacenter(StoragePool datacenter) { if (datacenter == null) { return; } getModel().getActivateDomain().setIsAvailable(datacenter.getId() != StorageModel.UnassignedDataCenterId); }

Target:
Use .equals instead, it's two objects
Source:
public static Map<String, Object> jsonToMap(String jsonString) throws JsonParseException, JsonMappingException, IOException { final ObjectMapper mapper = new ObjectMapper(); final MapType type = mapper.getTypeFactory().constructMapType(Map.class, String.class, Object.class); final Map<String, Object> data = mapper.readValue(jsonString, type); return data; }

Target:
Why's everything final?
Source:
protected void updateDiskProfile(DiskImage diskImage) { if (isDiskImage()) { DiskImage oldDisk = (DiskImage) getOldDisk(); if (!Objects.equals(oldDisk.getDiskProfileId(), diskImage.getDiskProfileId())) { getImageStorageDomainMapDao().updateDiskProfileByImageGroupId(diskImage.getId(), diskImage.getStorageIds().get(0), diskImage.getDiskProfileIds().get(0)); } } }

Target:
why not getDiskProfileId?
Source:
public void testChangeDiskProfileForDisk() { // fetch image image_storage_domain_map image_storage_domain_map = dao.getAllByImageId(EXISTING_IMAGE_ID).get(0); // test that the current disk profile doesn't equal with the new disk profile assertThat("Same source and dest disk profile id, cannot perform test", image_storage_domain_map.getDiskProfileId(), not(equalTo(Guid.newGuid()))); // change to newDiskProfileId dao.updateDiskProfileByImageGroupId(EXISTING_DISK_ID, EXISTING_DOMAIN_ID, FixturesTool.DISK_PROFILE_2); // fetch the image again image_storage_domain_map = dao.getAllByImageId(EXISTING_IMAGE_ID).get(0); // check that the new disk profile is the inserted one assertEquals("disk profile wasn't changed", image_storage_domain_map.getDiskProfileId(), FixturesTool.DISK_PROFILE_2); }

Target:
you use different guid here and on the update statement.
Source:
protected boolean setAndValidateDiskProfiles() { if (diskInfoDestinationMap != null) { Map<DiskImage, Guid> map = new HashMap<>(); for (DiskImage diskImage : diskInfoDestinationMap.values()) { map.put(diskImage, diskImage.getStorageIds().get(0)); } return validate(DiskProfileHelper.setAndValidateDiskProfiles(map)); } return true; }

Target:
iirc it's initialized in the ctor, check that it's not empty .
Source:
protected boolean setAndValidateDiskProfiles() { Map<DiskImage, Guid> map = new HashMap<>(); if (diskInfoDestinationMap != null) { for (DiskImage diskImage : diskInfoDestinationMap.values()) { map.put(diskImage, diskImage.getStorageIds().get(0)); } } return validate(DiskProfileHelper.setAndValidateDiskProfiles(map)); }

Target:
create the map here only when needed
Source:
public DiskProfileValidator(DiskProfile diskProfile) { this(diskProfile.getId()); this.diskProfile = diskProfile; }

Target:
NPE in case that diskProfile is null
Source:
public void close() throws IOException { tarArchiveOutputStream.close(); }

Target:
please remove from this patch
Source:
protected VDSReturnValue runVdsCommand(VDSCommandType commandType, VDSParametersBase parameters) throws VdcBLLException { parameters.setCorrelationId(getCorrelationId()); return getBackend().getResourceManager().RunVdsCommand(commandType, parameters); }

Target:
we still have this in thread local... why is it needed in this patch?
Source:
private void initCommandExecutor() { if (!cmdExecutorInitialized) { synchronized(LOCK) { if (!cmdExecutorInitialized) { for (CommandEntity cmdEntity : coco.getCommandsWithCallBackEnabled()) { switch(cmdEntity.getCommandStatus()) { case ACTIVE_SYNC: case NOT_STARTED: coco.retrieveCommand(cmdEntity.getId()).setCommandStatus(CommandStatus.FAILED_RESTARTED); break; default: if (!cmdEntity.isCallBackNotified()) { addToCallBackMap(cmdEntity); } break; } } cmdExecutorInitialized = true; } } } }

Target:
please rebase, arik removed the lock in a different patch.
Source:
public void initSelectedMacPool() { Collection<MacPool> allMacPools = getMacPoolListModel().getItems(); StoragePool dc = getEntity(); if (allMacPools != null && dc != null) { Guid macPoolId = dc.getMacPoolId(); if (macPoolId != null) { for (MacPool macPool : allMacPools) { if (macPoolId.equals(macPool.getId())) { getMacPoolListModel().setSelectedItem(macPool); break; } } } } }

Target:
1. And what if it it is null? Shouldn't you choose the default pool? 2. Should be part of the previous patch.
Source:
public TextBoxLabel() { super(new EmptyValueRenderer<String>() { @Override public String render(String value) { String renderedText = super.render(value); return renderedText; } }); }

Target:
in case you are removing the SafeHtmlUtils.htmlEscape(renderedText); you do not need to override the render() method. Please use only: super(new EmptyValueRenderer<String>());
Source:
public void remove() { if (getConfirmWindow() != null) { return; } ConfirmationModel model = getRemoveQosModel(); setConfirmWindow(model); }

Target:
variable can be removed
Source:
public void newQos() { if (getWindow() != null) { return; } final NewQosModel<T, P> newQosModel = getNewQosModel(); setWindow(newQosModel); newQosModel.getDataCenters().setItems(Arrays.asList(getEntity())); newQosModel.getDataCenters().setSelectedItem(getEntity()); }

Target:
use this signature: 'setItems(Collection<T> value, T selectedItem)'
Source:
protected void addCommands() { UICommand tempVar2 = new UICommand("OnSave", this); //$NON-NLS-1$ tempVar2.setTitle(ConstantsManager.getInstance().getConstants().ok()); tempVar2.setIsDefault(true); getCommands().add(tempVar2); UICommand tempVar3 = new UICommand("Cancel", this); //$NON-NLS-1$ tempVar3.setTitle(ConstantsManager.getInstance().getConstants().cancel()); tempVar3.setIsCancel(true); getCommands().add(tempVar3); }

Target:
rename tempvar
Source:
public void edit(QosModel<StorageQos, StorageQosParametersModel> object) { qosWidget.edit(object.getQosParametersModel()); driver.edit(object); }

Target:
call driver's edit first
Source:
static String getResourceBundleName() { return "bundles/AuditLogMessages"; }

Target:
package private.
Source:
private void scheduleCheckStatus() { if (scheduledStatusCheckInProgress || reportsWebappDeployed) { return; } scheduledStatusCheckInProgress = true; Scheduler.get().scheduleFixedDelay( new Scheduler.RepeatingCommand() { @Override public boolean execute() { if (retryCount > MAX_RETRY_COUNTS || reportsWebappDeployed) { scheduledStatusCheckInProgress = false; return false; } retryCount++; checkReportsWebAppStatus(); return true; } }, RETRY_INTERVAL); }

Target:
I see you"ve moved 'reportsWebappDeployed' but what about 'retryCount > MAX_RETRY_COUNTS'?
Source:
private void scheduleCheckStatus() { if (urlInitialized && reportBaseUrl.trim().isEmpty()) { return; } if (scheduledStatusCheckInProgress) { return; } scheduledStatusCheckInProgress = true; Scheduler.get().scheduleFixedDelay( new Scheduler.RepeatingCommand() { @Override public boolean execute() { if (retryCount > MAX_RETRY_COUNTS || reportsWebappDeployed) { scheduledStatusCheckInProgress = false; return false; } retryCount++; checkReportsWebAppStatus(); return true; } }, RETRY_INTERVAL); }

Target:
IMO, urlInitialized check here is redundant. I"m not sure how can you get to this point with urlInitialized=false. (And if it is false- don't you want to return?)
Source:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String queryString = request.getQueryString(); if (StringUtils.isNotEmpty(queryString)) { if (url.indexOf("?") == -1) { url += "?"; } else { url += "&"; } url += queryString; } response.sendRedirect(response.encodeRedirectURL(url)); }

Target:
I am almost sure you cannot encode the query string, as result is double encode.