auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void updateNetworks(final Guid vmId, final List<NicWithLogicalNetworks> nicsWithLogicalNetworks) { ArrayList<VdcActionParametersBase> parameters = createAddVmInterfaceParams(vmId, nicsWithLogicalNetworks); if (parameters.size() == 0) { callback.networkCreated(); return; } updateNetworksFromParams(vmId, parameters); }

Target:
updateNetworksFromParams() has the same code. Why do you also need it here?
Source:
private void onSave() { if (!validate()) { return; } flush(); Frontend.RunAction(action, new ProviderParameters(provider), null, true); cancel(); }

Target:
Why do you need this addition? Isn't it the default?
Source:
protected boolean canDoAction() { boolean retValue = true; if (getParameters().getDescription().trim().length()==0) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_EMPTY_DESCRIPTION); retValue = false; } return retValue; }

Target:
StringUtils.isEmpty ?
Source:
public TimeZoneType getTimeZoneType() { VmOsType vmOsType = (VmOsType) getModel().getOSType().getSelectedItem(); return vmOsType == null ? TimeZoneType.GENERAL_TIMEZONE : TimeZoneType.getTimeZoneByOs(vmOsType); }

Target:
Yes, this will solve the NPE, but if I may suggest that better place for this null check should actually be inside the TimeZoneType.getTimeZoneByOs method, to avoid similar omissions in the future. It makes sense for getTimeZoneByOs to return GENERAL_TIMEZONE if the osType is unspecified.
Source:
public void toFile(String krb5ConfPath, StringBuffer sb) throws FileNotFoundException, IOException { FileOutputStream fos = null; try { fos = new FileOutputStream(krb5ConfPath); fos.write(sb.toString().getBytes()); } finally { if (fos != null) { fos.close(); } } }

Target:
consider doing: try (FileOutputStream fos = new FileOutputStream(krb5ConfPath)) { fos.write(sb.toString().getBytes()); } which is equivalent to the above, with less lines of code :-)
Source:
private void validateGateway(VdsNetworkInterface iface) { if (!FeatureSupported.multipleGatewaysSupported(vds.getVdsGroupCompatibilityVersion()) && !NetworkUtils.isManagementNetwork(iface.getNetworkName()) && StringUtils.isNotEmpty(iface.getGateway())) { addViolation(VdcBllMessages.NETWORK_ATTACH_ILLEGAL_GATEWAY, iface.getNetworkName()); } }

