auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private List<VdsNetworkInterface> applyUserConfiguredNics() { List<VdsNetworkInterface> nicsToConfigure = getNicsToConfigureWithoutLabelsUpdates(); updateLabelsOnNicsToConfigure(nicsToConfigure); START return new ArrayList<>(nicsToConfigure); END } is this still needed?

Target:
private List<VdsNetworkInterface> applyUserConfiguredNics() { List<VdsNetworkInterface> nicsToConfigure = getNicsToConfigureWithoutLabelsUpdates(); updateLabelsOnNicsToConfigure(nicsToConfigure); return nicsToConfigure; }
Source:
private ValidationResult validateCoherentNetworkIdentification(NetworkAttachment attachment) { Guid networkId = attachment.getNetworkId(); String networkName = attachment.getNetworkName(); Guid violatingEntityId = attachment.getId(); START return validateCoherentIdentification(violatingEntityId == null ? null : violatingEntityId.toString(), END networkId, networkName, EngineMessage.NETWORK_ATTACHMENT_REFERENCES_NETWORK_INCOHERENTLY, networkBusinessEntityMap); } String.valueOf(str) does the same

Target:
private ValidationResult validateCoherentNetworkIdentification(NetworkAttachment attachment) { Guid networkId = attachment.getNetworkId(); String networkName = attachment.getNetworkName(); Guid violatingEntityId = attachment.getId(); return validateCoherentIdentification(String.valueOf(violatingEntityId), networkId, networkName, EngineMessage.NETWORK_ATTACHMENT_REFERENCES_NETWORK_INCOHERENTLY, networkBusinessEntityMap); }
Source:
public static Boolean getBoolean(String val) { if (val == null || val.trim().length() == 0) { return false; } try { return Boolean.valueOf(val); START } catch (Exception e) { END return false; } } What is the exception that you attempt to catch? Java doc says nothing about any exceptions from this method.

