From 9d2ff1d41d11e1ecaf855ea22a9948e6cf3c2b70 Mon Sep 17 00:00:00 2001 From: Daan Hoogland Date: Mon, 18 May 2026 09:38:43 +0200 Subject: [PATCH 1/3] add the proper checks for cross zone instatiation from template --- .../main/java/com/cloud/vm/UserVmManagerImpl.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java b/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java index b23291586ef3..bada46bba11c 100644 --- a/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java @@ -6413,7 +6413,13 @@ public UserVm createVirtualMachine(DeployVMCmd cmd) throws InsufficientCapacityE } _accountMgr.checkAccess(caller, null, true, snapshot); VolumeInfo volumeOfSnapshot = getVolume(snapshot.getVolumeId(), templateId, true); - templateId = volumeOfSnapshot.getTemplateId(); + if (volumeOfSnapshot != null) { + templateId = volumeOfSnapshot.getTemplateId(); + } else if (templateId == null) { + throw new InvalidParameterValueException( + "Could not determine template from snapshot id=" + cmd.getSnapshotId() + + "; the source volume no longer exists. Please specify a templateId."); + } } VirtualMachineTemplate template = null; @@ -6695,7 +6701,9 @@ protected void addLeaseDetailsForInstance(UserVm vm, Integer leaseDuration, VMLe private VolumeInfo getVolume(long id, Long templateId, boolean isSnapshot) { VolumeInfo volume = volFactory.getVolume(id); if (volume != null) { - if (volume.getDataStore() == null || !ScopeType.ZONE.equals(volume.getDataStore().getScope().getScopeType())) { + if (!isSnapshot + && (volume.getDataStore() == null + || !ScopeType.ZONE.equals(volume.getDataStore().getScope().getScopeType()))) { throw new InvalidParameterValueException("Deployment of virtual machine is supported only for Zone-wide storage pools"); } checkIfVolumeTemplateIsTheSameAsTheProvided(volume, templateId); From 0a5c4b0a320b08cca69057e3fa05f7a5b7553651 Mon Sep 17 00:00:00 2001 From: Daan Hoogland Date: Mon, 18 May 2026 09:48:17 +0200 Subject: [PATCH 2/3] tests for deploying from snapshot cross zone --- .../com/cloud/vm/UserVmManagerImplTest.java | 134 +++++++++++++++++- 1 file changed, 131 insertions(+), 3 deletions(-) diff --git a/server/src/test/java/com/cloud/vm/UserVmManagerImplTest.java b/server/src/test/java/com/cloud/vm/UserVmManagerImplTest.java index cb15298fbf33..7b1da4b75e2b 100644 --- a/server/src/test/java/com/cloud/vm/UserVmManagerImplTest.java +++ b/server/src/test/java/com/cloud/vm/UserVmManagerImplTest.java @@ -3908,9 +3908,6 @@ public void createVirtualMachineWithExistingSnapshot() throws ResourceUnavailabl when(snapshotMock.getVolumeId()).thenReturn(volumeId); when(volumeInfo.getTemplateId()).thenReturn(templateId); when(volumeInfo.getInstanceId()).thenReturn(null); - when(volumeInfo.getDataStore()).thenReturn(primaryDataStore); - when(primaryDataStore.getScope()).thenReturn(scopeMock); - when(primaryDataStore.getScope().getScopeType()).thenReturn(ScopeType.ZONE); when(templateMock.getTemplateType()).thenReturn(Storage.TemplateType.VNF); when(templateMock.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.KVM); when(templateMock.isDeployAsIs()).thenReturn(false); @@ -3927,6 +3924,137 @@ public void createVirtualMachineWithExistingSnapshot() throws ResourceUnavailabl userVmManagerImpl.createVirtualMachine(deployVMCmd); } + /** + * Bug fix: when deploying a VM from a snapshot whose source volume resided on + * local (HOST-scoped) storage, the zone-wide pool check must be skipped. + * The source volume's pool type is irrelevant – only the snapshot matters. + */ + @Test + public void createVirtualMachineWithSnapshotFromExpungedLocalStorageVolumeSucceeds() + throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { + DeployVMCmd deployVMCmd = new DeployVMCmd(); + ReflectionTestUtils.setField(deployVMCmd, "zoneId", zoneId); + ReflectionTestUtils.setField(deployVMCmd, "serviceOfferingId", serviceOfferingId); + ReflectionTestUtils.setField(deployVMCmd, "snapshotId", snashotId); + deployVMCmd._accountService = accountService; + + when(accountService.finalyzeAccountId(nullable(String.class), nullable(Long.class), nullable(Long.class), eq(true))).thenReturn(accountId); + when(accountService.getActiveAccountById(accountId)).thenReturn(account); + when(entityManager.findById(DataCenter.class, zoneId)).thenReturn(_dcMock); + when(entityManager.findById(ServiceOffering.class, serviceOfferingId)).thenReturn(serviceOffering); + when(snapshotDaoMock.findById(snashotId)).thenReturn(snapshotMock); + when(snapshotMock.getVolumeId()).thenReturn(volumeId); + when(volumeDataFactory.getVolume(volumeId)).thenReturn(volumeInfo); + when(volumeInfo.getTemplateId()).thenReturn(templateId); + when(volumeInfo.getInstanceId()).thenReturn(null); + when(entityManager.findByIdIncludingRemoved(VirtualMachineTemplate.class, templateId)).thenReturn(templateMock); + when(templateMock.getTemplateType()).thenReturn(Storage.TemplateType.VNF); + when(templateMock.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.KVM); + when(templateMock.isDeployAsIs()).thenReturn(false); + when(templateMock.getFormat()).thenReturn(Storage.ImageFormat.QCOW2); + when(templateMock.getUserDataId()).thenReturn(null); + Mockito.doNothing().when(vnfTemplateManager).validateVnfApplianceNics(any(), nullable(List.class), any()); + when(_dcMock.isLocalStorageEnabled()).thenReturn(true); + when(_dcMock.getNetworkType()).thenReturn(DataCenter.NetworkType.Basic); + Mockito.doReturn(userVmVoMock).when(userVmManagerImpl).createBasicSecurityGroupVirtualMachine(any(), any(), any(), any(), any(), any(), any(), + any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), nullable(Boolean.class), any(), any(), any(), + any(), any(), any(), any(), eq(true), any(), any(), any()); + + // Must NOT throw "Deployment of virtual machine is supported only for Zone-wide storage pools" + userVmManagerImpl.createVirtualMachine(deployVMCmd); + } + + /** + * Bug fix: when deploying a VM from a snapshot whose source volume's storage pool + * was expunged (data store is null), the zone-wide pool check must be skipped. + */ + @Test + public void createVirtualMachineWithSnapshotFromVolumeWithNullDataStoreSucceeds() + throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { + DeployVMCmd deployVMCmd = new DeployVMCmd(); + ReflectionTestUtils.setField(deployVMCmd, "zoneId", zoneId); + ReflectionTestUtils.setField(deployVMCmd, "serviceOfferingId", serviceOfferingId); + ReflectionTestUtils.setField(deployVMCmd, "snapshotId", snashotId); + deployVMCmd._accountService = accountService; + + when(accountService.finalyzeAccountId(nullable(String.class), nullable(Long.class), nullable(Long.class), eq(true))).thenReturn(accountId); + when(accountService.getActiveAccountById(accountId)).thenReturn(account); + when(entityManager.findById(DataCenter.class, zoneId)).thenReturn(_dcMock); + when(entityManager.findById(ServiceOffering.class, serviceOfferingId)).thenReturn(serviceOffering); + when(snapshotDaoMock.findById(snashotId)).thenReturn(snapshotMock); + when(snapshotMock.getVolumeId()).thenReturn(volumeId); + when(volumeDataFactory.getVolume(volumeId)).thenReturn(volumeInfo); + when(volumeInfo.getTemplateId()).thenReturn(templateId); + when(volumeInfo.getInstanceId()).thenReturn(null); + when(entityManager.findByIdIncludingRemoved(VirtualMachineTemplate.class, templateId)).thenReturn(templateMock); + when(templateMock.getTemplateType()).thenReturn(Storage.TemplateType.VNF); + when(templateMock.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.KVM); + when(templateMock.isDeployAsIs()).thenReturn(false); + when(templateMock.getFormat()).thenReturn(Storage.ImageFormat.QCOW2); + when(templateMock.getUserDataId()).thenReturn(null); + Mockito.doNothing().when(vnfTemplateManager).validateVnfApplianceNics(any(), nullable(List.class), any()); + when(_dcMock.isLocalStorageEnabled()).thenReturn(true); + when(_dcMock.getNetworkType()).thenReturn(DataCenter.NetworkType.Basic); + Mockito.doReturn(userVmVoMock).when(userVmManagerImpl).createBasicSecurityGroupVirtualMachine(any(), any(), any(), any(), any(), any(), any(), + any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), nullable(Boolean.class), any(), any(), any(), + any(), any(), any(), any(), eq(true), any(), any(), any()); + + // Must NOT throw "Deployment of virtual machine is supported only for Zone-wide storage pools" + userVmManagerImpl.createVirtualMachine(deployVMCmd); + } + + /** + * Regression: deploying directly from a volume (not a snapshot) whose storage pool + * is HOST-scoped (local) must still be rejected with an appropriate error. + */ + @Test + public void createVirtualMachineWithVolumeFromNonZoneScopedStorageFails() { + DeployVMCmd deployVMCmd = new DeployVMCmd(); + ReflectionTestUtils.setField(deployVMCmd, "zoneId", zoneId); + ReflectionTestUtils.setField(deployVMCmd, "serviceOfferingId", serviceOfferingId); + ReflectionTestUtils.setField(deployVMCmd, "volumeId", volumeId); + deployVMCmd._accountService = accountService; + + when(accountService.finalyzeAccountId(nullable(String.class), nullable(Long.class), nullable(Long.class), eq(true))).thenReturn(accountId); + when(accountService.getActiveAccountById(accountId)).thenReturn(account); + when(entityManager.findById(DataCenter.class, zoneId)).thenReturn(_dcMock); + when(entityManager.findById(ServiceOffering.class, serviceOfferingId)).thenReturn(serviceOffering); + when(volumeDataFactory.getVolume(volumeId)).thenReturn(volumeInfo); + // Volume lives on HOST-scoped (local) storage + when(volumeInfo.getDataStore()).thenReturn(primaryDataStore); + when(primaryDataStore.getScope()).thenReturn(scopeMock); + when(scopeMock.getScopeType()).thenReturn(ScopeType.HOST); + + InvalidParameterValueException ex = assertThrows(InvalidParameterValueException.class, + () -> userVmManagerImpl.createVirtualMachine(deployVMCmd)); + assertEquals("Deployment of virtual machine is supported only for Zone-wide storage pools", ex.getMessage()); + } + + /** + * Regression: deploying directly from a volume (not a snapshot) whose storage pool + * has been expunged (null data store) must still be rejected with an appropriate error. + */ + @Test + public void createVirtualMachineWithVolumeWithNullDataStoreFails() { + DeployVMCmd deployVMCmd = new DeployVMCmd(); + ReflectionTestUtils.setField(deployVMCmd, "zoneId", zoneId); + ReflectionTestUtils.setField(deployVMCmd, "serviceOfferingId", serviceOfferingId); + ReflectionTestUtils.setField(deployVMCmd, "volumeId", volumeId); + deployVMCmd._accountService = accountService; + + when(accountService.finalyzeAccountId(nullable(String.class), nullable(Long.class), nullable(Long.class), eq(true))).thenReturn(accountId); + when(accountService.getActiveAccountById(accountId)).thenReturn(account); + when(entityManager.findById(DataCenter.class, zoneId)).thenReturn(_dcMock); + when(entityManager.findById(ServiceOffering.class, serviceOfferingId)).thenReturn(serviceOffering); + when(volumeDataFactory.getVolume(volumeId)).thenReturn(volumeInfo); + // Volume's data store is null (pool was deleted) + when(volumeInfo.getDataStore()).thenReturn(null); + + InvalidParameterValueException ex = assertThrows(InvalidParameterValueException.class, + () -> userVmManagerImpl.createVirtualMachine(deployVMCmd)); + assertEquals("Deployment of virtual machine is supported only for Zone-wide storage pools", ex.getMessage()); + } + @Test public void testAllocateVMFromBackupWithVmSettingsRestoration() throws InsufficientCapacityException, ResourceAllocationException, ResourceUnavailableException { Long backupId = 10L; From d9c03a1fd1de4323201670574bfaa5df40594886 Mon Sep 17 00:00:00 2001 From: Daan Hoogland Date: Mon, 18 May 2026 12:07:50 +0200 Subject: [PATCH 3/3] cleanup --- .../java/com/cloud/vm/UserVmManagerImpl.java | 54 +- .../com/cloud/vm/UserVmManagerImplTest.java | 558 +++++++++--------- 2 files changed, 292 insertions(+), 320 deletions(-) diff --git a/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java b/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java index bada46bba11c..83cce4351b24 100644 --- a/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java @@ -155,7 +155,6 @@ import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.math.NumberUtils; import org.apache.commons.lang3.ObjectUtils; -import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.jetbrains.annotations.NotNull; @@ -376,6 +375,7 @@ import com.cloud.utils.Journal; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; +import com.cloud.utils.StringUtils; import com.cloud.utils.component.ComponentContext; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.concurrency.NamedThreadFactory; @@ -619,7 +619,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir @Inject BackupScheduleDao backupScheduleDao; @Inject - private StatsCollector statsCollector; + StatsCollector statsCollector; @Inject private UserDataDao userDataDao; @Inject @@ -903,10 +903,10 @@ public UserVm resetVMPassword(ResetVMPasswordCmd cmd, String password) throws Re } private boolean resetVMPasswordInternal(Long vmId, String password) throws ResourceUnavailableException, InsufficientCapacityException { - Long userId = CallContext.current().getCallingUserId(); + long userId = CallContext.current().getCallingUserId(); VMInstanceVO vmInstance = _vmDao.findById(vmId); - if (password == null || password.equals("")) { + if (StringUtils.isEmpty(password)) { return false; } @@ -1091,7 +1091,7 @@ protected void removeEncryptedPasswordFromUserVmVoDetails(long vmId) { } private boolean resetVMSSHKeyInternal(Long vmId, String sshPublicKeys, String keypairnames) throws ResourceUnavailableException, InsufficientCapacityException { - Long userId = CallContext.current().getCallingUserId(); + long userId = CallContext.current().getCallingUserId(); VMInstanceVO vmInstance = _vmDao.findById(vmId); VMTemplateVO template = _templateDao.findByIdIncludingRemoved(vmInstance.getTemplateId()); @@ -1263,7 +1263,7 @@ public UserVm upgradeVirtualMachine(UpgradeVMCmd cmd) throws ResourceAllocationE if (vmInstance == null) { throw new InvalidParameterValueException("unable to find an Instance with id " + vmId); } else if (!(vmInstance.getState().equals(State.Stopped))) { - throw new InvalidParameterValueException("Unable to upgrade Instance " + vmInstance.toString() + " " + " in state " + vmInstance.getState() + throw new InvalidParameterValueException("Unable to upgrade Instance " + vmInstance + " " + " in state " + vmInstance.getState() + "; make sure the Instance is stopped"); } @@ -1756,7 +1756,7 @@ public UserVm updateDefaultNicForVirtualMachine(UpdateDefaultNicForVMCmd cmd) th oldNetworkOfferingId = oldDefaultNetwork.getNetworkOfferingId(); } NicVO existingVO = _nicDao.findById(existing.id); - Integer chosenID = nic.getDeviceId(); + int chosenID = nic.getDeviceId(); Integer existingID = existing.getDeviceId(); Network newdefault = null; @@ -2136,14 +2136,14 @@ private boolean upgradeRunningVirtualMachine(Long vmId, Long newServiceOfferingI // Check vm flag if (!vmInstance.isDynamicallyScalable()) { - throw new CloudRuntimeException(String.format("Unable to scale %s as it does not have tools to support dynamic scaling.", vmInstance.toString())); + throw new CloudRuntimeException(String.format("Unable to scale %s as it does not have tools to support dynamic scaling.", vmInstance)); } // Check disable threshold for cluster is not crossed HostVO host = _hostDao.findById(vmInstance.getHostId()); _hostDao.loadDetails(host); if (_capacityMgr.checkIfClusterCrossesThreshold(host.getClusterId(), cpuDiff, memoryDiff)) { - throw new CloudRuntimeException(String.format("Unable to scale %s due to insufficient resources.", vmInstance.toString())); + throw new CloudRuntimeException(String.format("Unable to scale %s due to insufficient resources.", vmInstance)); } while (retry-- != 0) { // It's != so that it can match -1. @@ -2180,7 +2180,7 @@ private boolean upgradeRunningVirtualMachine(Long vmId, Long newServiceOfferingI success = true; return success; } catch (InsufficientCapacityException | ResourceUnavailableException | ConcurrentOperationException e) { - logger.error(String.format("Unable to scale %s due to [%s].", vmInstance.toString(), e.getMessage()), e); + logger.error(String.format("Unable to scale %s due to [%s].", vmInstance, e.getMessage()), e); } finally { if (!success) { // Decrement CPU and Memory count accordingly. @@ -4485,7 +4485,7 @@ private UserVm getUncheckedUserVmResource(DataCenter zone, String hostName, Stri } NetworkOffering ntwkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId()); - Long physicalNetworkId = _networkModel.findPhysicalNetworkId(zone.getId(), ntwkOffering.getTags(), ntwkOffering.getTrafficType()); + long physicalNetworkId = _networkModel.findPhysicalNetworkId(zone.getId(), ntwkOffering.getTags(), ntwkOffering.getTrafficType()); String provider = _ntwkSrvcDao.getProviderForServiceInNetwork(network.getId(), Service.Connectivity); if (!_networkModel.isProviderEnabledInPhysicalNetwork(physicalNetworkId, provider)) { @@ -4703,7 +4703,7 @@ protected long configureCustomRootDiskSize(Map customParameters, } if (customParameters.containsKey(VmDetailConstants.ROOT_DISK_SIZE)) { - Long rootDiskSize = NumbersUtil.parseLong(customParameters.get(VmDetailConstants.ROOT_DISK_SIZE), -1); + long rootDiskSize = NumbersUtil.parseLong(customParameters.get(VmDetailConstants.ROOT_DISK_SIZE), -1); if (rootDiskSize <= 0) { throw new InvalidParameterValueException("Root disk size should be a positive number."); } @@ -4822,7 +4822,7 @@ private UserVmVO commitUserVm(final boolean isImport, final DataCenter zone, fin final Map> extraDhcpOptionMap, final Map dataDiskTemplateToDiskOfferingMap, final Map userVmOVFPropertiesMap, final VirtualMachine.PowerState powerState, final boolean dynamicScalingEnabled, String vmType, final Long rootDiskOfferingId, String sshkeypairs, List dataDiskInfoList, Volume volume, Snapshot snapshot) throws InsufficientCapacityException { - Long selectedGuestOsId = guestOsId != null ? guestOsId : template.getGuestOSId(); + long selectedGuestOsId = guestOsId != null ? guestOsId : template.getGuestOSId(); UserVmVO vm = new UserVmVO(id, instanceName, displayName, template.getId(), hypervisorType, selectedGuestOsId, offering.isOfferHA(), offering.getLimitCpuUse(), owner.getDomainId(), owner.getId(), userId, offering.getId(), userData, userDataId, userDataDetails, hostName); vm.setUuid(uuidName); @@ -5381,7 +5381,7 @@ private void addUserVMCmdlineArgs(Long vmId, VirtualMachineProfile profile, Depl if (dc.getDns2() != null) { buf.append(" dns2=").append(dc.getDns2()); } - logger.info("cmdline details: "+ buf.toString()); + logger.info("cmdline details: "+ buf); } @Override @@ -5641,7 +5641,7 @@ private void checkForceStopVmPermission(Account callingAccount) { public UserVm stopVirtualMachine(long vmId, boolean forced) throws ConcurrentOperationException { // Input validation Account caller = CallContext.current().getCallingAccount(); - Long userId = CallContext.current().getCallingUserId(); + long userId = CallContext.current().getCallingUserId(); // if account is removed, return error if (caller != null && caller.getRemoved() != null) { @@ -6919,7 +6919,7 @@ protected void addExtraConfig(UserVm vm, String extraConfig) { } else if (hypervisorType.equals(HypervisorType.VMware)) { persistExtraConfigVmware(decodedUrl, vm); } else { - String msg = String.format("This hypervisor %s is not supported for use with this feature", hypervisorType.toString()); + String msg = String.format("This hypervisor %s is not supported for use with this feature", hypervisorType); throw new CloudRuntimeException(msg); } } @@ -7265,7 +7265,7 @@ private DeployDestination chooseVmMigrationDestination(VMInstanceVO vm, Host src vm.setLastHostId(null); // Last host does not have higher priority in vm migration final ServiceOfferingVO offering = serviceOfferingDao.findById(vm.getId(), vm.getServiceOfferingId()); final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm, null, offering, null, null); - final Long srcHostId = srcHost.getId(); + final long srcHostId = srcHost.getId(); final Host host = _hostDao.findById(srcHostId); ExcludeList excludes = new ExcludeList(); excludes.addHost(srcHostId); @@ -7918,7 +7918,7 @@ public UserVm moveVmToUser(final AssignVMCmd cmd) throws ResourceAllocationExcep Long domainId = cmd.getDomainId(); Long projectId = cmd.getProjectId(); - Long oldAccountId = vm.getAccountId(); + long oldAccountId = vm.getAccountId(); String newAccountName = cmd.getAccountName(); final Account oldAccount = _accountService.getActiveAccountById(oldAccountId); final Account newAccount = _accountMgr.finalizeOwner(caller, newAccountName, domainId, projectId); @@ -8547,7 +8547,7 @@ protected void selectApplicableNetworkToCreateVm(Account newAccount, DataCenterV protected void addDefaultSecurityGroupToSecurityGroupIdList(Account newAccount, List securityGroupIdList) { logger.debug("Adding default security group to security group list if not already in it."); - Long newAccountId = newAccount.getId(); + long newAccountId = newAccount.getId(); SecurityGroup defaultGroup = _securityGroupMgr.getDefaultSecurityGroup(newAccountId); boolean defaultGroupPresent = false; @@ -8694,7 +8694,7 @@ protected NetworkVO createApplicableNetworkToCreateVm(Account newAccount, DataCe logger.trace("Creating an applicable network to create the VM."); NetworkVO defaultNetwork; - Long zoneId = zone.getId(); + long zoneId = zone.getId(); Account caller = CallContext.current().getCallingAccount(); NetworkOfferingVO requiredOffering = getOfferingWithRequiredAvailabilityForNetworkCreation(); String requiredOfferingTags = requiredOffering.getTags(); @@ -9454,7 +9454,7 @@ private boolean checkStatusOfVolumeSnapshots(VirtualMachine vm, Volume.Type type } logger.debug("Found {} no. of volumes of type {} for vm with VM ID {}", listVolumes.size(), type, vm); for (VolumeVO volume : listVolumes) { - Long volumeId = volume.getId(); + long volumeId = volume.getId(); logger.debug("Checking status of snapshots for Volume: {}", volume); List ongoingSnapshots = _snapshotDao.listByStatus(volumeId, Snapshot.State.Creating, Snapshot.State.CreatedOnPrimary, Snapshot.State.BackingUp); int ongoingSnapshotsCount = ongoingSnapshots.size(); @@ -9473,12 +9473,12 @@ private void checkForUnattachedVolumes(long vmId, List volumes) { for (VolumeVO volume : volumes) { if (volume.getInstanceId() == null || vmId != volume.getInstanceId() || volume.getVolumeType() != Volume.Type.DATADISK) { - sb.append(volume.toString() + "; "); + sb.append(volume + "; "); } } if (!StringUtils.isEmpty(sb.toString())) { - throw new InvalidParameterValueException("The following supplied volumes are not DATADISK attached to the VM: " + sb.toString()); + throw new InvalidParameterValueException("The following supplied volumes are not DATADISK attached to the VM: " + sb); } } @@ -9486,7 +9486,7 @@ private void validateVolumes(List volumes) { for (VolumeVO volume : volumes) { if (!(volume.getVolumeType() == Volume.Type.ROOT || volume.getVolumeType() == Volume.Type.DATADISK)) { - throw new InvalidParameterValueException("Please specify volume of type " + Volume.Type.DATADISK.toString() + " or " + Volume.Type.ROOT.toString()); + throw new InvalidParameterValueException("Please specify volume of type " + Volume.Type.DATADISK + " or " + Volume.Type.ROOT); } if (volume.isDeleteProtection()) { throw new InvalidParameterValueException(String.format( @@ -9580,7 +9580,7 @@ public UserVm importVM(final DataCenter zone, final Host host, final VirtualMach final String uuidName = _uuidMgr.generateUuid(UserVm.class, null); final Host lastHost = powerState != VirtualMachine.PowerState.PowerOn ? host : null; - final Boolean dynamicScalingEnabled = checkIfDynamicScalingCanBeEnabled(null, serviceOffering, template, zone.getId()); + final boolean dynamicScalingEnabled = checkIfDynamicScalingCanBeEnabled(null, serviceOffering, template, zone.getId()); return commitUserVm(true, zone, host, lastHost, template, hostName, displayName, owner, null, null, userData, null, null, isDisplayVm, keyboard, accountId, userId, serviceOffering, template.getFormat().equals(ImageFormat.ISO), guestOsId, sshPublicKeys, networkNicMap, @@ -9642,7 +9642,7 @@ private void updateDetailsWithRootDiskAttributes(Map details, Vm } private void checkRootDiskSizeAgainstBackup(Long instanceVolumeSize,DiskOffering rootDiskOffering, Long backupVolumeSize) { - Long instanceRootDiskSize = rootDiskOffering.isCustomized() ? instanceVolumeSize : rootDiskOffering.getDiskSize() / GiB_TO_BYTES; + long instanceRootDiskSize = rootDiskOffering.isCustomized() ? instanceVolumeSize : rootDiskOffering.getDiskSize() / GiB_TO_BYTES; if (instanceRootDiskSize < backupVolumeSize) { throw new InvalidParameterValueException( String.format("Instance volume root disk size %d[GiB] cannot be less than the backed-up volume size %d[GiB].", @@ -9719,7 +9719,7 @@ public UserVm allocateVMFromBackup(CreateVMFromBackupCmd cmd) throws Insufficien Long size = cmd.getSize(); Long diskOfferingId = cmd.getDiskOfferingId(); - Boolean isIso = template.getFormat().equals(ImageFormat.ISO); + boolean isIso = template.getFormat().equals(ImageFormat.ISO); if (diskOfferingId != null) { if (!isIso) { throw new InvalidParameterValueException(ApiConstants.DISK_OFFERING_ID + " parameter is supported for creating instance from backup only for ISO. For creating VMs with templates, please use the parameter " + ApiConstants.DATADISKS_DETAILS); diff --git a/server/src/test/java/com/cloud/vm/UserVmManagerImplTest.java b/server/src/test/java/com/cloud/vm/UserVmManagerImplTest.java index 7b1da4b75e2b..f752dc31f181 100644 --- a/server/src/test/java/com/cloud/vm/UserVmManagerImplTest.java +++ b/server/src/test/java/com/cloud/vm/UserVmManagerImplTest.java @@ -59,12 +59,6 @@ import java.util.TimeZone; import java.util.UUID; -import com.cloud.network.as.AutoScaleManager; -import com.cloud.network.dao.FirewallRulesDao; -import com.cloud.network.dao.IPAddressDao; -import com.cloud.network.dao.IPAddressVO; -import com.cloud.network.dao.LoadBalancerVMMapDao; -import com.cloud.network.dao.LoadBalancerVMMapVO; import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.acl.SecurityChecker; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -99,6 +93,7 @@ import org.apache.cloudstack.userdata.UserDataManager; import org.apache.cloudstack.vm.UnmanagedVMsManager; import org.apache.cloudstack.vm.lease.VMLeaseManager; + import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -141,11 +136,17 @@ import com.cloud.kubernetes.cluster.KubernetesServiceHelper; import com.cloud.network.Network; import com.cloud.network.NetworkModel; +import com.cloud.network.as.AutoScaleManager; +import com.cloud.network.dao.FirewallRulesDao; +import com.cloud.network.dao.IPAddressDao; +import com.cloud.network.dao.IPAddressVO; +import com.cloud.network.dao.LoadBalancerVMMapDao; +import com.cloud.network.dao.LoadBalancerVMMapVO; import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.NetworkVO; -import com.cloud.network.element.UserDataServiceProvider; import com.cloud.network.dao.PhysicalNetworkDao; import com.cloud.network.dao.PhysicalNetworkVO; +import com.cloud.network.element.UserDataServiceProvider; import com.cloud.network.guru.NetworkGuru; import com.cloud.network.rules.FirewallRuleVO; import com.cloud.network.rules.PortForwardingRule; @@ -455,7 +456,7 @@ public class UserVmManagerImplTest { @Mock ServiceOfferingDetailsDao serviceOfferingDetailsDao; - private static final long vmId = 1l; + private static final long vmId = 1L; private static final long zoneId = 2L; private static final long accountId = 3L; private static final long serviceOfferingId = 10L; @@ -470,8 +471,8 @@ public class UserVmManagerImplTest { String[] detailsConstants = {VmDetailConstants.MEMORY, VmDetailConstants.CPU_NUMBER, VmDetailConstants.CPU_SPEED}; - private DiskOfferingVO smallerDisdkOffering = prepareDiskOffering(5l * GiB_TO_BYTES, 1l, 1L, 2L); - private DiskOfferingVO largerDisdkOffering = prepareDiskOffering(10l * GiB_TO_BYTES, 2l, 10L, 20L); + private DiskOfferingVO smallerDisdkOffering = prepareDiskOffering(5L * GiB_TO_BYTES, 1L, 1L, 2L); + private DiskOfferingVO largerDisdkOffering = prepareDiskOffering(10L * GiB_TO_BYTES, 2L, 10L, 20L); Class expectedInvalidParameterValueException = InvalidParameterValueException.class; Class expectedCloudRuntimeException = CloudRuntimeException.class; @@ -514,15 +515,15 @@ public void validateGuestOsIdForUpdateVirtualMachineCommandTestOsTypeNull() { @Test(expected = InvalidParameterValueException.class) public void validateGuestOsIdForUpdateVirtualMachineCommandTestOsTypeNotFound() { - Mockito.when(updateVmCommand.getOsTypeId()).thenReturn(1l); + Mockito.when(updateVmCommand.getOsTypeId()).thenReturn(1L); userVmManagerImpl.validateGuestOsIdForUpdateVirtualMachineCommand(updateVmCommand); } @Test public void validateGuestOsIdForUpdateVirtualMachineCommandTestOsTypeFound() { - Mockito.when(updateVmCommand.getOsTypeId()).thenReturn(1l); - Mockito.when(guestOSDao.findById(1l)).thenReturn(Mockito.mock(GuestOSVO.class)); + Mockito.when(updateVmCommand.getOsTypeId()).thenReturn(1L); + Mockito.when(guestOSDao.findById(1L)).thenReturn(Mockito.mock(GuestOSVO.class)); userVmManagerImpl.validateGuestOsIdForUpdateVirtualMachineCommand(updateVmCommand); } @@ -541,11 +542,10 @@ private ServiceOfferingVO getSvcoffering(int ramSize) { int speed = 128; boolean ha = false; - boolean useLocalStorage = false; ServiceOfferingVO serviceOffering = new ServiceOfferingVO(name, cpu, ramSize, speed, null, null, ha, displayText, false, null, false); - serviceOffering.setDiskOfferingId(1l); + serviceOffering.setDiskOfferingId(1L); return serviceOffering; } @@ -686,7 +686,6 @@ private void verifyMethodsThatAreAlwaysExecuted() throws ResourceUnavailableExce } - @SuppressWarnings("unchecked") private void configureDoNothingForMethodsThatWeDoNotWantToTest() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { Mockito.doNothing().when(userVmManagerImpl).validateInputsAndPermissionForUpdateVirtualMachineCommand(updateVmCommand); Mockito.doReturn(new ArrayList()).when(userVmManagerImpl).getSecurityGroupIdList(updateVmCommand); @@ -758,7 +757,7 @@ private void configureValidateOrReplaceMacAddressTest(int times, String macAddre } @Test - public void testValidatekeyValuePair() throws Exception { + public void testValidatekeyValuePair() { assertTrue(userVmManagerImpl.isValidKeyValuePair("is-a-template=true\nHVM-boot-policy=\nPV-bootloader=pygrub\nPV-args=hvc0")); assertTrue(userVmManagerImpl.isValidKeyValuePair("is-a-template=true HVM-boot-policy= PV-bootloader=pygrub PV-args=hvc0")); assertTrue(userVmManagerImpl.isValidKeyValuePair("nvp.vm-uuid=34b3d5ea-1c25-4bb0-9250-8dc3388bfa9b")); @@ -774,8 +773,8 @@ public void configureCustomRootDiskSizeTest() { String vmDetailsRootDiskSize = "123"; Map customParameters = new HashMap<>(); customParameters.put(VmDetailConstants.ROOT_DISK_SIZE, vmDetailsRootDiskSize); - long expectedRootDiskSize = 123l * GiB_TO_BYTES; - long offeringRootDiskSize = 0l; + long expectedRootDiskSize = 123L * GiB_TO_BYTES; + long offeringRootDiskSize = 0L; prepareAndRunConfigureCustomRootDiskSizeTest(customParameters, expectedRootDiskSize, 1, offeringRootDiskSize); } @@ -784,8 +783,8 @@ public void configureCustomRootDiskSizeTestExpectExceptionZero() { String vmDetailsRootDiskSize = "0"; Map customParameters = new HashMap<>(); customParameters.put(VmDetailConstants.ROOT_DISK_SIZE, vmDetailsRootDiskSize); - long expectedRootDiskSize = 0l; - long offeringRootDiskSize = 0l; + long expectedRootDiskSize = 0L; + long offeringRootDiskSize = 0L; prepareAndRunConfigureCustomRootDiskSizeTest(customParameters, expectedRootDiskSize, 1, offeringRootDiskSize); } @@ -794,31 +793,31 @@ public void configureCustomRootDiskSizeTestExpectExceptionNegativeNum() { String vmDetailsRootDiskSize = "-123"; Map customParameters = new HashMap<>(); customParameters.put(VmDetailConstants.ROOT_DISK_SIZE, vmDetailsRootDiskSize); - long expectedRootDiskSize = -123l * GiB_TO_BYTES; - long offeringRootDiskSize = 0l; + long expectedRootDiskSize = -123L * GiB_TO_BYTES; + long offeringRootDiskSize = 0L; prepareAndRunConfigureCustomRootDiskSizeTest(customParameters, expectedRootDiskSize, 1, offeringRootDiskSize); } @Test public void configureCustomRootDiskSizeTestEmptyParameters() { Map customParameters = new HashMap<>(); - long expectedRootDiskSize = 99l * GiB_TO_BYTES; - long offeringRootDiskSize = 0l; + long expectedRootDiskSize = 99L * GiB_TO_BYTES; + long offeringRootDiskSize = 0L; prepareAndRunConfigureCustomRootDiskSizeTest(customParameters, expectedRootDiskSize, 1, offeringRootDiskSize); } @Test public void configureCustomRootDiskSizeTestEmptyParametersAndOfferingRootSize() { Map customParameters = new HashMap<>(); - long expectedRootDiskSize = 10l * GiB_TO_BYTES; - long offeringRootDiskSize = 10l * GiB_TO_BYTES; + long expectedRootDiskSize = 10L * GiB_TO_BYTES; + long offeringRootDiskSize = 10L * GiB_TO_BYTES; prepareAndRunConfigureCustomRootDiskSizeTest(customParameters, expectedRootDiskSize, 1, offeringRootDiskSize); } private void prepareAndRunConfigureCustomRootDiskSizeTest(Map customParameters, long expectedRootDiskSize, int timesVerifyIfHypervisorSupports, Long offeringRootDiskSize) { VMTemplateVO template = Mockito.mock(VMTemplateVO.class); - Mockito.when(template.getId()).thenReturn(1l); + Mockito.when(template.getId()).thenReturn(1L); Mockito.when(template.getSize()).thenReturn(99L * GiB_TO_BYTES); Mockito.when(templateDao.findById(Mockito.anyLong())).thenReturn(template); @@ -887,7 +886,7 @@ public void prepareResizeVolumeCmdTestSameOfferingSize() { @Test public void prepareResizeVolumeCmdTestOfferingRootSizeZero() { - DiskOfferingVO rootSizeZero = prepareDiskOffering(0l, 3l, 100L, 200L); + DiskOfferingVO rootSizeZero = prepareDiskOffering(0L, 3L, 100L, 200L); prepareAndRunResizeVolumeTest(null, 100L, 200L, smallerDisdkOffering, rootSizeZero); } @@ -897,7 +896,7 @@ public void prepareResizeVolumeCmdTestNewOfferingSmaller() { } private void prepareAndRunResizeVolumeTest(Long expectedOfferingId, long expectedMinIops, long expectedMaxIops, DiskOfferingVO currentRootDiskOffering, DiskOfferingVO newRootDiskOffering) { - long rootVolumeId = 1l; + long rootVolumeId = 1L; VolumeVO rootVolumeOfVm = Mockito.mock(VolumeVO.class); Mockito.when(rootVolumeOfVm.getId()).thenReturn(rootVolumeId); @@ -944,7 +943,7 @@ public void testUserDataAllowOverride() { String finalUserdata = userVmManagerImpl.finalizeUserData(null, userDataId, template); - Assert.assertEquals(finalUserdata, templateUserData); + Assert.assertEquals(templateUserData, finalUserdata); } @Test @@ -961,7 +960,7 @@ public void testUserDataWithoutTemplate() { String finalUserdata = userVmManagerImpl.finalizeUserData(null, userDataId, template); - Assert.assertEquals(finalUserdata, userData); + Assert.assertEquals(userData, finalUserdata); } @Test @@ -977,7 +976,7 @@ public void testUserDataAllowOverrideWithoutAPIuserdata() { String finalUserdata = userVmManagerImpl.finalizeUserData(null, null, template); - Assert.assertEquals(finalUserdata, templateUserData); + Assert.assertEquals(templateUserData, finalUserdata); } @Test @@ -988,7 +987,7 @@ public void testUserDataAllowOverrideWithUserdataText() { String finalUserdata = userVmManagerImpl.finalizeUserData(userData, null, template); - Assert.assertEquals(finalUserdata, userData); + Assert.assertEquals(userData, finalUserdata); } @Test(expected = InvalidParameterValueException.class) @@ -1009,9 +1008,7 @@ public void testResetVMUserDataVMStateNotStopped() { try { userVmManagerImpl.resetVMUserData(cmd); - } catch (ResourceUnavailableException e) { - throw new RuntimeException(e); - } catch (InsufficientCapacityException e) { + } catch (ResourceUnavailableException | InsufficientCapacityException e) { throw new RuntimeException(e); } } @@ -1037,9 +1034,7 @@ public void testResetVMUserDataDontAcceptBothUserdataAndUserdataId() { try { userVmManagerImpl.resetVMUserData(cmd); - } catch (ResourceUnavailableException e) { - throw new RuntimeException(e); - } catch (InsufficientCapacityException e) { + } catch (ResourceUnavailableException | InsufficientCapacityException e) { throw new RuntimeException(e); } } @@ -1073,14 +1068,12 @@ public void testResetVMUserDataSuccessResetWithUserdata() { try { doNothing().when(userVmManagerImpl).updateUserData(userVmVO); userVmManagerImpl.resetVMUserData(cmd); - } catch (ResourceUnavailableException e) { - throw new RuntimeException(e); - } catch (InsufficientCapacityException e) { + } catch (ResourceUnavailableException | InsufficientCapacityException e) { throw new RuntimeException(e); } Assert.assertEquals("testUserdata", userVmVO.getUserData()); - Assert.assertEquals(null, userVmVO.getUserDataId()); + Assert.assertNull(userVmVO.getUserDataId()); } @Test @@ -1114,9 +1107,7 @@ public void testResetVMUserDataSuccessResetWithUserdataId() { try { doNothing().when(userVmManagerImpl).updateUserData(userVmVO); userVmManagerImpl.resetVMUserData(cmd); - } catch (ResourceUnavailableException e) { - throw new RuntimeException(e); - } catch (InsufficientCapacityException e) { + } catch (ResourceUnavailableException | InsufficientCapacityException e) { throw new RuntimeException(e); } @@ -1491,10 +1482,10 @@ public void testRestoreVMWithVolumeSnapshots() throws ResourceUnavailableExcepti } @Test(expected = InvalidParameterValueException.class) - public void testRestoreVirtualMachineNoOwner() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { - long userId = 1l; - long accountId = 2l; - long newTemplateId = 2l; + public void testRestoreVirtualMachineNoOwner() throws ResourceUnavailableException, InsufficientCapacityException { + long userId = 1L; + long accountId = 2L; + long newTemplateId = 2L; when(accountMock.getId()).thenReturn(userId); when(userVmDao.findById(vmId)).thenReturn(userVmVoMock); when(userVmVoMock.getAccountId()).thenReturn(accountId); @@ -1504,10 +1495,10 @@ public void testRestoreVirtualMachineNoOwner() throws ResourceUnavailableExcepti } @Test(expected = PermissionDeniedException.class) - public void testRestoreVirtualMachineOwnerDisabled() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { - long userId = 1l; - long accountId = 2l; - long newTemplateId = 2l; + public void testRestoreVirtualMachineOwnerDisabled() throws ResourceUnavailableException, InsufficientCapacityException { + long userId = 1L; + long accountId = 2L; + long newTemplateId = 2L; when(accountMock.getId()).thenReturn(userId); when(userVmDao.findById(vmId)).thenReturn(userVmVoMock); when(userVmVoMock.getAccountId()).thenReturn(accountId); @@ -1518,10 +1509,10 @@ public void testRestoreVirtualMachineOwnerDisabled() throws ResourceUnavailableE } @Test(expected = CloudRuntimeException.class) - public void testRestoreVirtualMachineNotInRightState() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { - long userId = 1l; - long accountId = 2l; - long newTemplateId = 2l; + public void testRestoreVirtualMachineNotInRightState() throws ResourceUnavailableException, InsufficientCapacityException { + long userId = 1L; + long accountId = 2L; + long newTemplateId = 2L; when(accountMock.getId()).thenReturn(userId); when(userVmDao.findById(vmId)).thenReturn(userVmVoMock); when(userVmVoMock.getAccountId()).thenReturn(accountId); @@ -1533,11 +1524,11 @@ public void testRestoreVirtualMachineNotInRightState() throws ResourceUnavailabl } @Test(expected = InvalidParameterValueException.class) - public void testRestoreVirtualMachineNoRootVolume() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { - long userId = 1l; - long accountId = 2l; - long currentTemplateId = 1l; - long newTemplateId = 2l; + public void testRestoreVirtualMachineNoRootVolume() throws ResourceUnavailableException, InsufficientCapacityException { + long userId = 1L; + long accountId = 2L; + long currentTemplateId = 1L; + long newTemplateId = 2L; when(accountMock.getId()).thenReturn(userId); when(userVmDao.findById(vmId)).thenReturn(userVmVoMock); when(userVmVoMock.getAccountId()).thenReturn(accountId); @@ -1548,17 +1539,17 @@ public void testRestoreVirtualMachineNoRootVolume() throws ResourceUnavailableEx VMTemplateVO currentTemplate = Mockito.mock(VMTemplateVO.class); when(templateDao.findById(currentTemplateId)).thenReturn(currentTemplate); - when(volumeDaoMock.findByInstanceAndType(vmId, Volume.Type.ROOT)).thenReturn(new ArrayList()); + when(volumeDaoMock.findByInstanceAndType(vmId, Volume.Type.ROOT)).thenReturn(new ArrayList<>()); userVmManagerImpl.restoreVirtualMachine(accountMock, vmId, newTemplateId, null, false, null); } @Test(expected = InvalidParameterValueException.class) - public void testRestoreVirtualMachineMoreThanOneRootVolume() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { - long userId = 1l; - long accountId = 2l; - long currentTemplateId = 1l; - long newTemplateId = 2l; + public void testRestoreVirtualMachineMoreThanOneRootVolume() throws ResourceUnavailableException, InsufficientCapacityException { + long userId = 1L; + long accountId = 2L; + long currentTemplateId = 1L; + long newTemplateId = 2L; when(accountMock.getId()).thenReturn(userId); when(userVmDao.findById(vmId)).thenReturn(userVmVoMock); when(userVmVoMock.getAccountId()).thenReturn(accountId); @@ -1581,11 +1572,11 @@ public void testRestoreVirtualMachineMoreThanOneRootVolume() throws ResourceUnav } @Test(expected = InvalidParameterValueException.class) - public void testRestoreVirtualMachineWithVMSnapshots() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { - long userId = 1l; - long accountId = 2l; - long currentTemplateId = 1l; - long newTemplateId = 2l; + public void testRestoreVirtualMachineWithVMSnapshots() throws ResourceUnavailableException, InsufficientCapacityException { + long userId = 1L; + long accountId = 2L; + long currentTemplateId = 1L; + long newTemplateId = 2L; when(accountMock.getId()).thenReturn(userId); when(userVmDao.findById(vmId)).thenReturn(userVmVoMock); when(userVmVoMock.getAccountId()).thenReturn(accountId); @@ -1615,9 +1606,9 @@ public void addCurrentDetailValueToInstanceDetailsMapIfNewValueWasNotSpecifiedTe userVmManagerImpl.addCurrentDetailValueToInstanceDetailsMapIfNewValueWasNotSpecified(null, customParameters, detailsConstant, currentValue); } - Assert.assertEquals(customParameters.get(VmDetailConstants.MEMORY), "2048"); - Assert.assertEquals(customParameters.get(VmDetailConstants.CPU_NUMBER), "4"); - Assert.assertEquals(customParameters.get(VmDetailConstants.CPU_SPEED), "1000"); + Assert.assertEquals("2048", customParameters.get(VmDetailConstants.MEMORY)); + Assert.assertEquals("4", customParameters.get(VmDetailConstants.CPU_NUMBER)); + Assert.assertEquals("1000", customParameters.get(VmDetailConstants.CPU_SPEED)); } @Test @@ -1656,9 +1647,9 @@ public void addCurrentDetailValueToInstanceDetailsMapIfNewValueWasNotSpecifiedTe userVmManagerImpl.addCurrentDetailValueToInstanceDetailsMapIfNewValueWasNotSpecified(321, customParameters, detailsConstant, currentValue); } - Assert.assertEquals(customParameters.get(VmDetailConstants.MEMORY), "2048"); - Assert.assertEquals(customParameters.get(VmDetailConstants.CPU_NUMBER), "4"); - Assert.assertEquals(customParameters.get(VmDetailConstants.CPU_SPEED),"1000"); + Assert.assertEquals("2048", customParameters.get(VmDetailConstants.MEMORY)); + Assert.assertEquals("4", customParameters.get(VmDetailConstants.CPU_NUMBER)); + Assert.assertEquals("1000", customParameters.get(VmDetailConstants.CPU_SPEED)); } @Test @@ -1667,7 +1658,7 @@ public void updateInstanceDetailsMapWithCurrentValuesForAbsentDetailsTestAllCons Mockito.doReturn(1L).when(vmInstanceMock).getId(); Mockito.doReturn(1L).when(vmInstanceMock).getServiceOfferingId(); Mockito.doReturn(serviceOffering).when(_serviceOfferingDao).findByIdIncludingRemoved(Mockito.anyLong(), Mockito.anyLong()); - userVmManagerImpl.updateInstanceDetailsMapWithCurrentValuesForAbsentDetails(null, vmInstanceMock, 0l); + userVmManagerImpl.updateInstanceDetailsMapWithCurrentValuesForAbsentDetails(null, vmInstanceMock, 0L); Mockito.verify(userVmManagerImpl).addCurrentDetailValueToInstanceDetailsMapIfNewValueWasNotSpecified(Mockito.any(), Mockito.any(), Mockito.eq(VmDetailConstants.CPU_SPEED), Mockito.any()); Mockito.verify(userVmManagerImpl).addCurrentDetailValueToInstanceDetailsMapIfNewValueWasNotSpecified(Mockito.any(), Mockito.any(), Mockito.eq(VmDetailConstants.MEMORY), Mockito.any()); @@ -1830,10 +1821,10 @@ public void checkExpungeVmPermissionTestAccountIsAdminHasApiAccessReturnNothing @Test public void validateIfVmSupportsMigrationTestVmIsNullThrowsInvalidParameterValueException() { - String expectedMessage = String.format("There is no VM by ID [%s].", 1l); + String expectedMessage = String.format("There is no VM by ID [%s].", 1L); InvalidParameterValueException assertThrows = Assert.assertThrows(expectedInvalidParameterValueException, () -> { - userVmManagerImpl.validateIfVmSupportsMigration(null, 1l); + userVmManagerImpl.validateIfVmSupportsMigration(null, 1L); }); Assert.assertEquals(expectedMessage, assertThrows.getMessage()); @@ -1845,7 +1836,7 @@ public void validateIfVmSupportsMigrationTestVmIsRunningThrowsInvalidParameterVa Mockito.doReturn(VirtualMachine.State.Running).when(userVmVoMock).getState(); InvalidParameterValueException assertThrows = Assert.assertThrows(expectedInvalidParameterValueException, () -> { - userVmManagerImpl.validateIfVmSupportsMigration(userVmVoMock, 1l); + userVmManagerImpl.validateIfVmSupportsMigration(userVmVoMock, 1L); }); Assert.assertEquals(expectedMessage, assertThrows.getMessage()); @@ -1856,7 +1847,7 @@ public void validateIfVmSupportsMigrationTestVmIsSharedFileSystemInstanceThrowsI Mockito.doReturn(UserVmManager.SHAREDFSVM).when(userVmVoMock).getUserVmType(); InvalidParameterValueException assertThrows = Assert.assertThrows(expectedInvalidParameterValueException, () -> { - userVmManagerImpl.validateIfVmSupportsMigration(userVmVoMock, 1l); + userVmManagerImpl.validateIfVmSupportsMigration(userVmVoMock, 1L); }); Assert.assertEquals("Migration is not supported for Shared FileSystem Instances.", assertThrows.getMessage()); @@ -1864,13 +1855,13 @@ public void validateIfVmSupportsMigrationTestVmIsSharedFileSystemInstanceThrowsI @Test public void validateIfVmSupportsMigrationTestVmIsNotRunningDoesNotThrowInvalidParameterValueException() { - userVmManagerImpl.validateIfVmSupportsMigration(userVmVoMock, 1l); + userVmManagerImpl.validateIfVmSupportsMigration(userVmVoMock, 1L); } @Test public void validateOldAndNewAccountsTestBothAreValidDoNothing() { Account newAccount = Mockito.mock(Account.class); - Mockito.doReturn(1l).when(newAccount).getAccountId(); + Mockito.doReturn(1L).when(newAccount).getAccountId(); userVmManagerImpl.validateOldAndNewAccounts(accountMock, newAccount, 1L, "", 1L); } @@ -1891,7 +1882,7 @@ public void validateOldAndNewAccountsTestNewAccountIsNullThrowsInvalidParameterV String expectedMessage = String.format("Invalid new account [%s] for VM in domain [%s].", assignVmCmdMock.getAccountName(), assignVmCmdMock.getDomainId()); InvalidParameterValueException assertThrows = Assert.assertThrows(expectedInvalidParameterValueException, () -> { - userVmManagerImpl.validateOldAndNewAccounts(accountMock, null, 1l, assignVmCmdMock.getAccountName(), assignVmCmdMock.getDomainId()); + userVmManagerImpl.validateOldAndNewAccounts(accountMock, null, 1L, assignVmCmdMock.getAccountName(), assignVmCmdMock.getDomainId()); }); Assert.assertEquals(expectedMessage, assertThrows.getMessage()); @@ -1899,12 +1890,12 @@ public void validateOldAndNewAccountsTestNewAccountIsNullThrowsInvalidParameterV @Test public void validateOldAndNewAccountsTestNewAccountStateIsDisabledThrowsInvalidParameterValueException() { - String expectedMessage = String.format("The new account owner [%s] is disabled.", accountMock.toString()); + String expectedMessage = String.format("The new account owner [%s] is disabled.", accountMock); Mockito.doReturn(Account.State.DISABLED).when(accountMock).getState(); InvalidParameterValueException assertThrows = Assert.assertThrows(expectedInvalidParameterValueException, () -> { - userVmManagerImpl.validateOldAndNewAccounts(accountMock, accountMock, 1l, "", 1l); + userVmManagerImpl.validateOldAndNewAccounts(accountMock, accountMock, 1L, "", 1L); }); Assert.assertEquals(expectedMessage, assertThrows.getMessage()); @@ -1912,12 +1903,12 @@ public void validateOldAndNewAccountsTestNewAccountStateIsDisabledThrowsInvalidP @Test public void validateOldAndNewAccountsTestOldAccountIsTheSameAsNewAccountThrowsInvalidParameterValueException() { - String expectedMessage = String.format("The new account [%s] is the same as the old account.", accountMock.toString()); + String expectedMessage = String.format("The new account [%s] is the same as the old account.", accountMock); Mockito.doReturn(Account.State.ENABLED).when(accountMock).getState(); InvalidParameterValueException assertThrows = Assert.assertThrows(expectedInvalidParameterValueException, () -> { - userVmManagerImpl.validateOldAndNewAccounts(accountMock, accountMock, 1l, "", 1l); + userVmManagerImpl.validateOldAndNewAccounts(accountMock, accountMock, 1L, "", 1L); }); Assert.assertEquals(expectedMessage, assertThrows.getMessage()); @@ -1926,9 +1917,9 @@ public void validateOldAndNewAccountsTestOldAccountIsTheSameAsNewAccountThrowsIn @Test public void validateOldAndNewAccountsTestOldAccountIsNotTheSameAsNewAccountDoesNotThrowInvalidParameterValueException() { AccountVO oldAccount = new AccountVO(); - Mockito.doReturn(1l).when(accountMock).getAccountId(); + Mockito.doReturn(1L).when(accountMock).getAccountId(); - userVmManagerImpl.validateOldAndNewAccounts(oldAccount, accountMock, 1l, "", 1l); + userVmManagerImpl.validateOldAndNewAccounts(oldAccount, accountMock, 1L, "", 1L); } @Test @@ -1948,7 +1939,7 @@ public void validateIfVmHasNoRulesTestPortForwardingRulesExistThrowsInvalidParam Mockito.doReturn(portForwardingRulesListMock).when(portForwardingRulesDaoMock).listByVm(Mockito.anyLong()); InvalidParameterValueException assertThrows = Assert.assertThrows(expectedInvalidParameterValueException, () -> { - userVmManagerImpl.validateIfVmHasNoRules(userVmVoMock, 1l); + userVmManagerImpl.validateIfVmHasNoRules(userVmVoMock, 1L); }); Assert.assertEquals(expectedMessage, assertThrows.getMessage()); @@ -1961,7 +1952,7 @@ public void validateIfVmHasNoRulesTestStaticNatRulesExistThrowsInvalidParameterV Mockito.doReturn(firewallRuleVoListMock).when(firewallRulesDaoMock).listStaticNatByVmId(Mockito.anyLong()); InvalidParameterValueException assertThrows = Assert.assertThrows(expectedInvalidParameterValueException, () -> { - userVmManagerImpl.validateIfVmHasNoRules(userVmVoMock, 1l); + userVmManagerImpl.validateIfVmHasNoRules(userVmVoMock, 1L); }); Assert.assertEquals(expectedMessage, assertThrows.getMessage()); @@ -1974,7 +1965,7 @@ public void validateIfVmHasNoRulesTestLoadBalancingRulesExistThrowsInvalidParame Mockito.doReturn(loadBalancerVmMapVoListMock).when(loadBalancerVmMapDaoMock).listByInstanceId(Mockito.anyLong()); InvalidParameterValueException assertThrows = Assert.assertThrows(expectedInvalidParameterValueException, () -> { - userVmManagerImpl.validateIfVmHasNoRules(userVmVoMock, 1l); + userVmManagerImpl.validateIfVmHasNoRules(userVmVoMock, 1L); }); Assert.assertEquals(expectedMessage, assertThrows.getMessage()); @@ -1984,14 +1975,14 @@ public void validateIfVmHasNoRulesTestLoadBalancingRulesExistThrowsInvalidParame public void validateIfVmHasNoRulesTestOneToOneNatRulesExistThrowsInvalidParameterValueException() { String expectedMessage = String.format("Remove the One to One Nat rule for VM [%s] for IP [%s].", userVmVoMock, ipAddressVoMock.toString()); - LinkedList ipAddressVoList = new LinkedList(); + LinkedList ipAddressVoList = new LinkedList<>(); Mockito.doReturn(ipAddressVoList).when(ipAddressDaoMock).findAllByAssociatedVmId(Mockito.anyLong()); ipAddressVoList.add(ipAddressVoMock); Mockito.doReturn(true).when(ipAddressVoMock).isOneToOneNat(); InvalidParameterValueException assertThrows = Assert.assertThrows(expectedInvalidParameterValueException, () -> { - userVmManagerImpl.validateIfVmHasNoRules(userVmVoMock, 1l); + userVmManagerImpl.validateIfVmHasNoRules(userVmVoMock, 1L); }); Assert.assertEquals(expectedMessage, assertThrows.getMessage()); @@ -1999,13 +1990,13 @@ public void validateIfVmHasNoRulesTestOneToOneNatRulesExistThrowsInvalidParamete @Test public void validateIfVmHasNoRulesTestOneToOneNatRulesDoNotExistDoesNotThrowInvalidParameterValueException() { - userVmManagerImpl.validateIfVmHasNoRules(userVmVoMock, 1l); + userVmManagerImpl.validateIfVmHasNoRules(userVmVoMock, 1L); } @Test public void verifyResourceLimitsForAccountAndStorageTestCountOnlyRunningVmsInResourceLimitationIsTrueDoesNotCallVmResourceLimitCheck() throws ResourceAllocationException { List reservations = new ArrayList<>(); - LinkedList volumeVoList = new LinkedList(); + LinkedList volumeVoList = new LinkedList<>(); Mockito.doReturn(true).when(userVmManagerImpl).countOnlyRunningVmsInResourceLimitation(); userVmManagerImpl.verifyResourceLimitsForAccountAndStorage(accountMock, userVmVoMock, serviceOfferingVoMock, volumeVoList, virtualMachineTemplateMock, reservations); @@ -2017,7 +2008,7 @@ public void verifyResourceLimitsForAccountAndStorageTestCountOnlyRunningVmsInRes @Test public void verifyResourceLimitsForAccountAndStorageTestCountOnlyRunningVmsInResourceLimitationIsFalseCallsVmResourceLimitCheck() throws ResourceAllocationException { List reservations = new ArrayList<>(); - LinkedList volumeVoList = new LinkedList(); + LinkedList volumeVoList = new LinkedList<>(); Mockito.doReturn(false).when(userVmManagerImpl).countOnlyRunningVmsInResourceLimitation(); userVmManagerImpl.verifyResourceLimitsForAccountAndStorage(accountMock, userVmVoMock, serviceOfferingVoMock, volumeVoList, virtualMachineTemplateMock, reservations); @@ -2046,7 +2037,7 @@ public void validateIfNewOwnerHasAccessToTemplateTestCallCheckAccessWhenTemplate @Test public void updateVmOwnerTestCallsSetAccountIdSetDomainIdAndPersist() { - userVmManagerImpl.updateVmOwner(accountMock, userVmVoMock, 1l, 1l); + userVmManagerImpl.updateVmOwner(accountMock, userVmVoMock, 1L, 1L); Mockito.verify(userVmVoMock).setAccountId(Mockito.anyLong()); Mockito.verify(userVmVoMock).setDomainId(Mockito.anyLong()); @@ -2107,7 +2098,7 @@ public void addDefaultNetworkToNetworkListTestDefaultNetworkIsNotNullAddNetworkT @Test public void allocateNetworksForVmTestCallsNetworkManagerAllocate() throws InsufficientCapacityException { - LinkedHashMap> networks = new LinkedHashMap>(); + LinkedHashMap> networks = new LinkedHashMap<>(); Mockito.doReturn(userVmVoMock).when(virtualMachineManager).findById(Mockito.anyLong()); @@ -2119,7 +2110,7 @@ public void allocateNetworksForVmTestCallsNetworkManagerAllocate() throws Insuff @Test public void addSecurityGroupsToVmTestIsVmWareAndSecurityGroupIdListIsNotNullThrowsInvalidParameterValueException() { String expectedMessage = "Security group feature is not supported for VMWare hypervisor."; - LinkedList securityGroupIdList = new LinkedList(); + LinkedList securityGroupIdList = new LinkedList<>(); Mockito.doReturn(Hypervisor.HypervisorType.VMware).when(virtualMachineTemplateMock).getHypervisorType(); @@ -2132,7 +2123,7 @@ public void addSecurityGroupsToVmTestIsVmWareAndSecurityGroupIdListIsNotNullThro @Test public void addSecurityGroupsToVmTestIsNotVmWareDefaultNetworkIsNullAndNetworkModelCanAddDefaultSecurityGroupCallsAddDefaultSecurityGroupToSecurityGroupIdList() { - LinkedList securityGroupIdList = new LinkedList(); + LinkedList securityGroupIdList = new LinkedList<>(); Mockito.doReturn(Hypervisor.HypervisorType.KVM).when(virtualMachineTemplateMock).getHypervisorType(); Mockito.doReturn(true).when(networkModel).canAddDefaultSecurityGroup(); @@ -2146,10 +2137,10 @@ public void addSecurityGroupsToVmTestIsNotVmWareDefaultNetworkIsNullAndNetworkMo @Test public void addNetworksToNetworkIdListTestCallsKeepOldSharedNetworkForVmAndAddAdditionalNetworksToVm() { - LinkedList networkIdList = new LinkedList(); - HashSet applicableNetworks = new HashSet(); - HashMap requestedIPv4ForNics = new HashMap(); - HashMap requestedIPv6ForNics = new HashMap(); + LinkedList networkIdList = new LinkedList<>(); + HashSet applicableNetworks = new HashSet<>(); + HashMap requestedIPv4ForNics = new HashMap<>(); + HashMap requestedIPv6ForNics = new HashMap<>(); userVmManagerImpl.addNetworksToNetworkIdList(userVmVoMock, accountMock, networkIdList, applicableNetworks, requestedIPv4ForNics, requestedIPv6ForNics); @@ -2175,14 +2166,14 @@ public void getOfferingWithRequiredAvailabilityForNetworkCreationTestRequiredOff @Test public void getOfferingWithRequiredAvailabilityForNetworkCreationTestFirstOfferingIsNotEnabledThrowsInvalidParameterValueException() { - String expectedMessage = String.format("Required network offering ID [%s] is not in [%s] state.", 1l, NetworkOffering.State.Enabled); + String expectedMessage = String.format("Required network offering ID [%s] is not in [%s] state.", 1L, NetworkOffering.State.Enabled); Mockito.doReturn(networkOfferingVoListMock).when(networkOfferingDaoMock).listByAvailability(NetworkOffering.Availability.Required, false); Mockito.doReturn(networkOfferingVoMock).when(networkOfferingVoListMock).get(0); Mockito.doReturn(NetworkOffering.State.Disabled).when(networkOfferingVoMock).getState(); - Mockito.doReturn(1l).when(networkOfferingVoMock).getId(); + Mockito.doReturn(1L).when(networkOfferingVoMock).getId(); InvalidParameterValueException assertThrows = Assert.assertThrows(expectedInvalidParameterValueException, () -> { userVmManagerImpl.getOfferingWithRequiredAvailabilityForNetworkCreation(); @@ -2205,9 +2196,9 @@ public void selectApplicableNetworkToCreateVmTestVirtualNetworkIsEmptyThrowsExce @Test public void selectApplicableNetworkToCreateVmTestVirtualNetworkHasMultipleNetworksThrowsInvalidParameterValueException() { - String expectedMessage = String.format("More than one default isolated network has been found for account [%s]; please specify networkIDs.", accountMock.toString()); - HashSet applicableNetworks = new HashSet(); - LinkedList virtualNetworks = new LinkedList(); + String expectedMessage = String.format("More than one default isolated network has been found for account [%s]; please specify networkIDs.", accountMock); + HashSet applicableNetworks = new HashSet<>(); + LinkedList virtualNetworks = new LinkedList<>(); Mockito.doReturn(virtualNetworks).when(networkModel).listNetworksForAccount(Mockito.anyLong(), Mockito.anyLong(), Mockito.any()); @@ -2223,7 +2214,7 @@ public void selectApplicableNetworkToCreateVmTestVirtualNetworkHasMultipleNetwor @Test public void selectApplicableNetworkToCreateVmTestVirtualNetworkHasOneNetworkCallsNetworkDaoFindById() throws InsufficientCapacityException, ResourceAllocationException { - HashSet applicableNetworks = new HashSet(); + HashSet applicableNetworks = new HashSet<>(); Mockito.doReturn(networkVoListMock).when(networkModel).listNetworksForAccount(Mockito.anyLong(), Mockito.anyLong(), Mockito.any()); @@ -2239,30 +2230,30 @@ public void selectApplicableNetworkToCreateVmTestVirtualNetworkHasOneNetworkCall @Test public void addDefaultSecurityGroupToSecurityGroupIdListTestDefaultGroupIsNullCallsCreateSecurityGroup() { String expected = ""; - LinkedList securityGroupIdList = Mockito.spy(new LinkedList()); + LinkedList securityGroupIdList = Mockito.spy(new LinkedList<>()); Mockito.doReturn(null).when(securityGroupManagerMock).getDefaultSecurityGroup(Mockito.anyLong()); Mockito.doReturn(securityGroupVoMock).when(securityGroupManagerMock).createSecurityGroup(SecurityGroupManager.DEFAULT_GROUP_NAME, - SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, 1l, 1l, expected); + SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, 1L, 1L, expected); - Mockito.doReturn(1l).when(accountMock).getDomainId(); - Mockito.doReturn(1l).when(accountMock).getId(); + Mockito.doReturn(1L).when(accountMock).getDomainId(); + Mockito.doReturn(1L).when(accountMock).getId(); Mockito.doReturn(expected).when(accountMock).getAccountName(); - Mockito.doReturn(1l).when(securityGroupVoMock).getId(); + Mockito.doReturn(1L).when(securityGroupVoMock).getId(); userVmManagerImpl.addDefaultSecurityGroupToSecurityGroupIdList(accountMock, securityGroupIdList); - Mockito.verify(securityGroupManagerMock).createSecurityGroup(SecurityGroupManager.DEFAULT_GROUP_NAME, SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, 1l, 1l, expected); - Mockito.verify(securityGroupIdList).add(1l); + Mockito.verify(securityGroupManagerMock).createSecurityGroup(SecurityGroupManager.DEFAULT_GROUP_NAME, SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, 1L, 1L, expected); + Mockito.verify(securityGroupIdList).add(1L); } @Test public void addDefaultSecurityGroupToSecurityGroupIdListTestDefaultGroupIsPresentDoesNotCallAddIdToSecurityGroupIdList() { - LinkedList securityGroupIdList = Mockito.spy(new LinkedList()); + LinkedList securityGroupIdList = Mockito.spy(new LinkedList<>()); - securityGroupIdList.addFirst(1l); + securityGroupIdList.addFirst(1L); Mockito.doReturn(securityGroupVoMock).when(securityGroupManagerMock).getDefaultSecurityGroup(Mockito.anyLong()); - Mockito.doReturn(1l).when(securityGroupVoMock).getId(); + Mockito.doReturn(1L).when(securityGroupVoMock).getId(); userVmManagerImpl.addDefaultSecurityGroupToSecurityGroupIdList(accountMock, securityGroupIdList); @@ -2271,24 +2262,24 @@ public void addDefaultSecurityGroupToSecurityGroupIdListTestDefaultGroupIsPresen @Test public void addDefaultSecurityGroupToSecurityGroupIdListTestDefaultGroupIsNotPresentCallsAddIdToSecurityGroupIdList() { - LinkedList securityGroupIdList = Mockito.spy(new LinkedList()); + LinkedList securityGroupIdList = Mockito.spy(new LinkedList<>()); Mockito.doReturn(securityGroupVoMock).when(securityGroupManagerMock).getDefaultSecurityGroup(Mockito.anyLong()); - Mockito.doReturn(1l).when(securityGroupVoMock).getId(); + Mockito.doReturn(1L).when(securityGroupVoMock).getId(); userVmManagerImpl.addDefaultSecurityGroupToSecurityGroupIdList(accountMock, securityGroupIdList); - Mockito.verify(securityGroupIdList).add(1l); + Mockito.verify(securityGroupIdList).add(1L); } @Test public void keepOldSharedNetworkForVmTestNetworkIdListIsNotNullOrEmptyDoesNotCallFindDefaultNicForVm() { - LinkedList networkIdList = new LinkedList(); - HashSet applicableNetworks = new HashSet(); - HashMap requestedIPv4ForNics = new HashMap(); - HashMap requestedIPv6ForNics = new HashMap(); + LinkedList networkIdList = new LinkedList<>(); + HashSet applicableNetworks = new HashSet<>(); + HashMap requestedIPv4ForNics = new HashMap<>(); + HashMap requestedIPv6ForNics = new HashMap<>(); - networkIdList.add(1l); + networkIdList.add(1L); userVmManagerImpl.keepOldSharedNetworkForVm(userVmVoMock, accountMock, networkIdList, applicableNetworks, requestedIPv4ForNics, requestedIPv6ForNics); @@ -2297,9 +2288,9 @@ public void keepOldSharedNetworkForVmTestNetworkIdListIsNotNullOrEmptyDoesNotCal @Test public void keepOldSharedNetworkForVmTestNetworkIdListIsNullCallsFindDefaultNicForVm() { - HashSet applicableNetworks = new HashSet(); - HashMap requestedIPv4ForNics = new HashMap(); - HashMap requestedIPv6ForNics = new HashMap(); + HashSet applicableNetworks = new HashSet<>(); + HashMap requestedIPv4ForNics = new HashMap<>(); + HashMap requestedIPv6ForNics = new HashMap<>(); userVmManagerImpl.keepOldSharedNetworkForVm(userVmVoMock, accountMock, null, applicableNetworks, requestedIPv4ForNics, requestedIPv6ForNics); @@ -2308,10 +2299,10 @@ public void keepOldSharedNetworkForVmTestNetworkIdListIsNullCallsFindDefaultNicF @Test public void keepOldSharedNetworkForVmTestNetworkIdListIsEmptyCallsFindDefaultNicForVm() { - LinkedList networkIdList = new LinkedList(); - HashSet applicableNetworks = new HashSet(); - HashMap requestedIPv4ForNics = new HashMap(); - HashMap requestedIPv6ForNics = new HashMap(); + LinkedList networkIdList = new LinkedList<>(); + HashSet applicableNetworks = new HashSet<>(); + HashMap requestedIPv4ForNics = new HashMap<>(); + HashMap requestedIPv6ForNics = new HashMap<>(); userVmManagerImpl.keepOldSharedNetworkForVm(userVmVoMock, accountMock, networkIdList, applicableNetworks, requestedIPv4ForNics, requestedIPv6ForNics); @@ -2320,9 +2311,9 @@ public void keepOldSharedNetworkForVmTestNetworkIdListIsEmptyCallsFindDefaultNic @Test public void keepOldSharedNetworkForVmTestDefaultNicOldIsNullDoesNotCallNetworkDaoFindById() { - HashSet applicableNetworks = new HashSet(); - HashMap requestedIPv4ForNics = new HashMap(); - HashMap requestedIPv6ForNics = new HashMap(); + HashSet applicableNetworks = new HashSet<>(); + HashMap requestedIPv4ForNics = new HashMap<>(); + HashMap requestedIPv6ForNics = new HashMap<>(); Mockito.doReturn(null).when(nicDao).findDefaultNicForVM(Mockito.anyLong()); @@ -2333,9 +2324,9 @@ public void keepOldSharedNetworkForVmTestDefaultNicOldIsNullDoesNotCallNetworkDa @Test public void keepOldSharedNetworkForVmTestDefaultNicOldIsNotNullCallsNetworkDaoFindById() { - HashSet applicableNetworks = new HashSet(); - HashMap requestedIPv4ForNics = new HashMap(); - HashMap requestedIPv6ForNics = new HashMap(); + HashSet applicableNetworks = new HashSet<>(); + HashMap requestedIPv4ForNics = new HashMap<>(); + HashMap requestedIPv6ForNics = new HashMap<>(); Mockito.doReturn(new NicVO()).when(nicDao).findDefaultNicForVM(Mockito.anyLong()); @@ -2346,9 +2337,9 @@ public void keepOldSharedNetworkForVmTestDefaultNicOldIsNotNullCallsNetworkDaoFi @Test public void keepOldSharedNetworkForVmTestAccountCanNotUseNetworkDoesNotAddNetworkToApplicableNetworks() { - HashSet applicableNetworks = Mockito.spy(new HashSet()); - HashMap requestedIPv4ForNics = new HashMap(); - HashMap requestedIPv6ForNics = new HashMap(); + HashSet applicableNetworks = Mockito.spy(new HashSet<>()); + HashMap requestedIPv4ForNics = new HashMap<>(); + HashMap requestedIPv6ForNics = new HashMap<>(); Mockito.doReturn(new NicVO()).when(nicDao).findDefaultNicForVM(Mockito.anyLong()); Mockito.doReturn(networkMock).when(_networkDao).findById(Mockito.anyLong()); @@ -2361,9 +2352,9 @@ public void keepOldSharedNetworkForVmTestAccountCanNotUseNetworkDoesNotAddNetwor @Test public void keepOldSharedNetworkForVmTestAccountCanUseNetworkAddsNetworkToApplicableNetworks() { - HashSet applicableNetworks = Mockito.spy(new HashSet()); - HashMap requestedIPv4ForNics = new HashMap(); - HashMap requestedIPv6ForNics = new HashMap(); + HashSet applicableNetworks = Mockito.spy(new HashSet<>()); + HashMap requestedIPv4ForNics = new HashMap<>(); + HashMap requestedIPv6ForNics = new HashMap<>(); Mockito.doReturn(new NicVO()).when(nicDao).findDefaultNicForVM(Mockito.anyLong()); Mockito.doReturn(networkMock).when(_networkDao).findById(Mockito.anyLong()); @@ -2376,9 +2367,9 @@ public void keepOldSharedNetworkForVmTestAccountCanUseNetworkAddsNetworkToApplic @Test public void addAdditionalNetworksToVmTestNetworkIdListIsNullDoesNotCallCheckNetworkPermissions() { - HashSet applicableNetworks = Mockito.spy(new HashSet()); - HashMap requestedIPv4ForNics = new HashMap(); - HashMap requestedIPv6ForNics = new HashMap(); + HashSet applicableNetworks = Mockito.spy(new HashSet<>()); + HashMap requestedIPv4ForNics = new HashMap<>(); + HashMap requestedIPv6ForNics = new HashMap<>(); userVmManagerImpl.addAdditionalNetworksToVm(userVmVoMock, accountMock, null, applicableNetworks, requestedIPv4ForNics, requestedIPv6ForNics); @@ -2387,10 +2378,10 @@ public void addAdditionalNetworksToVmTestNetworkIdListIsNullDoesNotCallCheckNetw @Test public void addAdditionalNetworksToVmTestNetworkIdListIsEmptyDoesNotCallCheckNetworkPermissions() { - LinkedList networkIdList = new LinkedList(); - HashSet applicableNetworks = Mockito.spy(new HashSet()); - HashMap requestedIPv4ForNics = new HashMap(); - HashMap requestedIPv6ForNics = new HashMap(); + LinkedList networkIdList = new LinkedList<>(); + HashSet applicableNetworks = Mockito.spy(new HashSet<>()); + HashMap requestedIPv4ForNics = new HashMap<>(); + HashMap requestedIPv6ForNics = new HashMap<>(); userVmManagerImpl.addAdditionalNetworksToVm(userVmVoMock, accountMock, networkIdList, applicableNetworks, requestedIPv4ForNics, requestedIPv6ForNics); @@ -2400,12 +2391,12 @@ public void addAdditionalNetworksToVmTestNetworkIdListIsEmptyDoesNotCallCheckNet @Test public void addAdditionalNetworksToVmTestNetworkIsNullThrowsInvalidParameterValueException() { String expectedMessage = "Unable to find specified Network ID."; - LinkedList networkIdList = new LinkedList(); - HashSet applicableNetworks = Mockito.spy(new HashSet()); - HashMap requestedIPv4ForNics = new HashMap(); - HashMap requestedIPv6ForNics = new HashMap(); + LinkedList networkIdList = new LinkedList<>(); + HashSet applicableNetworks = Mockito.spy(new HashSet<>()); + HashMap requestedIPv4ForNics = new HashMap<>(); + HashMap requestedIPv6ForNics = new HashMap<>(); - networkIdList.add(1l); + networkIdList.add(1L); InvalidParameterValueException assertThrows = Assert.assertThrows(expectedInvalidParameterValueException, () -> { userVmManagerImpl.addAdditionalNetworksToVm(userVmVoMock, accountMock, networkIdList, applicableNetworks, requestedIPv4ForNics, requestedIPv6ForNics); @@ -2417,12 +2408,12 @@ public void addAdditionalNetworksToVmTestNetworkIsNullThrowsInvalidParameterValu @Test public void addAdditionalNetworksToVmTestNetworkOfferingIsSystemOnlyThrowsInvalidParameterValueException() { String expectedMessage = String.format("Specified network [%s] is system only and cannot be used for VM deployment.", networkMock); - LinkedList networkIdList = new LinkedList(); - HashSet applicableNetworks = Mockito.spy(new HashSet()); - HashMap requestedIPv4ForNics = new HashMap(); - HashMap requestedIPv6ForNics = new HashMap(); + LinkedList networkIdList = new LinkedList<>(); + HashSet applicableNetworks = Mockito.spy(new HashSet<>()); + HashMap requestedIPv4ForNics = new HashMap<>(); + HashMap requestedIPv6ForNics = new HashMap<>(); - networkIdList.add(1l); + networkIdList.add(1L); Mockito.doReturn(networkMock).when(_networkDao).findById(Mockito.anyLong()); Mockito.doReturn(networkOfferingVoMock).when(entityManager).findById(Mockito.any(), Mockito.anyLong()); @@ -2437,12 +2428,12 @@ public void addAdditionalNetworksToVmTestNetworkOfferingIsSystemOnlyThrowsInvali @Test public void addAdditionalNetworksToVmTestNetworkIsNotSharedGuestTypeDoesNotCallNicDaoFindByNtwkIdAndInstanceId() { - LinkedList networkIdList = new LinkedList(); - HashSet applicableNetworks = Mockito.spy(new HashSet()); - HashMap requestedIPv4ForNics = new HashMap(); - HashMap requestedIPv6ForNics = new HashMap(); + LinkedList networkIdList = new LinkedList<>(); + HashSet applicableNetworks = Mockito.spy(new HashSet<>()); + HashMap requestedIPv4ForNics = new HashMap<>(); + HashMap requestedIPv6ForNics = new HashMap<>(); - networkIdList.add(1l); + networkIdList.add(1L); Mockito.doReturn(networkMock).when(_networkDao).findById(Mockito.anyLong()); Mockito.doReturn(networkOfferingVoMock).when(entityManager).findById(Mockito.any(), Mockito.anyLong()); @@ -2456,12 +2447,12 @@ public void addAdditionalNetworksToVmTestNetworkIsNotSharedGuestTypeDoesNotCallN @Test public void addAdditionalNetworksToVmTestNetworkIsNotDomainAclTypeDoesNotCallNicDaoFindByNtwkIdAndInstanceId() { - LinkedList networkIdList = new LinkedList(); - HashSet applicableNetworks = Mockito.spy(new HashSet()); - HashMap requestedIPv4ForNics = new HashMap(); - HashMap requestedIPv6ForNics = new HashMap(); + LinkedList networkIdList = new LinkedList<>(); + HashSet applicableNetworks = Mockito.spy(new HashSet<>()); + HashMap requestedIPv4ForNics = new HashMap<>(); + HashMap requestedIPv6ForNics = new HashMap<>(); - networkIdList.add(1l); + networkIdList.add(1L); Mockito.doReturn(networkMock).when(_networkDao).findById(Mockito.anyLong()); Mockito.doReturn(networkOfferingVoMock).when(entityManager).findById(Mockito.any(), Mockito.anyLong()); @@ -2476,12 +2467,12 @@ public void addAdditionalNetworksToVmTestNetworkIsNotDomainAclTypeDoesNotCallNic @Test public void addAdditionalNetworksToVmTestOldNicIsNullDoesNotPutIpv4InRequestIpv4ForNics() { - LinkedList networkIdList = new LinkedList(); - HashSet applicableNetworks = Mockito.spy(new HashSet()); - HashMap requestedIPv4ForNics = Mockito.spy(new HashMap()); - HashMap requestedIPv6ForNics = new HashMap(); + LinkedList networkIdList = new LinkedList<>(); + HashSet applicableNetworks = Mockito.spy(new HashSet<>()); + HashMap requestedIPv4ForNics = Mockito.spy(new HashMap<>()); + HashMap requestedIPv6ForNics = new HashMap<>(); - networkIdList.add(1l); + networkIdList.add(1L); Mockito.doReturn(networkMock).when(_networkDao).findById(Mockito.anyLong()); Mockito.doReturn(networkOfferingVoMock).when(entityManager).findById(Mockito.any(), Mockito.anyLong()); @@ -2498,12 +2489,12 @@ public void addAdditionalNetworksToVmTestOldNicIsNullDoesNotPutIpv4InRequestIpv4 @Test public void addAdditionalNetworksToVmTestOldNicIsNotNullPutsIpv4InRequestIpv4ForNics() { - LinkedList networkIdList = new LinkedList(); - HashSet applicableNetworks = Mockito.spy(new HashSet()); - HashMap requestedIPv4ForNics = Mockito.spy(new HashMap()); - HashMap requestedIPv6ForNics = new HashMap(); + LinkedList networkIdList = new LinkedList<>(); + HashSet applicableNetworks = Mockito.spy(new HashSet<>()); + HashMap requestedIPv4ForNics = Mockito.spy(new HashMap<>()); + HashMap requestedIPv6ForNics = new HashMap<>(); - networkIdList.add(1l); + networkIdList.add(1L); Mockito.doReturn(networkMock).when(_networkDao).findById(Mockito.anyLong()); Mockito.doReturn(networkOfferingVoMock).when(entityManager).findById(Mockito.any(), Mockito.anyLong()); @@ -2522,7 +2513,7 @@ public void addAdditionalNetworksToVmTestOldNicIsNotNullPutsIpv4InRequestIpv4For public void createApplicableNetworkToCreateVmTestPhysicalNetworkIsNullThrowsInvalidParameterValueException() { Mockito.doReturn(networkOfferingVoMock).when(userVmManagerImpl).getOfferingWithRequiredAvailabilityForNetworkCreation(); - String expectedMessage = String.format("Unable to find physical network with ID [%s] and tag [%s].", 0l, null); + String expectedMessage = String.format("Unable to find physical network with ID [%s] and tag [%s].", 0L, null); InvalidParameterValueException assertThrows = Assert.assertThrows(expectedInvalidParameterValueException, () -> { userVmManagerImpl.createApplicableNetworkToCreateVm(accountMock, _dcMock); }); @@ -2562,7 +2553,7 @@ public void createApplicableNetworkToCreateVmTestFirstNetworkOfferingIsNotPersis Mockito.any(), Mockito.any(), Mockito.anyBoolean(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); Mockito.doReturn(networkOfferingVoMock).when(userVmManagerImpl).getOfferingWithRequiredAvailabilityForNetworkCreation(); - Mockito.doReturn(1l).when(networkMock).getId(); + Mockito.doReturn(1L).when(networkMock).getId(); Mockito.doReturn(networkMock).when(_networkDao).findById(Mockito.anyLong()); userVmManagerImpl.createApplicableNetworkToCreateVm(accountMock, _dcMock); @@ -2638,7 +2629,7 @@ public void implementNetworkTestImplementedNetworkIsNullReturnCurrentNewNetwork( try (MockedStatic ignored = mockStatic(CallContext.class)) { Mockito.when(CallContext.current()).thenReturn(callContextMock); - Mockito.doReturn(1l).when(callContextMock).getCallingUserId(); + Mockito.doReturn(1L).when(callContextMock).getCallingUserId(); Mockito.doReturn(callerUser).when(userDao).findById(Mockito.anyLong()); Mockito.doReturn(null).when(_networkMgr).implementNetwork(Mockito.anyLong(), Mockito.any(), Mockito.any()); @@ -2657,7 +2648,7 @@ public void implementNetworkTestImplementedNetworkFirstIsNullReturnCurrentNewNet try (MockedStatic ignored = mockStatic(CallContext.class)) { Mockito.when(CallContext.current()).thenReturn(callContextMock); - Mockito.doReturn(1l).when(callContextMock).getCallingUserId(); + Mockito.doReturn(1L).when(callContextMock).getCallingUserId(); Pair implementedNetwork = Mockito.mock(Pair.class); @@ -2679,7 +2670,7 @@ public void implementNetworkTestImplementedNetworkSecondIsNullReturnCurrentNewNe try (MockedStatic ignored = mockStatic(CallContext.class)) { Mockito.when(CallContext.current()).thenReturn(callContextMock); - Mockito.doReturn(1l).when(callContextMock).getCallingUserId(); + Mockito.doReturn(1L).when(callContextMock).getCallingUserId(); Pair implementedNetwork = Mockito.mock(Pair.class); @@ -2702,7 +2693,7 @@ public void implementNetworkTestImplementedNetworkSecondIsNotNullReturnImplement try (MockedStatic ignored = mockStatic(CallContext.class)) { Mockito.when(CallContext.current()).thenReturn(callContextMock); - Mockito.doReturn(1l).when(callContextMock).getCallingUserId(); + Mockito.doReturn(1L).when(callContextMock).getCallingUserId(); Pair implementedNetwork = Mockito.mock(Pair.class); @@ -2726,7 +2717,7 @@ public void implementNetworkTestImplementedNetworkCatchException() throws Resour try (MockedStatic ignored = mockStatic(CallContext.class)) { Mockito.when(CallContext.current()).thenReturn(callContextMock); - Mockito.doReturn(1l).when(callContextMock).getCallingUserId(); + Mockito.doReturn(1L).when(callContextMock).getCallingUserId(); Pair implementedNetwork = Mockito.mock(Pair.class); @@ -2744,10 +2735,10 @@ public void implementNetworkTestImplementedNetworkCatchException() throws Resour @Test public void updateBasicTypeNetworkForVmTestNetworkIdListIsNotEmptyThrowsInvalidParameterValueException() { String expectedMessage = "Cannot move VM with Network IDs; this is a basic zone VM."; - LinkedList networkIdList = new LinkedList(); - LinkedList securityGroupIdList = new LinkedList(); + LinkedList networkIdList = new LinkedList<>(); + LinkedList securityGroupIdList = new LinkedList<>(); - networkIdList.add(1l); + networkIdList.add(1L); InvalidParameterValueException assertThrows = Assert.assertThrows(expectedInvalidParameterValueException, () -> { userVmManagerImpl.updateBasicTypeNetworkForVm(userVmVoMock, accountMock, virtualMachineTemplateMock, virtualMachineProfileMock, _dcMock, networkIdList, @@ -2779,7 +2770,7 @@ public void updateBasicTypeNetworkForVmTestNetworkIdListIsEmptyCallsCleanupOfOld throws InsufficientCapacityException { LinkedList securityGroupIdList = Mockito.mock(LinkedList.class); - LinkedList networkIdList = new LinkedList(); + LinkedList networkIdList = new LinkedList<>(); Mockito.doReturn(networkMock).when(networkModel).getExclusiveGuestNetwork(Mockito.anyLong()); @@ -2796,7 +2787,7 @@ public void updateBasicTypeNetworkForVmTestNetworkIdListIsEmptyCallsCleanupOfOld public void updateAdvancedTypeNetworkForVmTestSecurityGroupIsEnabledApplicableNetworksIsEmptyThrowsInvalidParameterValueException() { String expectedMessage = "No network is specified, please specify one when you move the VM. For now, please add a network to VM on NICs tab."; LinkedList securityGroupIdList = Mockito.mock(LinkedList.class); - LinkedList networkIdList = new LinkedList(); + LinkedList networkIdList = new LinkedList<>(); Mockito.doReturn(true).when(networkModel).checkSecurityGroupSupportForNetwork(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); @@ -2814,7 +2805,7 @@ public void updateAdvancedTypeNetworkForVmTestSecurityGroupIsEnabledApplicableNe ResourceAllocationException { LinkedList securityGroupIdList = Mockito.mock(LinkedList.class); - LinkedList networkIdList = new LinkedList(); + LinkedList networkIdList = new LinkedList<>(); Mockito.doReturn(new NicVO()).when(nicDao).findDefaultNicForVM(Mockito.anyLong()); Mockito.doReturn(networkMock).when(_networkDao).findById(Mockito.anyLong()); @@ -2834,9 +2825,9 @@ public void updateAdvancedTypeNetworkForVmTestSecurityGroupIsEnabledApplicableNe public void updateAdvancedTypeNetworkForVmTestSecurityGroupIsNotEnabledSecurityGroupIdListIsNotEmptyThrowsInvalidParameterValueException() { String expectedMessage = "Cannot move VM with security groups; security group feature is not enabled in this zone."; LinkedList securityGroupIdList = Mockito.mock(LinkedList.class); - LinkedList networkIdList = new LinkedList(); + LinkedList networkIdList = new LinkedList<>(); - securityGroupIdList.add(1l); + securityGroupIdList.add(1L); Mockito.doReturn(false).when(networkModel).checkSecurityGroupSupportForNetwork(accountMock, _dcMock, networkIdList, securityGroupIdList); @@ -2853,7 +2844,7 @@ public void updateAdvancedTypeNetworkForVmTestSecurityGroupIsNotEnabledApplicabl ResourceAllocationException { LinkedList securityGroupIdList = Mockito.mock(LinkedList.class); - LinkedList networkIdList = new LinkedList(); + LinkedList networkIdList = new LinkedList<>(); Mockito.doReturn(networkMock).when(userVmManagerImpl).addNicsToApplicableNetworksAndReturnDefaultNetwork(Mockito.any(), Mockito.anyMap(), Mockito.anyMap(), Mockito.any()); Mockito.doNothing().when(userVmManagerImpl).selectApplicableNetworkToCreateVm(Mockito.any(), Mockito.any(), Mockito.any()); @@ -2876,7 +2867,7 @@ public void updateAdvancedTypeNetworkForVmTestSecurityGroupIsNotEnabledApplicabl throws InsufficientCapacityException, ResourceAllocationException { LinkedList securityGroupIdList = Mockito.mock(LinkedList.class); - LinkedList networkIdList = new LinkedList(); + LinkedList networkIdList = new LinkedList<>(); Mockito.doReturn(false).when(networkModel).checkSecurityGroupSupportForNetwork(accountMock, _dcMock, networkIdList, securityGroupIdList); Mockito.doReturn(true).when(securityGroupIdList).isEmpty(); @@ -2897,10 +2888,10 @@ public void updateAdvancedTypeNetworkForVmTestSecurityGroupIsNotEnabledApplicabl @Test public void addNicsToApplicableNetworksAndReturnDefaultNetworkTestApplicableNetworkIsEmptyReturnNull() { - HashMap requestedIPv4ForNics = new HashMap(); - HashMap requestedIPv6ForNics = new HashMap(); - LinkedHashSet applicableNetworks = new LinkedHashSet(); - LinkedHashMap> networks = new LinkedHashMap>(); + HashMap requestedIPv4ForNics = new HashMap<>(); + HashMap requestedIPv6ForNics = new HashMap<>(); + LinkedHashSet applicableNetworks = new LinkedHashSet<>(); + LinkedHashMap> networks = new LinkedHashMap<>(); NetworkVO defaultNetwork = userVmManagerImpl.addNicsToApplicableNetworksAndReturnDefaultNetwork(applicableNetworks, requestedIPv4ForNics, requestedIPv6ForNics, networks); @@ -2909,9 +2900,9 @@ public void addNicsToApplicableNetworksAndReturnDefaultNetworkTestApplicableNetw @Test public void addNicsToApplicableNetworksAndReturnDefaultNetworkTestApplicableNetworkIsNotEmptyReturnFirstElement() { - HashMap requestedIPv4ForNics = new HashMap(); - HashMap requestedIPv6ForNics = new HashMap(); - LinkedHashSet applicableNetworks = new LinkedHashSet(); + HashMap requestedIPv4ForNics = new HashMap<>(); + HashMap requestedIPv6ForNics = new HashMap<>(); + LinkedHashSet applicableNetworks = new LinkedHashSet<>(); LinkedHashMap> networks = Mockito.spy(LinkedHashMap.class); applicableNetworks.add(networkMock); @@ -2924,9 +2915,9 @@ public void addNicsToApplicableNetworksAndReturnDefaultNetworkTestApplicableNetw @Test public void addNicsToApplicableNetworksAndReturnDefaultNetworkTestApplicableNetworkIsNotEmptyPutTwoNetworksInNetworksMapAndReturnFirst() { - HashMap requestedIPv4ForNics = new HashMap(); - HashMap requestedIPv6ForNics = new HashMap(); - LinkedHashSet applicableNetworks = new LinkedHashSet(); + HashMap requestedIPv4ForNics = new HashMap<>(); + HashMap requestedIPv6ForNics = new HashMap<>(); + LinkedHashSet applicableNetworks = new LinkedHashSet<>(); LinkedHashMap> networks = Mockito.spy(LinkedHashMap.class); NetworkVO networkVoMock2 = Mockito.mock(NetworkVO.class); @@ -2944,9 +2935,9 @@ public void validateIfVolumesHaveNoSnapshotsTestVolumeHasSnapshotsThrowsInvalidP String expectedMessage = String.format("Snapshots exist for volume [%s]. Detach volume or remove snapshots for the volume before assigning VM to another user.", volumeVOMock.getName()); - LinkedList volumes = new LinkedList(); + LinkedList volumes = new LinkedList<>(); volumes.add(volumeVOMock); - LinkedList snapshots = new LinkedList(); + LinkedList snapshots = new LinkedList<>(); snapshots.add(snapshotVoMock); Mockito.doReturn(snapshots).when(snapshotDaoMock).listByStatusNotIn(Mockito.anyLong(), Mockito.any(), Mockito.any()); @@ -2960,9 +2951,9 @@ public void validateIfVolumesHaveNoSnapshotsTestVolumeHasSnapshotsThrowsInvalidP @Test public void validateIfVolumesHaveNoSnapshotsTestVolumeHasNoSnapshotsDoesNotThrowInvalidParameterException() { - LinkedList volumes = new LinkedList(); + LinkedList volumes = new LinkedList<>(); volumes.add(volumeVOMock); - LinkedList snapshots = new LinkedList(); + LinkedList snapshots = new LinkedList<>(); Mockito.doReturn(snapshots).when(snapshotDaoMock).listByStatusNotIn(Mockito.anyLong(), Mockito.any(), Mockito.any()); @@ -3008,7 +2999,7 @@ public void moveVmToUserTestProjectIdProvidedAndDomainIdIsNullThrowsInvalidParam Mockito.doReturn(true).when(accountManager).isRootAdmin(Mockito.anyLong()); Mockito.doReturn(userVmVoMock).when(userVmDao).findById(Mockito.anyLong()); - Mockito.doReturn(1l).when(assignVmCmdMock).getProjectId(); + Mockito.doReturn(1L).when(assignVmCmdMock).getProjectId(); Mockito.doReturn(null).when(assignVmCmdMock).getDomainId(); configureDoNothingForMethodsThatWeDoNotWantToTest(); @@ -3039,7 +3030,7 @@ public void moveVmToUserTestValidateIfVmHasNoRulesThrowsInvalidParameterValueExc public void moveVmToUserTestSnapshotsForVolumeExistThrowsInvalidParameterValueException() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { - LinkedList volumes = new LinkedList(); + LinkedList volumes = new LinkedList<>(); volumes.add(volumeVOMock); Mockito.doReturn(true).when(accountManager).isRootAdmin(Mockito.anyLong()); @@ -3058,7 +3049,7 @@ public void moveVmToUserTestSnapshotsForVolumeExistThrowsInvalidParameterValueEx public void moveVmToUserTestVerifyResourceLimitsForAccountAndStorageThrowsResourceAllocationException() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { - LinkedList volumes = new LinkedList(); + LinkedList volumes = new LinkedList<>(); Mockito.doReturn(true).when(accountManager).isRootAdmin(Mockito.anyLong()); Mockito.doReturn(userVmVoMock).when(userVmDao).findById(Mockito.anyLong()); @@ -3077,7 +3068,7 @@ public void moveVmToUserTestVerifyResourceLimitsForAccountAndStorageThrowsResour public void moveVmToUserTestVerifyValidateIfNewOwnerHasAccessToTemplateThrowsInvalidParameterValueException() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { - LinkedList volumes = new LinkedList(); + LinkedList volumes = new LinkedList<>(); Mockito.doReturn(true).when(accountManager).isRootAdmin(Mockito.anyLong()); Mockito.doReturn(userVmVoMock).when(userVmDao).findById(Mockito.anyLong()); @@ -3095,7 +3086,7 @@ public void moveVmToUserTestVerifyValidateIfNewOwnerHasAccessToTemplateThrowsInv public void moveVmToUserTestAccountManagerCheckAccessThrowsPermissionDeniedException() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { - LinkedList volumes = new LinkedList(); + LinkedList volumes = new LinkedList<>(); Mockito.doReturn(true).when(accountManager).isRootAdmin(Mockito.anyLong()); Mockito.doReturn(userVmVoMock).when(userVmDao).findById(Mockito.anyLong()); @@ -3115,7 +3106,7 @@ public void moveVmToUserTestAccountManagerCheckAccessThrowsPermissionDeniedExcep public void executeStepsToChangeOwnershipOfVmTestUpdateVmNetworkThrowsInsufficientCapacityException() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { - LinkedList volumes = new LinkedList(); + LinkedList volumes = new LinkedList<>(); try (MockedStatic ignored = mockStatic(UsageEventUtils.class)) { Mockito.doReturn(Hypervisor.HypervisorType.KVM).when(userVmVoMock).getHypervisorType(); @@ -3126,7 +3117,7 @@ public void executeStepsToChangeOwnershipOfVmTestUpdateVmNetworkThrowsInsufficie Mockito.any()); Assert.assertThrows(CloudRuntimeException.class, () -> userVmManagerImpl.executeStepsToChangeOwnershipOfVm(assignVmCmdMock, callerAccount, accountMock, accountMock, - userVmVoMock, serviceOfferingVoMock, volumes, virtualMachineTemplateMock, 1l)); + userVmVoMock, serviceOfferingVoMock, volumes, virtualMachineTemplateMock, 1L)); Mockito.verify(userVmManagerImpl).resourceCountDecrement(Mockito.anyLong(), Mockito.any(), Mockito.any(), Mockito.any()); Mockito.verify(userVmManagerImpl).updateVmOwner(Mockito.any(), Mockito.any(), Mockito.anyLong(), Mockito.anyLong()); @@ -3138,7 +3129,7 @@ public void executeStepsToChangeOwnershipOfVmTestUpdateVmNetworkThrowsInsufficie public void executeStepsToChangeOwnershipOfVmTestUpdateVmNetworkThrowsResourceAllocationException() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { - LinkedList volumes = new LinkedList(); + LinkedList volumes = new LinkedList<>(); try (MockedStatic ignored = mockStatic(UsageEventUtils.class)) { Mockito.doReturn(Hypervisor.HypervisorType.KVM).when(userVmVoMock).getHypervisorType(); @@ -3149,7 +3140,7 @@ public void executeStepsToChangeOwnershipOfVmTestUpdateVmNetworkThrowsResourceAl Mockito.any()); Assert.assertThrows(CloudRuntimeException.class, () -> userVmManagerImpl.executeStepsToChangeOwnershipOfVm(assignVmCmdMock, callerAccount, accountMock, accountMock, - userVmVoMock, serviceOfferingVoMock, volumes, virtualMachineTemplateMock, 1l)); + userVmVoMock, serviceOfferingVoMock, volumes, virtualMachineTemplateMock, 1L)); Mockito.verify(userVmManagerImpl).resourceCountDecrement(Mockito.anyLong(), Mockito.any(), Mockito.any(), Mockito.any()); Mockito.verify(userVmManagerImpl).updateVmOwner(Mockito.any(), Mockito.any(), Mockito.anyLong(), Mockito.anyLong()); @@ -3161,7 +3152,7 @@ public void executeStepsToChangeOwnershipOfVmTestUpdateVmNetworkThrowsResourceAl public void executeStepsToChangeOwnershipOfVmTestResourceCountRunningVmsOnlyEnabledIsFalseCallsResourceCountIncrement() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { - LinkedList volumes = new LinkedList(); + LinkedList volumes = new LinkedList<>(); try (MockedStatic ignored = mockStatic(UsageEventUtils.class)) { @@ -3185,7 +3176,7 @@ public void executeStepsToChangeOwnershipOfVmTestResourceCountRunningVmsOnlyEnab public void executeStepsToChangeOwnershipOfVmTestResourceCountRunningVmsOnlyEnabledIsTrueDoesNotCallResourceCountIncrement() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { - LinkedList volumes = new LinkedList(); + LinkedList volumes = new LinkedList<>(); try (MockedStatic ignored = mockStatic(UsageEventUtils.class)) { Mockito.doReturn(Hypervisor.HypervisorType.KVM).when(userVmVoMock).getHypervisorType(); @@ -3194,7 +3185,7 @@ public void executeStepsToChangeOwnershipOfVmTestResourceCountRunningVmsOnlyEnab configureDoNothingForMethodsThatWeDoNotWantToTest(); userVmManagerImpl.executeStepsToChangeOwnershipOfVm(assignVmCmdMock, callerAccount, accountMock, accountMock, userVmVoMock, serviceOfferingVoMock, volumes, - virtualMachineTemplateMock, 1l); + virtualMachineTemplateMock, 1L); Mockito.verify(userVmManagerImpl).resourceCountDecrement(Mockito.anyLong(), Mockito.any(), Mockito.any(), Mockito.any()); Mockito.verify(userVmManagerImpl).updateVmOwner(Mockito.any(), Mockito.any(), Mockito.anyLong(), Mockito.anyLong()); @@ -3458,9 +3449,9 @@ public void testResetVMSSHKey() throws ResourceUnavailableException, Insufficien assertNotNull(result); Map details = result.getDetails(); - Assert.assertEquals(details.get(VmDetailConstants.SSH_PUBLIC_KEY), "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAr...\n" + - "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAr..."); - Assert.assertEquals(details.get(VmDetailConstants.SSH_KEY_PAIR_NAMES), "keypair1,keypair2"); + Assert.assertEquals("ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAr...\n" + + "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAr...", details.get(VmDetailConstants.SSH_PUBLIC_KEY)); + Assert.assertEquals("keypair1,keypair2", details.get(VmDetailConstants.SSH_KEY_PAIR_NAMES)); } @Test @@ -3853,15 +3844,38 @@ Map getLeaseDetails(int leaseDuration, String leaseExecution) { return leaseDetails; } + private static DeployVMCmd buildDeployVMCmd(Long volumeId, Long snapshotId) { + DeployVMCmd deployVMCmd = mock(DeployVMCmd.class); + when(deployVMCmd.getEntityOwnerId()).thenReturn(accountId); + when(deployVMCmd.getZoneId()).thenReturn(zoneId); + when(deployVMCmd.getServiceOfferingId()).thenReturn(serviceOfferingId); + when(deployVMCmd.getVolumeId()).thenReturn(volumeId); + when(deployVMCmd.getSnapshotId()).thenReturn(snapshotId); + when(deployVMCmd.getTemplateId()).thenReturn(null); + when(deployVMCmd.isVolumeOrSnapshotProvided()).thenReturn(true); + when(deployVMCmd.getNetworkIds()).thenReturn(null); + when(deployVMCmd.getSecurityGroupNameList()).thenReturn(null); + // Long methods default to 0L in Mockito; null is required to match real DeployVMCmd field-unset behaviour + when(deployVMCmd.getDiskOfferingId()).thenReturn(null); + when(deployVMCmd.getUserdataId()).thenReturn(null); + when(deployVMCmd.getHostId()).thenReturn(null); + // boolean method defaults to false; real DeployVMCmd returns true when field is null + when(deployVMCmd.isDynamicScalingEnabled()).thenReturn(true); + return deployVMCmd; + } + + private static DeployVMCmd getDeployVMCmdFromSnapshot() { + return buildDeployVMCmd(null, snashotId); + } + + private static DeployVMCmd getDeployVMCmdFromVolume() { + return buildDeployVMCmd(volumeId, null); + } + @Test public void createVirtualMachineWithExistingVolume() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { - DeployVMCmd deployVMCmd = new DeployVMCmd(); - ReflectionTestUtils.setField(deployVMCmd, "zoneId", zoneId); - ReflectionTestUtils.setField(deployVMCmd, "serviceOfferingId", serviceOfferingId); - ReflectionTestUtils.setField(deployVMCmd, "volumeId", volumeId); - deployVMCmd._accountService = accountService; + DeployVMCmd deployVMCmd = getDeployVMCmdFromVolume(); - when(accountService.finalyzeAccountId(nullable(String.class), nullable(Long.class), nullable(Long.class), eq(true))).thenReturn(accountId); when(accountService.getActiveAccountById(accountId)).thenReturn(account); when(entityManager.findById(DataCenter.class, zoneId)).thenReturn(_dcMock); when(entityManager.findById(ServiceOffering.class, serviceOfferingId)).thenReturn(serviceOffering); @@ -3890,15 +3904,11 @@ public void createVirtualMachineWithExistingVolume() throws ResourceUnavailableE } @Test - public void createVirtualMachineWithExistingSnapshot() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { - DeployVMCmd deployVMCmd = new DeployVMCmd(); - ReflectionTestUtils.setField(deployVMCmd, "zoneId", zoneId); - ReflectionTestUtils.setField(deployVMCmd, "serviceOfferingId", serviceOfferingId); - ReflectionTestUtils.setField(deployVMCmd, "snapshotId", snashotId); - deployVMCmd._accountService = accountService; + public void createVirtualMachineWithExistingSnapshot() + throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { + DeployVMCmd deployVMCmd = getDeployVMCmdFromSnapshot(); // mock, no field hacks - when(accountService.finalyzeAccountId(nullable(String.class), nullable(Long.class), nullable(Long.class), eq(true))).thenReturn(accountId); - when(accountService.getActiveAccountById(accountId)).thenReturn(account); + when(accountService.getActiveAccountById(accountId)).thenReturn(account); // keep when(entityManager.findById(DataCenter.class, zoneId)).thenReturn(_dcMock); when(entityManager.findById(ServiceOffering.class, serviceOfferingId)).thenReturn(serviceOffering); when(entityManager.findById(DiskOffering.class, serviceOffering.getId())).thenReturn(smallerDisdkOffering); @@ -3920,25 +3930,14 @@ public void createVirtualMachineWithExistingSnapshot() throws ResourceUnavailabl any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), nullable(Boolean.class), any(), any(), any(), any(), any(), any(), any(), eq(true), any(), any(), any()); - userVmManagerImpl.createVirtualMachine(deployVMCmd); } - /** - * Bug fix: when deploying a VM from a snapshot whose source volume resided on - * local (HOST-scoped) storage, the zone-wide pool check must be skipped. - * The source volume's pool type is irrelevant – only the snapshot matters. - */ @Test public void createVirtualMachineWithSnapshotFromExpungedLocalStorageVolumeSucceeds() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { - DeployVMCmd deployVMCmd = new DeployVMCmd(); - ReflectionTestUtils.setField(deployVMCmd, "zoneId", zoneId); - ReflectionTestUtils.setField(deployVMCmd, "serviceOfferingId", serviceOfferingId); - ReflectionTestUtils.setField(deployVMCmd, "snapshotId", snashotId); - deployVMCmd._accountService = accountService; + DeployVMCmd deployVMCmd = getDeployVMCmdFromSnapshot(); // mock, no field hacks - when(accountService.finalyzeAccountId(nullable(String.class), nullable(Long.class), nullable(Long.class), eq(true))).thenReturn(accountId); when(accountService.getActiveAccountById(accountId)).thenReturn(account); when(entityManager.findById(DataCenter.class, zoneId)).thenReturn(_dcMock); when(entityManager.findById(ServiceOffering.class, serviceOfferingId)).thenReturn(serviceOffering); @@ -3964,20 +3963,11 @@ public void createVirtualMachineWithSnapshotFromExpungedLocalStorageVolumeSuccee userVmManagerImpl.createVirtualMachine(deployVMCmd); } - /** - * Bug fix: when deploying a VM from a snapshot whose source volume's storage pool - * was expunged (data store is null), the zone-wide pool check must be skipped. - */ @Test public void createVirtualMachineWithSnapshotFromVolumeWithNullDataStoreSucceeds() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { - DeployVMCmd deployVMCmd = new DeployVMCmd(); - ReflectionTestUtils.setField(deployVMCmd, "zoneId", zoneId); - ReflectionTestUtils.setField(deployVMCmd, "serviceOfferingId", serviceOfferingId); - ReflectionTestUtils.setField(deployVMCmd, "snapshotId", snashotId); - deployVMCmd._accountService = accountService; + DeployVMCmd deployVMCmd = getDeployVMCmdFromSnapshot(); // mock, no field hacks - when(accountService.finalyzeAccountId(nullable(String.class), nullable(Long.class), nullable(Long.class), eq(true))).thenReturn(accountId); when(accountService.getActiveAccountById(accountId)).thenReturn(account); when(entityManager.findById(DataCenter.class, zoneId)).thenReturn(_dcMock); when(entityManager.findById(ServiceOffering.class, serviceOfferingId)).thenReturn(serviceOffering); @@ -4003,19 +3993,10 @@ public void createVirtualMachineWithSnapshotFromVolumeWithNullDataStoreSucceeds( userVmManagerImpl.createVirtualMachine(deployVMCmd); } - /** - * Regression: deploying directly from a volume (not a snapshot) whose storage pool - * is HOST-scoped (local) must still be rejected with an appropriate error. - */ @Test public void createVirtualMachineWithVolumeFromNonZoneScopedStorageFails() { - DeployVMCmd deployVMCmd = new DeployVMCmd(); - ReflectionTestUtils.setField(deployVMCmd, "zoneId", zoneId); - ReflectionTestUtils.setField(deployVMCmd, "serviceOfferingId", serviceOfferingId); - ReflectionTestUtils.setField(deployVMCmd, "volumeId", volumeId); - deployVMCmd._accountService = accountService; + DeployVMCmd deployVMCmd = getDeployVMCmdFromVolume(); - when(accountService.finalyzeAccountId(nullable(String.class), nullable(Long.class), nullable(Long.class), eq(true))).thenReturn(accountId); when(accountService.getActiveAccountById(accountId)).thenReturn(account); when(entityManager.findById(DataCenter.class, zoneId)).thenReturn(_dcMock); when(entityManager.findById(ServiceOffering.class, serviceOfferingId)).thenReturn(serviceOffering); @@ -4030,19 +4011,10 @@ public void createVirtualMachineWithVolumeFromNonZoneScopedStorageFails() { assertEquals("Deployment of virtual machine is supported only for Zone-wide storage pools", ex.getMessage()); } - /** - * Regression: deploying directly from a volume (not a snapshot) whose storage pool - * has been expunged (null data store) must still be rejected with an appropriate error. - */ @Test public void createVirtualMachineWithVolumeWithNullDataStoreFails() { - DeployVMCmd deployVMCmd = new DeployVMCmd(); - ReflectionTestUtils.setField(deployVMCmd, "zoneId", zoneId); - ReflectionTestUtils.setField(deployVMCmd, "serviceOfferingId", serviceOfferingId); - ReflectionTestUtils.setField(deployVMCmd, "volumeId", volumeId); - deployVMCmd._accountService = accountService; + DeployVMCmd deployVMCmd = getDeployVMCmdFromVolume(); - when(accountService.finalyzeAccountId(nullable(String.class), nullable(Long.class), nullable(Long.class), eq(true))).thenReturn(accountId); when(accountService.getActiveAccountById(accountId)).thenReturn(account); when(entityManager.findById(DataCenter.class, zoneId)).thenReturn(_dcMock); when(entityManager.findById(ServiceOffering.class, serviceOfferingId)).thenReturn(serviceOffering);