Target:
please revert the order of conditions from static validation to validation which requires fetching value from DB: private void validateGateway(VdsNetworkInterface iface) {if (StringUtils.isNotEmpty(iface.getGateway()) && !NetworkUtils.isManagementNetwork(iface.getNetworkName()) && !FeatureSupported.multipleGatewaysSupported(vds.getVdsGroupCompatibilityVersion()) ) { ... }
Source:
public boolean validateDistributedStripedReplicateRemove(GlusterVolumeType volumeType, List<GlusterBrickEntity> selectedBricks, List<GlusterBrickEntity> brickList, RemoveBrickModel removeBrickModel) { int stripeCount = removeBrickModel.getStripeCount(); int replicaCount = removeBrickModel.getReplicaCount(); if (selectedBricks.size() != stripeCount * replicaCount) { return false; } return true; }

Target:
is it possible to remove multiple distribution groups in a single shot? If yes, then there is problem with the above logic.
Source:
private void cleanConnection(StorageServerConnections connection, Guid hostId) { // if create connection command was the one to fail and didn't create a connection // then the id of connection will be empty, and there's nothing to delete. if (connection.getid()!=null && !connection.getid().equalsIgnoreCase("")) { Frontend.RunAction(VdcActionType.RemoveStorageServerConnection, new StorageServerConnectionParametersBase(connection, hostId), null, this); } }

Target:
there is no point in case sensitive check for an empty string. Also, just use StringUtils.isEmpty(connection.getId())
Source:
public UpdateVmCommand(T parameters) { super(parameters); if (getVdsGroup() != null) { setStoragePoolId(getVdsGroup().getStoragePoolId()); } if (isVmExist()) { setCustomDefinedProperties(parameters.getVmStaticData()); setCustomDefinedProperties(getVm().getStaticData()); } if (parameters.isConsoleEnabled() == null) { parameters.setConsoleEnabled(false); } }

Target:
i think on update we should use null as "don't touch device setting" (if its there leave it, if not don't create)
Source:
public List<AsyncTasks> getTasksByEntity(Guid entityId) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource(); parameterSource.addValue("entity_id", entityId); return getCallsHandler().executeReadList("GetAsyncTasksByEntityId", AsyncTaskRowMapper.instance, parameterSource); }

Target:
I'd inline this - MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("entity_id", entityId);
Source:
public static String getMessage(final String key) { return getMessage(key, LocaleFilter.DEFAULT_LOCALE); }

Target:
Why is this method static? Only singleton access methods like getInstance() should be static.
Source:
public static BrandingManager getInstance(final File etcDir) { if (instance == null) { instance = new BrandingManager(etcDir); } return instance; }

Target:
oh behalf of Michael Pasternak: about [1], i'd consider synchronizing writes at getInstance() & getInstance(final File etcDir) or creating the actual instance at instance var. definition.
Source:
public VDS activate() { VDS vds = null; try { refreshHost(vds); } catch (java.lang.Exception e) { log.infoFormat("Failed to activate VDS = {0} with error: {1}.", getVdsId(), e.getMessage()); } return vds; }

Target:
the prefix of full package name java.lang. is redundant.
Source:
protected void releaseMonitorLock(EngineLock monitoringLock, String commandName) { final VDS vds = getVds(); getLockManager().releaseLock(monitoringLock); log.infoFormat(commandName + " finished. Lock released. Monitoring can run now for host {0} from data-center {1}", vds.getName(), vds.getStoragePoolName()); }

Target:
This line should come after the lock is released, since it's not actually used until then.
Source:
public static Guid getGuidValue(Guid id) { return id == null ? null : id; }

Target:
return id;
Source:
private void setNonOperational(VDS server) { Map<String, String> customValues = new HashMap<String, String>(); customValues.put(GlusterConstants.COMMAND, "gluster peer probe"); customValues.put(GlusterConstants.SERVER, server.getHostName()); SetNonOperationalVdsParameters nonOpParams = new SetNonOperationalVdsParameters(server.getId(), NonOperationalReason.GLUSTER_COMMAND_FAILED, customValues); nonOpParams.setSaveToDb(true); Backend.getInstance().runInternalAction(VdcActionType.SetNonOperationalVds, nonOpParams, ExecutionHandler.createInternalJobContext()); }

Target:
I think the message GLUSTER_COMMAND_FAILED can be changed to use vdsName instead of Server. This way you will not need to add custom value for server in other places - like InitVdsOnUpCommand, SetNonOperationalVdsCommand etc.
Source:
protected static DbFacade getDbFacade() { return DbFacade.getInstance(); }

Target:
can'y this be made private?
Source:
public void setUp() { mappingLocator = new MappingLocator(); mappingLocator.populate(); HashMap<Integer, String> osNames = new HashMap<>(1); osNames.put(0, "Unassigned"); }

Target:
this has no meaning here . the osNames var is local here and not used by anyone
Source:
protected VDSCommandType getRevertVDSCommandType() { return VDSCommandType.DeleteImageGroup; }

Target:
reminder: remove the VDSCommandType and just return null (perform rollback from previous task handler).
Source:
protected VDSParametersBase getRevertVDSParameters() { DeleteImageGroupVDSCommandParameters parameters = new DeleteImageGroupVDSCommandParameters(); parameters.setStoragePoolId(getEnclosingCommand().getParameters().getStoragePoolId()); parameters.setStorageDomainId(getEnclosingCommand().getParameters().getStorageDomainId()); parameters.setImageGroupId(getEnclosingCommand().getParameters().getImageGroupID()); return parameters; }

Target:
perhaps perform the revert through RemoveImageCommand in revertTask() - that way the image would be removed completely in that case (also from the DB) i and we will benefit from the additional logic in RemoveImage.
Source:
public boolean shouldAlertUpgrade(ArrayList<RpmVersion> isos, Version hostOs) { boolean alert = false; for (RpmVersion iso: isos) { if (iso.getMajor() == hostOs.getMajor() && iso.compareTo(hostOs) != 0) { alert = true; break; } } return alert; }

Target:
why have you changed the > to != ?
Source:
public void setVds(VDS vds) { _vds = vds; setHost(_vds.getHostName(), _vds.getSSHPort()); setUser(_vds.getSSHUsername()); }

Target:
please move the setUser and setHost to connect (if _vds != null)
Source:
public Response end(Action action) { return doAction(VdcActionType.EndExternalStep, new EndExternalStepParameters(guid, action.isSucceeded(), action.isForce()), action); }

Target:
The combination of succedded and force is not clear to me, let's discuss this; I believe this API should change.
Source:
protected Snapshot doPopulate(Snapshot model, org.ovirt.engine.core.common.businessentities.Snapshot entity) { if (isPopulate()) { VdcQueryReturnValue queryReturnValue = runQuery(VdcQueryType.GetVmOvfConfigurationBySnapshot, new IdQueryParameters(Guid.createGuidFromString(model.getId()))); if (queryReturnValue.getSucceeded() && queryReturnValue.getReturnValue() != null) { return SnapshotMapper.mapSnapshotConfiguration((String) queryReturnValue.getReturnValue(), ConfigurationType.OVF, model); } } return model; }

Target:
btw same true for fetchCreatedEntity() which is triggers mapEntity()
Source:
public boolean isWebSocketProxyDefined() { String wsConfig = (String) AsyncDataProvider.getConfigValuePreConverted(ConfigurationValues.WebSocketProxy); return wsConfig != null && !"".equals(wsConfig) && !"Off".equals(wsConfig); //$NON-NLS-1$ $NON-NLS-2$ }

Target:
does it have to be "Off" with capital? Don't you need to do a case insensitive compare?
Source:
protected void setActionMessageParameters() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__ADD); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__NETWORK_QOS); }

Target:
this line can be pulled into setActionMessageParameters() method in the NetworkQoSCommandBase class since it repeats in any of the NetworkQoS commands.
Source:
protected Map<String, Pair<String, String>> getSharedLocks() { if (getDisk() == null) { return null; } if (getDisk().getVmEntityType() != null) { switch (getDisk().getVmEntityType()) { case VM: return createSharedLocksForVmDisk(); case TEMPLATE: return createSharedLocksForTemplateDisk(); } } log.warnFormat("No shared locks are taken while removing disk of entity: {0}", getDisk().getVmEntityType()); return null; }

Target:
yeah, I didn't think about this.. but don't you prefer to add it to the first clause (i mean to check in line 356) that: getDisk() == null || getDisk().getVmEntityType() == null ? it's a matter of style, so as you think..
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AsyncTaskEntity other = (AsyncTaskEntity) obj; return ObjectUtils.objectsEqual(taskId, other.taskId) && ObjectUtils.objectsEqual(entityId, other.entityId) && ObjectUtils.objectsEqual(entityType, other.entityType); }

Target:
please add brackets to all of these ifs
Source:
public StoragePool getEntity() { return (StoragePool) ((super.getEntity() instanceof StoragePool) ? super.getEntity() : null); }

Target:
do you need this check? Since the setEntity already takes only StoragePool...
Source:
public VdcActionParametersBase getParameters(Template incoming, VmTemplate entity) { VmTemplate updated = getMapper(modelType, VmTemplate.class).map(incoming, entity); updated.setUsbPolicy(VmMapper.getUsbPolicyOnUpdate(incoming.getUsb(), entity.getUsbPolicy(), lookupCluster(updated.getVdsGroupId()))); UpdateVmTemplateParameters params = new UpdateVmTemplateParameters(updated); if (incoming.isSetConsoleDeviceEnabled()) { params.setConsoleEnabled(incoming.isConsoleDeviceEnabled()); } return params; }