Target:
public static Boolean getBoolean(String val) { if (val == null || val.trim().length() == 0) { return false; } try { return Boolean.valueOf(val); } catch (IllegalArgumentException e) { return false; } }
Source:
private void send(String message){ //get client ReactorClient client = JsonRpcServer.getReactorClient(); //send message try { client.sendMessage(message.getBytes()); log.error("sending events message {}", message); }catch (ClientConnectionException e) { START log.error("Failure in sending response", e); END }finally { log.debug("send events"); } } ClientConnectionException mean that there are issues with network connection. Please consider reconnect logic here.

Target:
private void send(String message){ //get client ReactorClient client = JsonRpcServer.getReactorClient(); //send message try { client.sendMessage(message.getBytes()); log.debug("sending events message {}", message); }catch (ClientConnectionException e) { log.error("Failure in sending response", e); } }
Source:
public void addTask(TaskType t, long delay, Object o){ // support events, if enabled. try { //TODO: seems it better to use different thread. if (AppConfig.getInstance().isJsonEvents()){ START JsonRpcNotification jsonRpcNotification = new JsonRpcNotification(); END jsonRpcNotification.fireEvents(t, delay, o); }else{ //backward compatible. TaskProcessor.getInstance().addTask(new TaskRequest(t, delay, o)); } }catch (Exception e){ log.error("wrapping task error {}", e.toString()); } } Why to create JsonRpcNotification each time we want to fire an event? Please have it as instance variable for this class.

Target:
public static void addTask(TaskType t, long delay, Object o){ // support events, if enabled. try { //TODO: seems it better to use different thread. if (AppConfig.getInstance().isJsonEvents()){ JsonRpcNotification jsonRpcNotification = new JsonRpcNotification(); jsonRpcNotification.fireEvents(t, delay, o); }else{ //backward compatible. TaskProcessor.getInstance().addTask(new TaskRequest(t, delay, o)); } }catch (Exception e){ log.error("wrapping task error {}", e.toString()); } }
Source:
private void send(String message, String vmID, boolean removeClient) throws ClientConnectionException{ String hostName = null; try { //get client ReactorClient client = JsonRpcServer.getReactorsMap().get(vmID); START hostName = client.getHostname(); END //send message client.sendMessage(message.getBytes()); log.debug("sending events message {}", message); }catch (ClientConnectionException e) { log.error("Host {}, failed to send event message {}", hostName, e); } // remove client from the map in case the operation completed \ last event was sent. if (removeClient){ JsonRpcServer.removeReactorsMap(vmID); } } we need hostName only to log error. Please call it there.

Target:
private void send(String message, String vmID, boolean removeClient) throws ClientConnectionException{ ReactorClient client = null; try { //get client client = JsonRpcServer.getReactorsMap().get(vmID); //send message client.sendMessage(message.getBytes()); log.debug("sending events message {}", message); }catch (ClientConnectionException e) { log.error("Host {}, failed to send event message {}", client.getHostname(), e); } // remove client from the map in case the operation completed \ last event was sent. if (removeClient){ JsonRpcServer.removeReactorsMap(vmID); } }
Source:
public START static void END setReactorsMap(String vmId, ReactorClient client){ reactorsMap.put(vmId, client); } Map should not be static. There us only single instance of JsonRpcServer so we can pass it around and call instance methods.

Target:
public void setReactorsMap(String vmId, ReactorClient client){ reactorsMap.put(vmId, client); }
Source:
public synchronized static void START setReactorsMap(String END vmId, ReactorClient client){ reactorsMap.put(vmId, client); } Lack of consistency in naming. Please fix.

Target:
public static void setReactorsMap(String vmId, ReactorClient client){ reactorsMap.put(vmId, client); }
Source:
public void sendNotification(String message, String id){ if (message == null){ log.warn("empty message has arrived, ignore empty messages"); return; } //generate message message = messageFormatter(message, id); //send START send(message); END } What about: send(messageFormatter(message, id));

Target:
public void sendNotification(String message, String id){ if (message == null){ log.warn("empty message has arrived, ignore empty messages"); return; } //send send(messageFormatter(message, id)); }
Source:
private ValidationResult validateStatus(VDSStatus hostStatus) { return ValidationResult.failWith(EngineMessage.ACTION_TYPE_FAILED_VDS_STATUS_ILLEGAL, ReplacementUtils.createSetVariableString("hostStatus", host.getStatus().name())) START .unless(hostStatus == host.getStatus()); END } errata: I beg you pardon; by 'declarative programming' phrase I of course meant 'imperative programming'.

Target:
private ValidationResult validateStatus(VDSStatus hostStatus) { return ValidationResult.failWith(EngineMessage.ACTION_TYPE_FAILED_VDS_STATUS_ILLEGAL, ReplacementUtils.createSetVariableString("hostStatus", hostStatus.name())) .unless(hostStatus == host.getStatus()); }
Source:
private void updateModifiedInterfaces() { List<VdsNetworkInterface> nicsForUpdate = prepareNicsForUpdate(); START List<Guid> updateNicsIds = Entities.getIds(nicsForUpdate); END if (!nicsForUpdate.isEmpty()) { interfaceDao.massClearNetworkFromNics(updateNicsIds); interfaceDao.massUpdateInterfacesForVds(getNicsForUpdate()); } } albeit not related to this patch - shouldn't be called explicitly, but via its getter.

Target:
private void updateModifiedInterfaces() { List<VdsNetworkInterface> nicsForUpdate = getNicsForUpdate(); List<Guid> updateNicsIds = Entities.getIds(nicsForUpdate); if (!nicsForUpdate.isEmpty()) { interfaceDao.massClearNetworkFromNics(updateNicsIds); interfaceDao.massUpdateInterfacesForVds(nicsForUpdate); } }
Source:
public Api getConnection() throws UnsecuredConnectionAttemptError, ServerException, IOException { START if (api == null) { END String url = String.format("%s://%s:%s/ovirt-engine/api", protocol, server, port); log.debug(String.format("Logging to %s as %s", url, username)); api = new Api(url, username, password, true); } return api; } I guess we need thread safety here. wouldn't it be simpler to eagerly set the api? and OvirtClient should become a singleton. even a @Singleton

Target:
public synchronized Api getConnection() throws UnsecuredConnectionAttemptError, ServerException, IOException { if (api == null) { String url = String.format("%s://%s:%s/ovirt-engine/api", protocol, server, port); log.debug(String.format("Logging to %s as %s", url, username)); api = new Api(url, username, password, true); } return api; }
Source:
START @Override public void setEnabled(boolean enabled) { END label.setEnabled(enabled); if (contentWidget instanceof HasEnabled) { HasEnabled enableableWidget = (HasEnabled) this.contentWidget; enableableWidget.setEnabled(enabled); } } we typically write the annotations on separate line

Target:
public void setEnabled(boolean enabled) { label.setEnabled(enabled); if (contentWidget instanceof HasEnabled) { HasEnabled enableableWidget = (HasEnabled) this.contentWidget; enableableWidget.setEnabled(enabled); } }
Source:
public void testEvalNegative() { START Mockito.when(mockExternalNetworkPredicate.eval(mockNetwork)).thenReturn(true); END assertFalse(underTest.eval(mockNetwork)); } please use static import

Target:
public void testEvalNegative() { when(mockExternalNetworkPredicate.eval(mockNetwork)).thenReturn(true); assertFalse(underTest.eval(mockNetwork)); }
Source:
protected void onShowErrata() { START logger.info(this.getClass().toString() + " onShowErrata"); //$NON-NLS-1$ END if (getWindow() != null) { return; } HostErrataCountModel transferObj = new HostErrataCountModel(); transferObj.setTitle(messages.errataForHost(getName())); transferObj.setGuid(getGuid()); transferObj.setName(getName()); setWindow(transferObj); initCommands(transferObj); } This should be logger.debug or trace

Target:
protected void onShowErrata() { if (getWindow() != null) { return; } HostErrataCountModel transferObj = new HostErrataCountModel(); transferObj.setTitle(messages.errataForHost(getName())); transferObj.setGuid(getGuid()); transferObj.setName(getName()); setWindow(transferObj); initCommands(transferObj); }
Source:
protected PlaceRequest getMainTabRequest() { START logger.info(this.getClass().toString() + " getMainTabRequest"); //$NON-NLS-1$ END return PlaceRequestFactory.get(WebAdminApplicationPlaces.errataMainTabPlace); } this should be debug/trace, or better no be here at all.

Target:
protected PlaceRequest getMainTabRequest() { return PlaceRequestFactory.get(WebAdminApplicationPlaces.errataMainTabPlace); }
Source:
protected void fireTableSelectionChangeEvent() { START logger.info(this.getClass().toString() + " fireTableSelectionChangeEvent"); //$NON-NLS-1$ END ErrataSelectionChangeEvent.fire(this, getSelectedItems()); } debug/trace/remove?

Target:
protected void fireTableSelectionChangeEvent() { ErrataSelectionChangeEvent.fire(this, getSelectedItems()); }
Source:
public void onErratumSelectionChange(ErrataSelectionChangeEvent event) { START logger.info(this.getClass().toString() + " onErratumSelectionChange"); //$NON-NLS-1$ END updateMainTabSelection(event.getSelectedItems()); } debug/trace/remove?

Target:
public void onErratumSelectionChange(ErrataSelectionChangeEvent event) { updateMainTabSelection(event.getSelectedItems()); }
Source:
public SubTabHostGeneralHostErrataPresenter(EventBus eventBus, ViewDef view, ProxyDef proxy, PlaceManager placeManager, DetailTabModelProvider<HostListModel<Void>, HostErrataCountModel> errataCountModelProvider) { super(eventBus, view, proxy, placeManager, errataCountModelProvider, HostGeneralSubTabPanelPresenter.TYPE_SetTabContent); currentErrataModel = getModelProvider().getModel(); START logger.info("SubTabHostGeneralHostErrataPresenter created: " + this.toString()); //$NON-NLS-1$ END } debug/trace/remove?

Target:
public SubTabHostGeneralHostErrataPresenter(EventBus eventBus, ViewDef view, ProxyDef proxy, PlaceManager placeManager, DetailTabModelProvider<HostListModel<Void>, HostErrataCountModel> errataCountModelProvider) { super(eventBus, view, proxy, placeManager, errataCountModelProvider, HostGeneralSubTabPanelPresenter.TYPE_SetTabContent); currentErrataModel = getModelProvider().getModel(); }
Source:
protected void onBind() { super.onBind(); START logger.info(this.getClass().toString() + " onBind"); //$NON-NLS-1$ END updateModel(currentErrataModel); getView().getTotalSecurity().setCommand(currentErrataModel.getShowSecurityCommand()); getView().getTotalBugFix().setCommand(currentErrataModel.getShowBugsCommand()); getView().getTotalEnhancement().setCommand(currentErrataModel.getShowEnhancementsCommand()); } debug/trace/remove?

Target:
protected void onBind() { super.onBind(); updateModel(currentErrataModel); getView().getTotalSecurity().setCommand(currentErrataModel.getShowSecurityCommand()); getView().getTotalBugFix().setCommand(currentErrataModel.getShowBugsCommand()); getView().getTotalEnhancement().setCommand(currentErrataModel.getShowEnhancementsCommand()); }
Source:
private void buildErrataDetailPanel() { errataDetailPanel = new FlowPanel(); errataDetailFormPanel = new GeneralFormPanel(); errataTitle = new Span(); errataTitle.setStyleName(style.errataTitleLabel()); FlowPanel errataTitlePanel = new FlowPanel(); errataTitlePanel.setStyleName(style.errataTitlePanel()); errataTitlePanel.add(errataTitle); errataDetailPanel.add(errataTitlePanel); START errataDetailPanel.setStyleName("testtest"); //$NON-NLS-1$ END errataDetailPanel.add(errataDetailFormPanel); } I am guessing this style name should be something else? especially since you have style defined.

Target:
private void buildErrataDetailPanel() { errataDetailPanel = new FlowPanel(); errataDetailFormPanel = new GeneralFormPanel(); errataTitle = new Span(); errataTitle.setStyleName(style.errataTitleLabel()); FlowPanel errataTitlePanel = new FlowPanel(); errataTitlePanel.setStyleName(style.errataTitlePanel()); errataTitlePanel.add(errataTitle); errataDetailPanel.add(errataTitlePanel); errataDetailPanel.add(errataDetailFormPanel); }
Source:
public void setErrataDetailPanelVisibilty(boolean visible) { START logger.info("updateErrataDetailPanelVisibilty"); //$NON-NLS-1$ END splitLayoutPanel.clear(); if (visible) { splitLayoutPanel.addSouth(errataDetailPanel, SOUTH_SIZE); } splitLayoutPanel.add(errataTableView); } debug/trace/remove?

Target:
public void setErrataDetailPanelVisibilty(boolean visible) { splitLayoutPanel.clear(); if (visible) { splitLayoutPanel.addSouth(errataDetailPanel, SOUTH_SIZE); } splitLayoutPanel.add(errataTableView); }
Source:
protected Pair<Boolean, EngineFault> runConnectionStorageToDomain(StorageDomain storageDomain, Guid vdsId, int type) { Guid poolId = Guid.Empty; if (storageDomain.getStoragePoolId() != null) { poolId = storageDomain.getStoragePoolId(); START } END return runConnectionStorageToDomain(storageDomain, vdsId, type, null, poolId); } you can just pass storageDomain.getStoragePoolId(), the called method is handling null pool id, please change that and rebase the patch. other than that seems good to me.

Target:
protected Pair<Boolean, EngineFault> runConnectionStorageToDomain(StorageDomain storageDomain, Guid vdsId, int type) { return runConnectionStorageToDomain(storageDomain, vdsId, type, null, storageDomain.getStoragePoolId()); }
Source:
protected void initConnectionList(boolean includeInactiveDomains) { Set<StorageDomainStatus> statuses; statuses = includeInactiveDomains ? EnumSet.of(StorageDomainStatus.Active, StorageDomainStatus.Unknown, StorageDomainStatus.Inactive) : EnumSet.of(StorageDomainStatus.Active, StorageDomainStatus.Unknown); _connections = DbFacade.getInstance() .getStorageServerConnectionDao() .getStorageConnectionsByStorageTypeAndStatus(getStoragePool().getId(), null, statuses); updateConnectionsTypeMap(); START updateConnectionMapForFiberChannel(); END } what about DisconnectHostFromStoragePoolServersCommand?

Target:
protected void initConnectionList(boolean includeInactiveDomains) { Set<StorageDomainStatus> statuses; statuses = includeInactiveDomains ? EnumSet.of(StorageDomainStatus.Active, StorageDomainStatus.Unknown, StorageDomainStatus.Inactive) : EnumSet.of(StorageDomainStatus.Active, StorageDomainStatus.Unknown); _connections = DbFacade.getInstance() .getStorageServerConnectionDao() .getStorageConnectionsByStorageTypeAndStatus(getStoragePool().getId(), null, statuses); updateConnectionsTypeMap(); updateConnectionMapForFiberChannel(statuses); }
Source:
START private Map<String, Object> buildVmGraphicsSpecParamsFromVm(Map<GraphicsType, GraphicsInfo> infos) { END Map<String, Object> specParamsFromVm = null; if (infos.containsKey(GraphicsType.SPICE)) { // harmless if added to VNC devices. Just noise. specParamsFromVm = new HashMap(); specParamsFromVm.put(VdsProperties.spiceFileTransferEnable, Boolean.toString(vm.isSpiceFileTransferEnabled())); specParamsFromVm.put(VdsProperties.spiceCopyPasteEnable, Boolean.toString(vm.isSpiceCopyPasteEnabled())); } return specParamsFromVm; } can infos be null? (the check in line 112 above implies it might be)

Target:
private Map<String, Object> buildVmGraphicsSpecParamsFromVm(Map<GraphicsType, GraphicsInfo> infos) { Map<String, Object> specParamsFromVm = null; if (infos != null && infos.containsKey(GraphicsType.SPICE)) { // harmless if added to VNC devices. Just noise. specParamsFromVm = new HashMap(); specParamsFromVm.put(VdsProperties.spiceFileTransferEnable, Boolean.toString(vm.isSpiceFileTransferEnabled())); specParamsFromVm.put(VdsProperties.spiceCopyPasteEnable, Boolean.toString(vm.isSpiceCopyPasteEnabled())); } return specParamsFromVm; }
Source:
public static boolean isGlusterfsCliInstalled(VDS vds) { if (FeatureSupported.glusterVolumeInfoSupported(getStoragePool(vds.getId()).getCompatibilityVersion())) { RpmVersion glusterfsCliVer = vds.getGlusterfsCliVersion(); START if (glusterfsCliVer == null || END glusterfsCliVer.getRpmRelease() == null || glusterfsCliVer.getRpmRelease().isEmpty()) { return false; } return true; } return true; } consider rephrasing to 'return !(condition)' or 'return (cond1 && cond2 && ...).

Target:
public static boolean isGlusterfsCliInstalled(VDS vds) { if (FeatureSupported.glusterVolumeInfoSupported(getStoragePool(vds.getId()).getCompatibilityVersion())) { RpmVersion glusterfsCliVer = vds.getGlusterfsCliVersion(); return glusterfsCliVer == null || glusterfsCliVer.getRpmRelease() == null || glusterfsCliVer.getRpmRelease().isEmpty(); } return true; }
Source:
private boolean registerLibvirtSecretsImpl(VDS vds, List<LibvirtSecret> libvirtSecrets, boolean clearUnusedSecrets) { VDSReturnValue returnValue = Backend.getInstance().getResourceManager().RunVdsCommand( VDSCommandType.RegisterLibvirtSecrets, new RegisterLibvirtSecretsVDSParameters(vds.getId(), libvirtSecrets, clearUnusedSecrets)); if (!returnValue.getSucceeded()) { START log.error("Failed to register libvirt secret on vds {}.", vds.getName()); END return false; } return true; } You already use this error at line 179, it will be shown twice. You can simply replace line 221-226 with return returnValue.getSucceeded;

Target:
private boolean registerLibvirtSecretsImpl(VDS vds, List<LibvirtSecret> libvirtSecrets, boolean clearUnusedSecrets) { VDSReturnValue returnValue = Backend.getInstance().getResourceManager().RunVdsCommand( VDSCommandType.RegisterLibvirtSecrets, new RegisterLibvirtSecretsVDSParameters(vds.getId(), libvirtSecrets, clearUnusedSecrets)); return returnValue.getSucceeded(); }
Source:
private String getPoolVmTooltip(VmType vmType) { switch (vmType) { case Server: return constants.pooledServer(); case Desktop: return constants.pooledDesktop(); default: START return ""; //$NON-NLS-1$ END } } please make this consistent with getPoolVmImageResource where the default case is fallthrough of Desktop.

Target:
private String getPoolVmTooltip(VmType vmType) { switch (vmType) { case Server: return constants.pooledServer(); case Desktop: return constants.pooledDesktop(); default: return constants.pooledDesktop(); } }
Source:
public Boolean getValue(ClusterNetworkModel clusterNetworkModel) { START return clusterNetworkModel.isAttached() && clusterNetworkModel.isRequired(); END } The view should display the model data, it shouldn't have logic for showing data that doesn't represent the model values. The root cause of the problem resides in- ClusterNetworkModel. public ClusterNetworkModel(Network network)->if (network.getCluster() == null)-> getEntity().setCluster(new NetworkCluster(/*isRequired*/!network.isExternal())); It means that in case of detached network the required value is true by default (in case of internal network), it should be changed to be false (no matter if the network is internal or external).

Target:
public Boolean getValue(ClusterNetworkModel clusterNetworkModel) { return clusterNetworkModel.isRequired(); }
Source:
public void execute(T t) { START return; END } Empty return isn't needed

Target:
public void execute(T t) { }
Source:
START private void assertDiskDescriptionMap(String diskAlias, String diskDescription) throws IOException { END assertEquals("Should be map of disk alias and disk description", String.format("{\"DiskAlias\":\"%s\"," + "\"DiskDescription\":\"%s\"}", diskAlias, StringUtils.defaultString(diskDescription)), ImagesHandler.getJsonDiskDescription(diskAlias, diskDescription)); } should be static - please fix when you rebase

Target:
private static void assertDiskDescriptionMap(String diskAlias, String diskDescription) throws IOException { assertEquals("Should be map of disk alias and disk description", String.format("{\"DiskAlias\":\"%s\"," + "\"DiskDescription\":\"%s\"}", diskAlias, StringUtils.defaultString(diskDescription)), ImagesHandler.getJsonDiskDescription(diskAlias, diskDescription)); }
Source:
public static void enrichDiskByJsonDescription(String jsonDiskDescription, Disk disk) throws IOException { Map<String, Object> diskDescriptionMap = JsonHelper.jsonToMap(jsonDiskDescription); disk.setDiskAlias((String) diskDescriptionMap.get(DISK_ALIAS)); START disk.setDiskDescription((String) diskDescriptionMap.get(DISK_DESCRIPTION)); END } This assumes that the json helper parses the values as strings. Let's play it safe and use toString() instead of a cast?

Target:
public static void enrichDiskByJsonDescription(String jsonDiskDescription, Disk disk) throws IOException { Map<String, Object> diskDescriptionMap = JsonHelper.jsonToMap(jsonDiskDescription); disk.setDiskAlias(diskDescriptionMap.get(DISK_ALIAS).toString()); disk.setDiskDescription(diskDescriptionMap.get(DISK_DESCRIPTION).toString()); }
Source:
private int getJsonFieldPotentialOverhead(String fieldName, Map<String, Object> descriptionMap) { return String.format("\"%s\":\"\"", fieldName).length() + START (descriptionMap.size() >= 1 ? 1 : 0); // for the comma. END } try to use descriptionMap.isEmpty instead

Target:
private int getJsonFieldPotentialOverhead(String fieldName, Map<String, Object> descriptionMap) { return String.format("\"%s\":\"\"", fieldName).length() + (descriptionMap.isEmpty() ? 0 : 1); // for the comma. }
Source:
protected boolean validate() { Guid nicId = getParameters().getNicId(); HostInterfaceValidator hostInterfaceValidator = new HostInterfaceValidator(getNic()); ValidationResult validationResult = hostInterfaceValidator.interfaceExists(nicId); if (!validationResult.isValid()) { return validate(validationResult); } START return validate(hostInterfaceValidator.nicIsNotLabeledWithSpecifiedLabel(getLabel())); END } Maybe- return validate(hostInterfaceValidator.interfaceExists(nicId)) && validate(hostInterfaceValidator.nicIsNotLabeledWithSpecifiedLabel(getLabel()));

Target:
protected boolean validate() { Guid nicId = getParameters().getNicId(); HostInterfaceValidator hostInterfaceValidator = new HostInterfaceValidator(getNic()); return validate(hostInterfaceValidator.interfaceExists(nicId)) && validate(hostInterfaceValidator.nicIsNotLabeledWithSpecifiedLabel(getLabel())); }
Source:
public GetDeviceListVDSCommandParameters(Guid vdsId, StorageType storageType) { super(vdsId); setStorageType(storageType); START setCheckStatus(false); END } This is becoming a bit clunk - just call this(... )

Target:
public GetDeviceListVDSCommandParameters(Guid vdsId, StorageType storageType) { this(vdsId, storageType, false, null); }
Source:
private void assertDiskDescriptionMap(Disk disk) throws IOException { assertEquals("Should be map of disk alias and disk description", String.format("{\"DiskAlias\":\"%s\"," + START "\"DiskDescription\":\"%s\"}", END disk.getDiskAlias(), StringUtils.defaultString(disk.getDiskDescription())), MetadataDiskDescriptionHandler.getJsonDiskDescription(disk)); } You can try to use the static fields at MetadataDiskDescriptionHandler, this way, it will be more related to the real scenario which we are testing.

Target:
private static void assertDiskDescriptionMap(Disk disk) throws IOException { assertEquals("Should be map of disk alias and disk description", String.format("{\"DiskAlias\":\"%s\"," + "\"DiskDescription\":\"%s\"}", disk.getDiskAlias(), StringUtils.defaultString(disk.getDiskDescription())), MetadataDiskDescriptionHandler.getJsonDiskDescription(disk)); }
Source:
START private static Set<String> getHostEmulatedMachines(VDS vds) { END return new HashSet<>(Arrays.asList(vds.getSupportedEmulatedMachines().split(","))); } any chance same approach should be taken here ?

Target:
private static Set<String> getHostEmulatedMachines(VDS vds) { if (vds.getSupportedEmulatedMachines() == null) { return new HashSet<>(); } else { return new HashSet<>(Arrays.asList(vds.getSupportedEmulatedMachines().split(","))); } }
Source:
private boolean isNetmaskInSync() { return ObjectUtils.objectsEqual(iface.getSubnet(), START isPrimaryAddressExist() ? networkDataCenterIpConfigurationDefinition.getPrimaryAddress().getNetmask() END : null); } extract method for getting primary address would make these lines shorter.

Target:
private boolean isNetmaskInSync() { return ObjectUtils.objectsEqual(iface.getSubnet(), isPrimaryAddressExist() ? getPrimaryAddress().getNetmask() : null); }
Source:
private void initGraphicsData() { ImportUtils.updateGraphicsDevices(getVm().getStaticData(), START getVdsGroup() != null ? getVdsGroup().getCompatibilityVersion() : null); END } no need to check that getVdsGroup is not null - already done in ImportVmCommandBase#canDoAction

Target:
private void initGraphicsData() { ImportUtils.updateGraphicsDevices(getVm().getStaticData(), getVdsGroup().getCompatibilityVersion()); }
Source:
public void setUpSessionDataContainer() { MockitoAnnotations.initMocks(this); if (Config.getConfigUtils() == null) { Config.setConfigUtils(mock(IConfigUtilsInterface.class)); } START when(Config.getConfigUtils().getValue(ConfigValues.CoCoCommandLifeInMinutes, ConfigCommon.defaultConfigurationVersion)).thenReturn(300); END } pls use formatter

Target:
public void setUpSessionDataContainer() { MockitoAnnotations.initMocks(this); }
Source:
public void setUp() { when(model.getProgress()).thenReturn(null, progressModel); Config.setConfigUtils(mock(IConfigUtilsInterface.class)); START when(Config.getConfigUtils().getValue(ConfigValues.CoCoCommandLifeInMinutes, ConfigCommon.defaultConfigurationVersion)).thenReturn(300); END } formatter?

Target:
public void setUp() { when(model.getProgress()).thenReturn(null, progressModel); }
Source:
START protected void setBondingOptions(ListModel<Map.Entry<String, EntityModel<String>>> value) { END privateBondingOptions = value; } Why did you change the modifier? If you want to change the list of bondingOptions, isn't is enough to do- 'getBondingOptions().setItems(newBondingOptions)'?

Target:
private void setBondingOptions(ListModel<Map.Entry<String, EntityModel<String>>> value) { privateBondingOptions = value; }
Source:
public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { super.eventRaised(ev, sender, args); if (ev.matchesDefinition(RegistrationResult.RetrievedEventDefinition)) { asyncResult_Retrieved(); } if (ev.matchesDefinition(ProvideTickEvent.definition)) { syncSearch(); } START entityModel.eventRaised(ev, sender, args); END } probably just to be a little more defensive we could put this call just after 'super()' call since we want to treat EntityModel as our ancestor (as was before)

Target:
public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { super.eventRaised(ev, sender, args); entityModel.eventRaised(ev, sender, args); if (ev.matchesDefinition(RegistrationResult.RetrievedEventDefinition)) { asyncResult_Retrieved(); } if (ev.matchesDefinition(ProvideTickEvent.definition)) { syncSearch(); } }
Source:
START protected boolean shouldAddVlanToNic(VdsNetworkInterface vlan) { END return true; } The following code can be valid here as well- protected boolean shouldAddVlanToNic(VdsNetworkInterface vlan) { return vlan.getId()==null; }

Target:
private boolean shouldAddVlanToNic(VdsNetworkInterface vlan) { return vlan.getId()==null; }
Source:
protected boolean canDoAction() { StorageServerConnectionExtension newConnExt = getParameters().getStorageServerConnectionExtension(); START return validate(getConnectionExtensionValidator().isConnectionDoesNotExistForHostAndTarget(newConnExt.getHostId(), END newConnExt.getIqn())); } I'd do this in the previous patch already

Target:
protected boolean canDoAction() { StorageServerConnectionExtension newConnExt = getParameters().getStorageServerConnectionExtension(); return validate(getConnectionExtensionValidator().isConnectionDoesNotExistForHostAndTarget(newConnExt)); }
Source:
protected void updateWipeAfterDeleteChangeability() { if (isVmAttachedToPool()) { getIsWipeAfterDelete().setIsChangeable(false); } else { START getIsWipeAfterDelete().setIsChangeable(true); END } } so just use getIsWipeAfterDelete().setIsChangeable(!isVmAttachedToPool());

Target:
protected void updateWipeAfterDeleteChangeability() { getIsWipeAfterDelete().setIsChangeable(!isVmAttachedToPool()); }
Source:
public List<VdsNetworkInterface> getNics(Guid hostId) { if (!hostIdToNics.containsKey(hostId)) { VDS host = new VDS(); host.setId(hostId); NetworkConfigurator configurator = new NetworkConfigurator(host, commandContext); START hostIdToNics.put(hostId, configurator.filterBondsWithoutSlaves(interfaceDao.getAllInterfacesForVds(hostId))); END } return hostIdToNics.get(hostId); } it seems, that filterBondsWithoutSlaves is not interrested in 'host' and neither in commandContext. we can make at least the method static — that's easy although ugly and goes against CDI. Better would be to move this method to different class. Please notice, that this class requires commandContext although it's only usage is this fake one. So doing this change will simplify this method, heal NetworkConfigurator, simplify this class constructor, and all descendants.

Target:
public List<VdsNetworkInterface> getNics(Guid hostId) { if (!hostIdToNics.containsKey(hostId)) { VDS host = new VDS(); host.setId(hostId); NetworkConfigurator configurator = new NetworkConfigurator(host, null); hostIdToNics.put(hostId, configurator.filterBondsWithoutSlaves(interfaceDao.getAllInterfacesForVds(hostId))); } return hostIdToNics.get(hostId); }
Source:
protected void loadVmInit() { START if (!getVm().isInitialized() && getVm().getVmInit() == null) { END VmHandler.updateVmInitFromDB(getVm().getStaticData(), false); } } why we need to check for getVm().isInitialized() ?

Target:
protected void loadVmInit() { if (getVm() != null && getVm().getVmInit() == null) { VmHandler.updateVmInitFromDB(getVm().getStaticData(), false); } }
Source:
protected Integer parseNodeInteger(XmlNode sourceNode, String string, Integer defaultValue) { XmlNode subNode = selectSingleNode(sourceNode, string, _xmlNS); if (subNode != null && subNode.innerText != null) { Integer ret = Integer.parseInt(subNode.innerText); START return ret; END } return defaultValue; } please inline, no need for the 'ret' variable

Target:
protected Integer parseNodeInteger(XmlNode sourceNode, String string, Integer defaultValue) { XmlNode subNode = selectSingleNode(sourceNode, string, _xmlNS); if (subNode != null && subNode.innerText != null) { return Integer.parseInt(subNode.innerText); } return defaultValue; }
Source:
public IntegerValidation() { START super(Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.class); END } Here, you can simply call the other constructor: this(Integer.MIN_VALUE, Integer.MAX_VALUE);

Target:
public IntegerValidation() { this(Integer.MIN_VALUE, Integer.MAX_VALUE); }
Source:
protected void executeCommand() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getCompensationContext().snapshotEntity(getVmPool()); setPoolBeingDestroyed(); setPrestartedToZero(); getCompensationContext().stateChanged(); return null; } }); setCommandShouldBeLogged(false); // disable logging at the end of command execution log(); // and log the message now stopVms(); if (allVmsDown) { START getParameters().setTaskGroupSuccess(true); END endSuccessfully(); } else { setSucceeded(true); } } this line is redundant now that you call endSuccessfully directly

Target:
protected void executeCommand() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getCompensationContext().snapshotEntity(getVmPool()); setPoolBeingDestroyed(); setPrestartedToZero(); getCompensationContext().stateChanged(); return null; } }); setCommandShouldBeLogged(false); // disable logging at the end of command execution log(); // and log the message now stopVms(); if (allVmsDown) { endSuccessfully(); } else { setSucceeded(true); } }
Source:
START private StorageDomainSharedStatus getStorageDomainSharedStatus() { StorageDomainSharedStatus status = null; if (getStorageDomain() != null) { status = getStorageDomain().getStorageDomainSharedStatus(); } return status; } END You consider following syntax: return getStorageDomain() == null ? null : getStorageDomain().getStorageDomainSharedStatus()

Target:
private StorageDomainSharedStatus getStorageDomainSharedStatus() { return getStorageDomain() == null ? null : getStorageDomain().getStorageDomainSharedStatus(); }
Source:
protected void addStorageDomainStatusIllegalMessage() { addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2); StorageDomainStatus status = getStorageDomainStatus(); StorageDomainSharedStatus sharedStatus = getStorageDomainSharedStatus(); START Object messageParameter; if (status == StorageDomainStatus.Unknown && sharedStatus != null) { // We got more informative information than "Unknown". messageParameter = sharedStatus; } else { messageParameter = status; } END addCanDoActionMessageVariable("status", messageParameter); } You can initialize messageParameter with status, i.e: Object messageParameter = getStorageDomainStatus(); And then do the check: if (messageParameter == Unknown && sharedStatus != null) { messageParameter = sharedStatus; } This way you can save the 'else' part. BTW, if the call to getStorageDomainSharedStatus() is expensive, you may want to save it by first validating that getStorageDomainStatus() is not Unknown: Object messageParameter = getStorageDomainStatus(); if (messageParameter == Unknown) { SDSharedStatus sharedStatus = getSDSharedStatus(); if (sharedStatus != null) { messageParameter = sharedStatus; } } addCanDo ...

Target:
protected void addStorageDomainStatusIllegalMessage() { addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2); StorageDomainStatus status = getStorageDomainStatus(); StorageDomainSharedStatus sharedStatus = getStorageDomainSharedStatus(); Object messageParameter = status; if (status == StorageDomainStatus.Unknown && sharedStatus != null) { // We got more informative information than "Unknown". messageParameter = sharedStatus; } addCanDoActionMessageVariable("status", messageParameter); }
Source:
public static EngineError forValue(int value) { START return mappings.getOrDefault(value, ERROR_CODE_NOT_FOUND); END } getOrDefault was introduced in java 8 - this class is being compiled to gwt which supports 1.7. You should implement the behavior yourself.

Target:
public static EngineError forValue(int value) { return mappings.containsKey(value) ? mappings.get(value) : ERROR_CODE_NOT_FOUND; }
Source:
private void initAllModels(boolean fetchFromBackend) { if (fetchFromBackend) { // run query for networks, this chains the query for nics, and also stops progress when done startProgress(); queryLabels(); START queryVfMap(); END } else { initLabelModels(); initNetworkModels(); initNicModels(); } } queryLabels invokes a chain of queries that the final one initiates the class models. You should add your query to the chain (it can be the last one). Your query cannot be parallel to the chain since there is chance the chain will be finished before your query comes back. It will cause NPE in the models initialization since it assumes vfMap is not null.

Target:
private void initAllModels(boolean fetchFromBackend) { if (fetchFromBackend) { // run query for networks, this chains the query for nics, and also stops progress when done startProgress(); queryLabels(); } else { initLabelModels(); initNetworkModels(); initNicModels(); } }
Source:
protected boolean canDoAction() { final VM vm = getVm(); START if (vm == null) { END return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_VM_NOT_FOUND); } if (!canRunActionOnNonManagedVm()) { return false; } if (getVm().getStatus() != VMStatus.Up && getVm().getStatus() != VMStatus.PoweringUp) { return failVmStatusIllegal(); } return true; } please inline (I see you'r'e using getVm() later on)

Target:
protected boolean canDoAction() { if (getVm() == null) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_VM_NOT_FOUND); } if (!canRunActionOnNonManagedVm()) { return false; } if (getVm().getStatus() != VMStatus.Up && getVm().getStatus() != VMStatus.PoweringUp) { return failVmStatusIllegal(); } return true; }
Source:
protected boolean runVm(Guid vmId, EngineLock lock) { return backend.runInternalAction( VdcActionType.RunVm, new RunVmParams(vmId), ExecutionHandler.createInternalJobContext(lock)).getSucceeded(); START } END why did you reorder the methods? 1. it makes it harder to review the patch 2. methods that are not that interesting like getVmDynamicDao appear before the interesting methods in this class such as startFailedAutoStartVms

Target:
private boolean runVm(Guid vmId, EngineLock lock) { return backend.runInternalAction( VdcActionType.RunVm, new RunVmParams(vmId), ExecutionHandler.createInternalJobContext(lock)).getSucceeded(); }
Source:
public boolean isStrict() { START return value == STRICT.value ? true : false; END } sed 's/value == STRICT.value ? true : false/value == STRICT.value/' (Redundant inline if)

Target:
public boolean isStrict() { return value == STRICT.value; }
Source:
START public static BondMode getBondMode(String bondOptions){ END if(bondOptions == null){ return null; } String bondModeValue = findMode(bondOptions); if (bondModeValue == null){ return null; } for (BondMode bondMode : BondMode.values()){ if (bondMode.getValue().equals(bondModeValue)){ return bondMode; } } return null; } It is still public. Why?

Target:
static BondMode getBondMode(String bondOptions){ if(bondOptions == null){ return null; } String bondModeValue = findMode(bondOptions); if (bondModeValue == null){ return null; } for (BondMode bondMode : BondMode.values()){ if (bondMode.getValue().equals(bondModeValue)){ return bondMode; } } return null; }
Source:
START public static BondMode getBondMode(String bondOptions){ END if(bondOptions == null){ return BOND0; } String bondModeValue = findMode(bondOptions); if (bondModeValue == null){ return BOND0; } for (BondMode bondMode : BondMode.values()){ if (bondMode.getValue().equals(bondModeValue)){ return bondMode; } } return BOND0; } Please check if the are any usages of this method outside this class. If not, please make it private.

Target:
public static BondMode getBondMode(String bondOptions){ if(bondOptions == null){ return null; } String bondModeValue = findMode(bondOptions); if (bondModeValue == null){ return null; } for (BondMode bondMode : BondMode.values()){ if (bondMode.getValue().equals(bondModeValue)){ return bondMode; } } return null; }
Source:
public CreateUserSessionParameters(String ssoToken, String profileName, String principalName, String principalId, String email, String sourceIp, List<Map> groupIds, boolean adminRequired) { setSsoToken(ssoToken); setProfileName(profileName); setPrincipalName(principalName); setPrincipalId(principalId); setEmail(email); // setSourceIp(sourceIp); START setSourceIp("fe80::56ee:75ff:fe5c:6cc7"); END setGroupIds(groupIds); setAdminRequired(adminRequired); } please fix

Target:
public CreateUserSessionParameters(String ssoToken, String profileName, String principalName, String principalId, String email, String sourceIp, List<Map> groupIds, boolean adminRequired) { setSsoToken(ssoToken); setProfileName(profileName); setPrincipalName(principalName); setPrincipalId(principalId); setEmail(email); setSourceIp(sourceIp); setGroupIds(groupIds); setAdminRequired(adminRequired); }
Source:
START private NetworkClusterDao getNetworkClusterDao() { END return DbFacade.getInstance().getNetworkClusterDao(); } The removal of the static causes the patch to fail compilation.

Target:
private static NetworkClusterDao getNetworkClusterDao() { return DbFacade.getInstance().getNetworkClusterDao(); }
Source:
public Response add(SchedulingPolicy schedulingPolicy) { // Allow the usage of "policy" for backward-compatibility if (!schedulingPolicy.isSetName()){ schedulingPolicy.setName(schedulingPolicy.getPolicy()); START } END validateParameters(schedulingPolicy, "name"); return performCreate(VdcActionType.AddClusterPolicy, new ClusterPolicyCRUDParameters(null, map(schedulingPolicy)), queryIdResolver); } This is done by the mapper, so we don't need to do it again here. In addition we don't need to support the "policy" attribute when adding scheduling policies, only when changing the policy of a cluster.

Target:
public Response add(SchedulingPolicy schedulingPolicy) { validateParameters(schedulingPolicy, "name"); return performCreate(VdcActionType.AddClusterPolicy, new ClusterPolicyCRUDParameters(null, map(schedulingPolicy)), queryIdResolver); }
Source:
START public boolean isEmptyOrNullAllowed() { END return emptyOrNullAllowed; } If we need this method for unit tests only, it can have default (package) visibility instead of public: boolean isEmptyOrNullAllowed() { ... }

Target:
boolean isEmptyOrNullAllowed() { return emptyOrNullAllowed; }
Source:
public static Version getEffective(Version vmCustomCompatibilityVersion, Version vdsGroupCompatibilityVersion, Version defaultVersion) { if (vmCustomCompatibilityVersion != null) { return vmCustomCompatibilityVersion; } else if (vdsGroupCompatibilityVersion != null) { return vdsGroupCompatibilityVersion; } else { return defaultVersion; START } END } I find it more readable as: if (vmCustomCompatibilityVersion != null) { return vmCustomCompatibilityVersion; } if (vdsGroupCompatibilityVersion != null) { return vdsGroupCompatibilityVersion; } return defaultVersion; please consider

Target:
public static Version getEffective(Version vmCustomCompatibilityVersion, Version vdsGroupCompatibilityVersion, Version defaultVersion) { if (vmCustomCompatibilityVersion != null) { return vmCustomCompatibilityVersion; } if (vdsGroupCompatibilityVersion != null) { return vdsGroupCompatibilityVersion; } return defaultVersion; }
Source:
private Guid getNewMacPoolId() { //TODO MM: this feels as duplicate to code in 'getPermissionCheckSubjects' but I'm not sure if // I can get null-valued storagePool elsewhere than in getPermissionSubjects. START return getParameters().getStoragePool().getMacPoolId(); END } Why not using "getNewMacPoolId()" in getPermissionCheckSubjects as well (please notice there is also a null check- 'getParameters().getStoragePool() == null', please add it here as well).

Target:
private Guid getNewMacPoolId() { return getParameters().getStoragePool() == null ? null : getParameters().getStoragePool().getMacPoolId(); }
Source:
protected void executeCommand() { // This will cache the snapshot names, avoiding '<UNKNOWN>' in the audit log upon command completion START getSnapshotsNames(); END if (isLiveMerge()) { getParameters().setLiveMerge(true); persistCommand(getParameters().getParentCommand(), true); } removeCinderSnapshotDisks(); setSucceeded(true); } Is it mandatory? The names should be already cached upon calling 'addAuditLogCustomValues', which is invoked on CommandBase's execute flow (execute -> logCommand).

Target:
protected void executeCommand() { if (isLiveMerge()) { getParameters().setLiveMerge(true); persistCommand(getParameters().getParentCommand(), true); } removeCinderSnapshotDisks(); setSucceeded(true); }
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof OpenstackNetworkProviderProperties)) { return false; } OpenstackNetworkProviderProperties other = (OpenstackNetworkProviderProperties) obj; return super.equals(obj) && Objects.equals(pluginType, START pluginType) END && Objects.equals(agentConfiguration, other.agentConfiguration); } I guess you forgot "other." prefix

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof OpenstackNetworkProviderProperties)) { return false; } OpenstackNetworkProviderProperties other = (OpenstackNetworkProviderProperties) obj; return super.equals(obj) && Objects.equals(pluginType, other.pluginType) && Objects.equals(agentConfiguration, other.agentConfiguration); }
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof IconWithOsDefault)) START return false; END IconWithOsDefault other = (IconWithOsDefault) obj; return Objects.equals(icon, other.icon) && Objects.equals(osDefaultIcon, other.osDefaultIcon) && Objects.equals(smallIconId, other.smallIconId) && Objects.equals(validationResult, other.validationResult); } missing { and }

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof IconWithOsDefault)) { return false; } IconWithOsDefault other = (IconWithOsDefault) obj; return Objects.equals(icon, other.icon) && Objects.equals(osDefaultIcon, other.osDefaultIcon) && Objects.equals(smallIconId, other.smallIconId) && Objects.equals(validationResult, other.validationResult); }
Source:
public int hashCode() { return Objects.hash( forceMigrationForNonMigratableVm, getVmId(), targetVdsGroupId ); START } END it is not that good - let's say I add a field in VmOperationParameterBase then I'll need to go over all the classes that inherit it to add the new field in their hashCode?

Target:
public int hashCode() { return Objects.hash( super.hashCode(), forceMigrationForNonMigratableVm, targetVdsGroupId ); }
Source:
public void testInvalidParameterKey() { try { String key = "version=1;uuid=12345610-0000-0000-0000-000000000001"; DataMapKey deserializedParam = DataMapKey.deserialize(key); fail("InvalidParameterKeyException should have been raised"); START } catch (InvalidPersistentMapKeyException e) { END assertNotNull(e); } } please use @Test(expected=InvalidPersistentMapKeyException.class) instead of try{} catch

Target:
public void testInvalidParameterKey() { String key = "version=1;uuid=12345610-0000-0000-0000-000000000001"; DataMapKey deserializedParam = DataMapKey.deserialize(key); fail("InvalidParameterKeyException should have been raised"); }
Source:
private List<VM> getMigratableVmsRunningOnVds(final VmDao vmDao, final Guid hostId) { List<VM> vmsFromDB = vmDao.getAllRunningForVds(hostId); return vmsFromDB.stream() .filter( START v -> END v.getMigrationSupport() == MigrationSupport.MIGRATABLE // must not be pinned to the host && !v.getDedicatedVmForVdsList().contains(hostId) ).collect(Collectors.toList()); } while on it can you please rename v to vm ?

Target:
private List<VM> getMigratableVmsRunningOnVds(final VmDao vmDao, final Guid hostId) { List<VM> vmsFromDB = vmDao.getAllRunningForVds(hostId); return vmsFromDB.stream() .filter( vm -> vm.getMigrationSupport() == MigrationSupport.MIGRATABLE // must not be pinned to the host && !vm.getDedicatedVmForVdsList().contains(hostId) ).collect(Collectors.toList()); }