Target:
i'd create a dedicated mapper for the UpdateVmTemplateParameters (see [1]), [1] VmMapper.RunVmOnceParams map(VM vm, RunVmOnceParams template)
Source:
public boolean shouldVdsBeFenced() { boolean result = false; switch (vds.getStatus()) { case Down: case InstallFailed: case Maintenance: case NonOperational: case NonResponsive: result = true; break; default: break; } return result; }

Target:
If you want to remove not null validation from constructor, it should be added here
Source:
public ValidationResult validateStatusForActivation() { ValidationResult existsValidation = exists(); if (!existsValidation.isValid()) { return existsValidation; } if (vds.getStatus().equals(VDSStatus.Up)) { return new ValidationResult(VdcBllMessages.VDS_ALREADY_UP); } if (vds.getStatus().equals(VDSStatus.NonResponsive)) { return new ValidationResult(VdcBllMessages.VDS_NON_RESPONSIVE); } return ValidationResult.VALID; }

Target:
is it better practice to do the following if (VDSStatus.NonResponsive.equals(vds.getStatus())) same for the check above
Source:
private void validateParameters(Action action) { String srvcTypeParam = action.getServiceType(); validateParameters(action, "serviceType"); validateEnum(ServiceType.class, srvcTypeParam); }

Target:
any reason for this local var?
Source:
private List<VM> getSelectedVms() { List<VM> vms = new ArrayList<VM>(); if (getSelectedItems() == null) { return vms; } for (Object selectedItem : getSelectedItems()) { UserPortalItemModel itemModel = (UserPortalItemModel) selectedItem; VM vm = itemModel.getVM(); if (vm == null) { continue; } vms.add(vm); } return vms; }

Target:
I'd rather avoid using continue and just do: if (vm != null) { vms.add(vm); }
Source:
public void newNetwork() { if (getWindow() != null) { return; } final NetworkModel networkModel = new NewNetworkModel(this); setWindow(networkModel); networkModel.startProgress(null); initDcList(networkModel); }

Target:
Why do you do it here and not as part of the initDcList()?
Source:
public void handleTasksOfCommandWithEmptyVdsmId(final List<AsyncTasks> tasks) { ThreadPoolUtil.execute(new Runnable() { @SuppressWarnings("synthetic-access") @Override public void run() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Object>() { @Override public Object runInTransaction() { boolean isPartiallySubmittedCommand = isPartiallySubmittedCommand(tasks); for (AsyncTasks task : tasks) { handleTaskOfCommandWithEmptyVdsmId(isPartiallySubmittedCommand, task); } irsBrokerLatch.countDown(); return null; } }); } }); }

Target:
I think it is better to do this in the finally block, just in case an exception is thrown in the previous methods.
Source:
private String getVmIsBeingImportedMessage() { StringBuilder builder = new StringBuilder(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_BEING_IMPORTED.name()); builder.append(String.format("$VmName %1$s", getVmName())); return builder.toString(); }

Target:
possible NPE?
Source:
public void testGetMasterStorageDomainIdForPool() { Guid result = dao.getMasterStorageDomainIdForPool(Guid.createGuidFromString("6d849ebf-755f-4552-ad09-9a090cda105d")); assertNotNull(result); assertEquals(EXISTING_DOMAIN_ID, result); }

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

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

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

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

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

Target:
use new Guid(String) - this literal can't be null
Source:
public void addExternallyManagedVms(List<VmStatic> externalVmList) { for (VmStatic currVm : externalVmList) { AddVmFromScratchParameters params = new AddVmFromScratchParameters(currVm, null, null); VdcReturnValueBase returnValue = Backend.getInstance().runInternalAction(VdcActionType.AddVmFromScratch, params, ExecutionHandler.createInternalJobContext()); if (!returnValue.getSucceeded()) { log.debugFormat("Failed adding Externally managed VM {0}", params.getVm().getName()); } } }

Target:
not so important but i think it would be nicer to use currVm.getName()
Source:
public void updateAllInBatch(Collection<T> entities) { if (entities != null && entities.size() > 0) updateAllInBatch(getProcedureNameForUpdate(), entities, getBatchMapper()); }

Target:
we use { even for one line in the scope. lets keep it consider a report if null is passed.
Source:
public synchronized VDS getFullVds() { if (fullVds == null) { fullVds = DbFacade.getInstance().getVdsDao().get(vdsStatic.getId()); } return fullVds; }

Target:
any reason this should be synced? make the fullVDs variable volatile and you got the visibility problem solved
Source:
protected boolean canDoAction() { VdsValidator vdsValidator = new VdsValidator(getVds()); return validate(vdsValidator.exists()) && validate(vdsValidator.isUp()) && validate(vdsValidator.validateMinimumVersionSupport(Version.v3_3)); }

Target:
Please use FeatureSupported class for the versioning checking, it's the standard way to constrain the feature to a specific version.
Source:
protected void validateParameters(VnicProfile vnicProfile) { validateParameters(vnicProfile, "name"); if (!vnicProfile.isSetNetwork() || !vnicProfile.getNetwork().isSetId()) { vnicProfile.setNetwork(new Network()); vnicProfile.getNetwork().setId(networkId); } }

Target:
this is not a part of the validateParameters() logic
Source:
protected String getSearchPattern() { String user_defined_pattern = QueryHelper.getConstraint(getUriInfo(), "", modelType); return user_defined_pattern.equals("Users : ") ? user_defined_pattern + USERS_SEARCH_PATTERN : user_defined_pattern + AND_SEARCH_PATTERN + USERS_SEARCH_PATTERN; }

Target:
now when you split, we should not allow seeing AD users in this context.
Source:
public void ClearTasks() { synchronized (_listTasks) { java.util.ArrayList<CommandAsyncTask> CurrentActionTypeTasks = getCurrentTasks(); for (CommandAsyncTask task : CurrentActionTypeTasks) { if (task.getLastTaskStatus().getStatus() == AsyncTaskStatusEnum.finished) { task.clearAsyncTask(); if (task.getVdsmTaskId() != null) { _listTasks.remove(task.getVdsmTaskId()); } } } } }

Target:
if we already called clearAsyncTask(), wouldn't we want to remove it from the list regardless of vdsmTaskId?
Source:
private void initDisplayProtocol() { ArrayList<EntityModel> displayProtocolOptions = new ArrayList<EntityModel>(); getDisplayProtocol().setItems(displayProtocolOptions); getDisplayProtocol().getSelectedItemChangedEvent().addListener(this); }

Target:
can be just inlined as setItems(new ArrayList...)
Source:
private static boolean hasTaskCompleted(GlusterAsyncTask task) { if (JobExecutionStatus.ABORTED.equals(task.getStatus()) || JobExecutionStatus.FINISHED.equals(task.getStatus()) || JobExecutionStatus.FAILED.equals(task.getStatus())) { return true; } return false; }

Target:
Why "equals" instead of "==". Above method also has same logic, please remove the duplication.
Source:
protected ValidationResult isVmInterfacesConfigured(VM vm) { for (VmNetworkInterface nic : vm.getInterfaces()) { if (nic.getVnicProfileId() == null) { return !FeatureSupported.networkLinking(vm.getVdsGroupCompatibilityVersion()) ? new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_INTERFACE_NETWORK_NOT_CONFIGURED) : ValidationResult.VALID; } } return ValidationResult.VALID; }

Target:
would you mind reverting the condition into a positive form ? return FeatureSupported.networkLinking(vm.getVdsGroupCompatibilityVersion()) ? ValidationResult.VALID: new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_INTERFACE_NETWORK_NOT_CONFIGURED);
Source:
private boolean isNotSPM(VDSReturnValue returnValue) { return returnValue != null && returnValue.getVdsError() != null && returnValue.getVdsError().getCode() == VdcBllErrors.SpmStatusError; }

Target:
the two last checks can and should be squashed into one check - returnValue.getVdsError() != VdcBllErrors.SpmStatusError, I actually prefer !VdcBllErrors.SpmStatusError.equals(returnValue.getVdsError()) the first check can be removed, but that's up to you..if it's being changed into one check, the whole method call can be replaced with the check :)
Source:
private static void updateOption(VdcOption option) { Map<String, Object> values = _vdcOptionCache.get(option.getoption_name()); if (values == null) { values = new HashMap<String, Object>(); _vdcOptionCache.put(option.getoption_name(), values); } log.info("In updateOption decrypting and saving option "+option.getoption_name()+" version = "+option.getversion()); values.put(option.getversion(), GetValue(option)); }

Target:
This looks more like a debug to me. Can you please remove this one, or maybe have it as log.debug?
Source:
public AddBondParameters(Guid vdsId, String bondName, Network network, String[] nics, int vladId) { this(vdsId, bondName, network, nics); setVlanId(vladId); privateBootProtocol = NetworkBootProtocol.NONE; }

Target:
Redundant, the call to this(vdsId, bondName, network, nics) already handles it
Source:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getParameters().getRngDevice() == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_RNG_NOT_FOUND); } if (!getRngDevices().isEmpty()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_RNG_ALREADY_EXISTS); } return true; }

Target:
this should be in super as well.. even first
Source:
public String value() { return statusMsg.toUpperCase(); }

Target:
but it's already defined as upper case - so, do we really need to run "toUpperCase"?
Source:
public String getCascadedResource(String resourceName) { List<BrandingTheme> brandingThemes = getBrandingThemes(); // assume these are sorted 00, 01, 02, etc. for (int i = brandingThemes.size() - 1; i >= 0; i--) { String resourcePath = brandingThemes.get(i).getResourcePath(resourceName); if (resourcePath != null) { return resourcePath; } } return null; }

Target:
The resource name should be gotten from the interface (branding.properties), you cannot relay on file name.
Source:
private static int isIsoVersionSupported(String isoVersion) { String supported = Config.<String> GetValue(ConfigValues.OvirtInitialSupportedIsoVersion); return VersionUtils.compareRpmPart(isoVersion, supported); }

Target:
should not be static, please check.
Source:
private String getDiskIsBeingMigratedMessage() { if (cachedDiskIsBeingMigratedMessage == null) { StringBuilder builder = new StringBuilder(VdcBllMessages.ACTION_TYPE_FAILED_DISK_IS_BEING_MIGRATED.name()); if (getImage() != null) { builder.append(String.format("$DiskName %1$s", getDiskAlias())); } builder.append(String.format("$OperationType %1$s", ImageOperation.Move == getParameters().getOperation() ? "moved" : "copied")); cachedDiskIsBeingMigratedMessage = builder.toString(); } return cachedDiskIsBeingMigratedMessage; }

Target:
where does the caching help u?
Source:
void forceRefresh(M model) { if (model instanceof SearchableListModel) { UICommand lastExecutedCommand = model.getLastExecutedCommand(); if (lastExecutedCommand != null && !lastExecutedCommand.getIsCancel()) { // Refresh the grid using ForceRefresh command SearchableListModel searchableList = (SearchableListModel) model; searchableList.getForceRefreshCommand().execute(); } } }

Target:
for readability/consistency, consider invoking SearchableListModel -> forceRefresh() instead...
Source:
protected boolean acquireLockInternal() { final boolean acquireLock = super.acquireLockInternal(); if (!acquireLock && getVm().isAutoStartup()) { AutoStartVmsRunner.getInstance().addVmToRun(getParameters().getVmId()); } return acquireLock; }

Target:
add a null check here please
Source:
protected void ExecuteVdsBrokerCommand() { glusterTaskReturn = getBroker().glusterVolumeRemoveBricksStart(getParameters().getVolumeName(), getParameters().getBrickDirectories().toArray(new String[0]), getParameters().getReplicaCount(), getParameters().isForceRemove()); task = glusterTaskReturn.getGlusterTask(); setReturnValue(task); proceedProxyReturnValue(); }

Target:
Mostly we call processProxyReturnValue() before setting the return value. The setting of the retunr value should be the last statement.
Source:
public void moveUnpluggedDiskVmDown() { command.getParameters().setParametersList(createMoveDisksParameters()); initDiskImage(diskImageId); initVm(VMStatus.Down, Guid.newGuid(), diskImageId, false); command.updateParameters(); assertTrue(command.getMoveDiskParametersList().size() == 1); }

Target:
use assertEquals
Source:
public static List<String> getVirtioScsiControllersForEntity(Guid id) { return VmHelper.getInstance().getEntity(List.class, VdcQueryType.GetVirtioScsiControllers, new IdQueryParameters(id), "GetVirtioScsiControllers", true); }

Target:
ummm... is this is a singleton, should this simply be an instance method?
Source:
protected BaseEditVmInterfaceModel(VmBase vm, VMStatus vmStatus, Guid dcId, Version clusterCompatibilityVersion, ArrayList<VmNetworkInterface> vmNicList, VmNetworkInterface nic, EntityModel sourceModel) { super(vm, dcId, clusterCompatibilityVersion, vmNicList, sourceModel, new EditProfileBehavior()); this.nic = nic; this.vmStatus = vmStatus; setTitle(ConstantsManager.getInstance().getConstants().editNetworkInterfaceTitle()); setHashName("edit_network_interface_vms"); //$NON-NLS-1$ }

Target:
Please format for uniformity, i.e. one argument per line. There's a formatter that's part of the git repository, you can just plug it into an IDE and let it do the job for you.
Source:
public Disk getDisk() { if (disk == null) { disk = getDiskDao().get(getParameters().getDiskId()); } return disk; }

Target:
Please use protected here
Source:
public HotPlugDiskToVmCommand(T parameters) { super(parameters); disk = getDiskDao().get(getParameters().getDiskId()); }

Target:
constructors are a bad place to invoke DB operations - it makes it really hard to test this command. Why not use a simple lazy getter?
Source:
public void cancelRefresh() { if(refresh == null) { return; } else { refresh.cancel(); } }

Target:
This can be simplified as follows if(refresh != null) { refresh.cancel(); }
Source:
public void refresh(final GlusterVolumeEntity volumeEntity) { refresh = new Timer() { @Override public void run() { refreshDetails(volumeEntity); } }; refresh.schedule(10000); }

Target:
The problem still exists You are just cancelling the last timer not the previous one If you see above, after each request has returned you are creating a new timer and scheduling. Can this timer be re-used? May be you can create the time in the constructor and the schedule can be triggered from wherever you want
Source:
private static long retrieveIsoFileSize(Map.Entry<String, Map<String, String>> isoFileWithMetadata) { // old VDSM versions don't provide the metadata for iso files therefore engine marks size as not available String sizeValue = isoFileWithMetadata.getValue().get("size"); if (sizeValue == null) { return SIZE_IS_NOT_AVAILABLE; } try { return Long.valueOf(sizeValue); } catch (NumberFormatException e) { // illegal number is treated as not available, treating exception in UI will be more complicate log.errorFormat("File's '{0}' size is illegal number", isoFileWithMetadata.getKey(), e); return SIZE_IS_NOT_AVAILABLE; } }

Target:
Lines 578-581 can be removed since Long.valueOf handles null.
Source:
protected boolean canDoAction() { GlusterVolumeEntity glusterVolume = getGlusterVolume(); if (!super.canDoAction()) { return false; } boolean isVolumeDistributed = glusterVolume.getVolumeType().isDistributedType(); if (!isVolumeDistributed) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_NOT_DISTRIBUTED); } else if (isVolumeDistributed && glusterVolume.getBricks().size() == 1) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_DISTRIBUTED_AND_HAS_SINGLE_VOLUME); } return true; }

Target:
redundant clause at the second if , as it's "else if" from the if (!isVolumeDistributed) - this means that else if will be called when isVolumeDestributed == true and no need to include it in the 2nd clause.
Source:
public int countDownBricks(GlusterVolumeEntity volume) { int downCount = 0; int upCount = 0; for (int i = 0 ; i < volume.getBricks().size(); i++) { GlusterBrickEntity brick = volume.getBricks().get(i); if(brick.getStatus() == GlusterStatus.UP) { upCount++; }else { downCount++; } if(upCount > 0 && downCount > 0) { return downCount; } } return downCount; }

Target:
use foreach style loop
Source:
public int countDownBricks(GlusterVolumeEntity volume) { int downCount = 0; int upCount = 0; for (int i = 0 ; i < volume.getBricks().size(); i++) { GlusterBrickEntity brick = volume.getBricks().get(i); if(brick.getStatus() == GlusterStatus.UP) { upCount++; }else { downCount++; } if(upCount > 1 && downCount > 1) { return downCount; } } return downCount; }

Target:
why not >0 ? let say a volume has 6 bricks and first 2 are down. In this scenario, the above loop will executed 4 times but 3 is enough to get the expected result
Source:
public String getThemeStyleSheet(ApplicationType type) { if (type == null) { type = DEFAULT_APPLICATION_TYPE; } return brandingProperties.getProperty(type.getCssKey()); }

Target:
I still think this should be context parameter.
Source:
private boolean shouldUpdateImageProperties() { if (getOldDisk().getDiskStorageType() == DiskStorageType.IMAGE) { return false; } Guid oldQuotaId = ((DiskImage) getOldDisk()).getQuotaId(); return !ObjectUtils.objectsEqual(oldQuotaId, getQuotaId()); }

Target:
IIUC, this should be "!= DiskStorageType.IMAGE", no?
Source:
protected void postSaveAction(Guid networkGuid, boolean succeeded) { if (succeeded) { if ((Boolean) getIsVmNetwork().getEntity()) { performProfilesActions(networkGuid); } else { stopProgress(); cancel(); } } stopProgress(); }

Target:
we might call stopProgress twice now...
Source:
private void closeConfirmationWindow() { getConfirmWindow().stopProgress(); setConfirmWindow(null); }

Target:
add a null check for getConfirmWindow()
Source:
protected void executeCommand() { VDSReturnValue vdsReturnaValue = runVdsCommand(VDSCommandType.StopRebalanceGlusterVolume, new GlusterVolumeVDSParameters(upServer.getId(), getGlusterVolumeName())); if (!vdsReturnaValue.getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_VOLUME_REBALANCE_STOP_FAILED, vdsReturnaValue.getVdsError() .getMessage()); return; } endStepJob(); releaseVolumeLock(); setSucceeded(vdsReturnaValue.getSucceeded()); }

Target:
should setSucceeded(false) before return
Source:
protected void entityPropertyChanged(Object sender, PropertyChangedEventArgs e) { super.entityPropertyChanged(sender, e); if (e.PropertyName.equals("status")) //$NON-NLS-1$ { getSearchCommand().execute(); } }

Target:
no need to worry about the status of the host here
Source:
public UnitVmModel flush() { UnitVmModel model = driver.flush(); model.getNicsWithLogicalNetworks().getItemsChangedEvent().removeListener(vnicsChangedListener); profilesInstanceTypeEditor.flush(); priorityEditor.flush(); return model; }

Target:
can't it be resolved in the editor itself (to avoid similar issues on other widgets)? E.g. Since AddRemoveRowWidget -> flush() - 'model.setItems(values)' invokes the ItemsChangedEvent, try clearing the listeners directly beforehand.
Source:
protected static VdcParameter create(String name, Class javaType, String uuidStr) { UUID uuid = UUID.fromString(uuidStr); synchronized (parametersMap) { VdcParameter param = parametersMap.get(uuid); if (param != null) { throw new InvalidParameterUuidException(name, param.getUuid(), param.getName()); } param = new VdcParameter(name, javaType.getName(), uuid); parametersMap.put(uuid, param); return param; } }

Target:
I prefer to keep create in VdcParameter, and just delegate these method from here. The use of the VdcParametersMeta is optional, just for the developer who like easier integration with IDE, no?
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } VdcParametersMap otherParamsMap = (VdcParametersMap) obj; return paramsMap.equals(otherParamsMap.paramsMap); }

Target:
I know I am out of this world... but do not like temp vars... :) Please ignore! return paramsMap.equals(((VdcParametersMap) obj).paramsMap)
Source:
public boolean equals(Object other) { if (other == null || !(other instanceof VdcParameter)) { return false; } VdcParameter otherParam = (VdcParameter) other; return getName().equals(otherParam.getName()) && getJavaType().equals(otherParam.getJavaType()) && getGuid().equals(otherParam.getGuid()); }

Target:
compare only guid, no?
Source:
public int hashCode() { int hash = 7; hash = 31 * hash + (this.name != null ? this.name.hashCode() : 0); hash = 31 * hash + (this.javaType != null ? this.javaType.hashCode() : 0); hash = 31 * hash + (this.guid != null ? this.guid.hashCode() : 0); return hash; }

Target:
should be based on guid only
Source:
public int hashCode() { int hash = 7; final int prime = 31; for (Entry<VdcParameter, Object> entry : paramsMap.entrySet()) { hash = prime * hash + entry.getKey().hashCode(); hash = prime * hash + entry.getValue().hashCode(); } return hash; }

Target:
why AbstractMap::hashCode is not enough?
Source:
public int hashCode() { int hash = 7; hash = 31 * hash + (this.value != null ? this.value.hashCode() : 0); return hash; }

Target:
why not just return Object? Why do we need this class?
Source:
protected void executeQueryCommand() { getQueryReturnValue().setReturnValue(DbFacade.getInstance().getRoleDao().get( getParameters().<Guid>getParameter(UserRolesVdcParameters.RoleId, Guid.class))); }

Target:
Can we have: getParameters().<Guid>getParameter(UserRolesVdsParameters.RoleId) or even: getParameters().getParameter(UserRolesVdsParameters.RoleId) if the function gets object?
Source:
private void handleTitlePanel(String eventType, Element parent) { if (title == "") { //$NON-NLS-1$ // no need to show/hide title return; } titlePanel.setWidget(new Label(title)); if (BrowserEvents.MOUSEOVER.equals(eventType)) { titlePanel.showRelativeTo(parent); } else if (BrowserEvents.MOUSEOUT.equals(eventType)) { titlePanel.hide(); } }

Target:
Just a small thing, I'd rather do if (title.isEmpty()) ... or alternatively if ("".equals(title)) ... but I guess it's the same thing in the end, from generated JavaScript perspective.
Source:
public GlusterVolumeTaskReturnForXmlRpc glusterVolumeRebalanceStop(String volumeName) { try { Map<String, Object> xmlRpcReturnValue = vdsServer.glusterVolumeRebalanceStatus(volumeName); GlusterVolumeTaskReturnForXmlRpc wrapper = new GlusterVolumeTaskReturnForXmlRpc(xmlRpcReturnValue); return wrapper; } catch (UndeclaredThrowableException ute) { throw new XmlRpcRunTimeException(ute); } }

Target:
Would this method stop the rebalance as well? I can not see stop call here.
Source:
public void refreshDetails(GlusterVolumeEntity volumeEntity) { AsyncDataProvider.getGlusterRebalanceStatus(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { VdcQueryReturnValue vdcValue = (VdcQueryReturnValue) returnValue; GlusterVolumeTaskStatusEntity rebalanceStatusEntity =vdcValue.getReturnValue(); showStatus(rebalanceStatusEntity); } }), volumeEntity.getClusterId(), volumeEntity.getId()); }

Target:
its better to have a null check for rebalanceStatusEntity
Source:
private LiveMigrateDiskParameters createLiveMigrateDiskParameters(MoveDiskParameters moveDiskParameters, Guid vmId) { LiveMigrateDiskParameters toReturn = new LiveMigrateDiskParameters(moveDiskParameters.getImageId(), moveDiskParameters.getSourceDomainId(), moveDiskParameters.getStorageDomainId(), vmId, moveDiskParameters.getQuotaId()); toReturn.setImageGroupID(diskMap.get(moveDiskParameters.getImageId()).getId()); return toReturn; }

Target:
why not to add it to the parameters of LiveMigrateDiskParameters's constructor to enforce that the parameters of the live migrate disk command will always have the image group id?
Source:
private static String getQuotaRegexString(SearchObjectAutoCompleter search) { String query = ".*" + search.getDefaultSort(SearchObjects.QUOTA_OBJ_NAME) + ".*" + search.getRelatedTableNameWithOutTags(SearchObjects.QUOTA_OBJ_NAME) + ".* "; return query; }

Target:
Why not using here StringBuilder as well ???
Source:
private static String getQuotaRegexString(SearchObjectAutoCompleter search) { String query = ".*" + search.getDefaultSort(SearchObjects.QUOTA_OBJ_NAME) + ".*" + search.getRelatedTableNameWithOutTags(SearchObjects.QUOTA_OBJ_NAME) + ".* "; System.out.println("VdsGroupRegExp: " + query); return query; }

Target:
Please remove printing to stdout
Source:
public String getRelativePath() { String path = getPath(); if (path.startsWith("/")) { //$NON-NLS-1$ path = path.substring(1); } return path; }

Target:
Yes, this will work. If I understand correctly, this is run by gwt... right? Does it support File::getCanonicalPath()? if so let's use it... If not... I would have gone with something a little more generic... path.replace("//", "/") without conditional...
Source:
public GlusterBricks list() { boolean flag = QueryHelper.hasMatrixParam(getUriInfo(), "force"); List<GlusterBrickEntity> bricks = getBackendCollection(VdcQueryType.GetGlusterVolumeBricks, new IdQueryParameters(asGuid(getVolumeId()))); GlusterBricks bricksModel = mapCollection(bricks); return addActions(bricksModel); }

Target:
remove above line
Source:
public EventBus getEventBus() { return eventBus; }

Target:
Thinking about it, this method can be protected and final.
Source:
public void registerHandler(HandlerRegistration reg) { if (reg != null && !handlerRegistrations.contains(reg)) { handlerRegistrations.add(reg); } }

Target:
I think this should be final.
Source:
public void unregisterHandlers() { for (HandlerRegistration reg: handlerRegistrations) { reg.removeHandler(); // can't call unregisterHandler(reg) as that would modify the list during iteration } handlerRegistrations.clear(); }

Target:
I think this should be final.
Source:
public void unregisterHandler(HandlerRegistration reg) { if (reg != null) { reg.removeHandler(); handlerRegistrations.remove(reg); } }

Target:
I think this should be final.
Source:
public void logMessage(Guid clusterId, GlusterVolumeEntity volume, final String action, final String status, AuditLogType logType) { logUtil.logAuditMessage(clusterId, volume, null, logType, new HashMap<String, String>(){ { put("action", action); put("status", status); }}); }

Target:
Does this need to be public?
Source:
public void refreshDetails(GlusterVolumeEntity volumeEntity) { AsyncDataProvider.getGlusterRemoveBricksStatus(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { VdcQueryReturnValue vdcValue = (VdcQueryReturnValue) returnValue; GlusterVolumeTaskStatusEntity statusEntity = vdcValue.getReturnValue(); if (statusEntity != null) { showStatus(statusEntity); } else { cancelRefresh(); } } }), volumeEntity.getClusterId(), volumeEntity.getId(), getBricks()); }

Target:
you should not cancelRefresh if the query is failed
Source:
public void UpdateDynamicData(VdsDynamic dynamicData) { log.debug("Updated VDS dynamic without checking if update is needed"); DbFacade.getInstance().getVdsDynamicDao().update(dynamicData); }

Target:
I don't see a cache update here. pls fix the java doc
Source:
protected void syncSearch() { SearchParameters tempVar = new SearchParameters(getSearchString(), SearchType.VDS, isCaseSensitiveSearch()); tempVar.setRefresh(getIsQueryFirstTime()); super.syncSearch(VdcQueryType.Search, tempVar); }

Target:
this model is not influenced by the searchbar, you can remove it from patch.
Source:
public VdcActionParametersBase(ParametersMap map) { for (Map.Entry<Parameter, Serializable> entry : map.entrySet()) { put(Parameter.getByUuid(entry.getKey().getUuid().toString()), entry.getValue()); } }

Target:
this I need to understand... let's discuss this on the VdcParameter at infrastructure, as I think it should be done automatically while de-serialized.
Source:
protected boolean checkStorageDomainStatusNotEqual(StorageDomainStatus status) { boolean returnValue = false; if (getStorageDomainStatus() != null && getStorageDomainStatus() != null) { returnValue = (getStorageDomainStatus() != status); if (!returnValue) { addStorageDomainStatusIllegalMessage(); } } return returnValue; }

Target:
the same condition is checked twice
Source:
private void applyModeCustomizations() { if (ApplicationModeHelper.getUiMode() == ApplicationMode.GlusterOnly) { optimizationTab.setVisible(false); resiliencePolicyTab.setVisible(false); clusterPolicyTab.setVisible(false); dataCenterPanel.addStyleName(style.generalTabTopDecoratorEmpty()); cPUEditor.setVisible(false); } }

Target:
i think CPU is already not visible in the Cluster dialog
Source:
public void executeQueryCommand() { clusterId = getParameters().getClusterId(); Guid volumeId = getParameters().getVolumeId(); if (volumeId != null) { volume = getGlusterVolumeDao().getById(volumeId); if (volume == null) { throw new RuntimeException(VdcBllMessages.GLUSTER_VOLUME_ID_INVALID.toString()); } } if (clusterId == null) { clusterId = volume.getClusterId(); } getQueryReturnValue().setReturnValue(fetchTaskStatusDetails()); }

Target:
if volumeId is null then we will have NPE here i think its safe to send null to getById method, no? if so then the null check on volumeId can be removed and this will prevent NPE
Source:
protected void syncSearch() { if (getEntity() == null) { return; } if (getEntity() != null) { GlusterVolumeEntity glusterVolumeEntity = (GlusterVolumeEntity) getEntity(); // If the items are same, just fire the item changed event to make sure that items are displayed if (getItems() == glusterVolumeEntity.getBricks()) { getItemsChangedEvent().raise(this, EventArgs.Empty); } else { setItems(glusterVolumeEntity.getBricks()); } } else { setItems(null); } }

Target:
this check is redundant
Source:
public static Parameter instantiate(SerializationStreamReader reader) throws SerializationException { UUID uuid = UUID_CustomFieldSerializer.instantiate(reader); return Parameter.getByUuid(uuid.toString()); }

Target:
no reason for the uuid temp parameter :)
Source:
public ParametersMap put(Parameter param, Object value) { if (!isAssignableFrom(param.getJavaType(), value.getClass())) { throw new InvalidParameterValueException(param.getName(), param.getJavaType(), value.getClass()); } paramsMap.put(param, (Serializable) value); return this; }

Target:
I think this should be pushed higher in patch chain.
Source:
public List<permissions> getAllForEntity(Guid id, Guid userID, boolean isFiltered) { Integer appMode = Config.<Integer> GetValue(ConfigValues.ApplicationMode); MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("id", id).addValue("user_id", userID).addValue("is_filtered", isFiltered) .addValue("app_mode", appMode.intValue()); return getCallsHandler().executeReadList("GetPermissionsByEntityId", PermissionRowMapper.instance, parameterSource); }

Target:
I think GetValue returns an "int" only, so no need to assign to Integer. Rather you can assign to int type and then pass to parameter creation code.
Source:
protected void executeQueryCommand() { getQueryReturnValue().setReturnValue(DbFacade.getInstance().getVmTemplateDao().getCount()); }

Target:
please separate to a method, getVmTemplateDao() and use getDbFacade().
Source:
protected Map<String, Pair<String, String>> getExclusiveLocks() { Map<String, Pair<String, String>> locks = new HashMap<String, Pair<String, String>>(); VDSGroup cluster = getVdsGroup(); if (cluster == null || cluster.supportsVirtService()) { locks.put(getParameters().getVdsId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.VDS, VdcBllMessages.ACTION_TYPE_FAILED_OBJECT_LOCKED)); } return locks; }

Target:
Vds lock should be acquired for gluster hosts as well
Source:
public static boolean isOsSupportedForVirtIoScsi(int osId, Version clusterVersion) { ArrayList<String> diskInterfaces = SimpleDependecyInjector.getInstance().get(OsRepository.class).getDiskInterfaces(osId, clusterVersion); return diskInterfaces.contains(DiskInterface.VirtIO_SCSI.toString()); }

Target:
Don't count on this being an ArrayList - use a List
Source:
private String getValidBrickNames(List<GlusterBrickEntity> bricksForTask) { StringBuilder builder = new StringBuilder(); for (GlusterBrickEntity brick : bricksForTask) { builder.append(brick.getQualifiedName()); builder.append(", "); } return builder.substring(0, builder.length() - 2).toString(); }

Target:
Are we sure that bricksForTask will never be empty? otherwise builder.length -2 would cause error
Source:
public void runMultipleActions(final VdcActionType actionType, final List<VdcActionParametersBase> parameters, final IFrontendActionAsyncCallback successCallback) { runMultipleActions(actionType, parameters, successCallback, null, false); }

Target:
Changing this to true would still be useful to solve the unreported bug that I described.
Source:
private static List<VmDevice> getPluggedInterfaces(List<VmDevice> devices) { ArrayList<VmDevice> result = new ArrayList<VmDevice>(); for (VmDevice device : devices) { if (isBridge(device) && device.getIsPlugged()) { result.add(device); } } return result; }

Target:
The reference type should be just List
Source:
public NetworkModification(T parameters) { super(parameters); this.setStoragePoolId(getNetwork().getDataCenterId()); }

Target:
"this." prefix not necessary
Source:
private void initVncKeyboardLayout() { final List<String> layouts = (List<String>) AsyncDataProvider.getConfigValuePreConverted(ConfigurationValues.VncKeyboardLayoutValidValues); final ArrayList<String> vncKeyboardLayoutItems = new ArrayList<String>(); vncKeyboardLayoutItems.add(null); vncKeyboardLayoutItems.addAll(layouts); getVncKeyboardLayout().setItems(vncKeyboardLayoutItems); getVncKeyboardLayout().setIsChangable(false); }

Target:
why final? and please stick to a single type (List/ArrayList)
Source:
public void executeCommand(UICommand command) { super.executeCommand(command); if (command == getRemoveCommand()) { remove(); } else if ("Cancel".equals(command.getName())) { //$NON-NLS-1$ cancel(); } }

Target:
I don't see the point of having a cancel action in a subtab.
Source:
public List<ExternalSubnet> getSubnets() { return subnets; }

Target:
I don't think this getter is needed, and definitely not publicly.
Source:
private Provider<?> getProvider() { if (provider == null) { provider = getDbFacade().getProviderDao().get(getExternalNetwork().getProviderId()); } return provider; }

Target:
if getExternalNetwork() returns null, you'll end up with NPE.
Source:
private ProviderNetwork getExternalNetwork() { if (externalNetwork == null) { Network network = getNetworkDAO().get(getParameters().getNetworkId()); externalNetwork = network.getProvidedBy(); } return externalNetwork; }

Target:
what guarantees getParameters().getNetworkId()) represents a real network ?