text:
package org.apache.cloudstack.vm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.inject.Inject;

import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.ResponseGenerator;
import org.apache.cloudstack.api.ResponseObject;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.command.admin.vm.ImportUnmanagedInstanceCmd;
import org.apache.cloudstack.api.command.admin.vm.ListUnmanagedInstancesCmd;
import org.apache.cloudstack.api.response.ListResponse;
import org.apache.cloudstack.api.response.NicResponse;
import org.apache.cloudstack.api.response.UnmanagedInstanceDiskResponse;
import org.apache.cloudstack.api.response.UnmanagedInstanceResponse;
import org.apache.cloudstack.api.response.UserVmResponse;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
import org.apache.cloudstack.engine.orchestration.service.VolumeOrchestrationService;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
import org.apache.cloudstack.utils.volume.VirtualMachineDiskInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.log4j.Logger;

import com.cloud.agent.AgentManager;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.GetUnmanagedInstancesAnswer;
import com.cloud.agent.api.GetUnmanagedInstancesCommand;
import com.cloud.capacity.CapacityManager;
import com.cloud.configuration.Config;
import com.cloud.configuration.Resource;
import com.cloud.dc.DataCenter;
import com.cloud.dc.dao.ClusterDao;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.deploy.DataCenterDeployment;
import com.cloud.deploy.DeployDestination;
import com.cloud.deploy.DeploymentPlanner;
import com.cloud.deploy.DeploymentPlanningManager;
import com.cloud.event.EventTypes;
import com.cloud.event.UsageEventUtils;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InsufficientVirtualNetworkCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor;
import com.cloud.network.Network;
import com.cloud.network.NetworkModel;
import com.cloud.network.Networks;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.NetworkVO;
import com.cloud.offering.DiskOffering;
import com.cloud.offering.ServiceOffering;
import com.cloud.org.Cluster;
import com.cloud.resource.ResourceManager;
import com.cloud.serializer.GsonHelper;
import com.cloud.server.ManagementService;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.storage.GuestOS;
import com.cloud.storage.GuestOSHypervisor;
import com.cloud.storage.Storage;
import com.cloud.storage.StoragePool;
import com.cloud.storage.VMTemplateStoragePoolVO;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.Volume;
import com.cloud.storage.VolumeApiService;
import com.cloud.storage.VolumeVO;
import com.cloud.storage.dao.DiskOfferingDao;
import com.cloud.storage.dao.GuestOSDao;
import com.cloud.storage.dao.GuestOSHypervisorDao;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VMTemplatePoolDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.template.VirtualMachineTemplate;
import com.cloud.user.Account;
import com.cloud.user.AccountService;
import com.cloud.user.ResourceLimitService;
import com.cloud.user.UserVO;
import com.cloud.user.dao.UserDao;
import com.cloud.uservm.UserVm;
import com.cloud.utils.Pair;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
import com.cloud.vm.DiskProfile;
import com.cloud.vm.NicProfile;
import com.cloud.vm.UserVmManager;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineManager;
import com.cloud.vm.VirtualMachineProfile;
import com.cloud.vm.VirtualMachineProfileImpl;
import com.cloud.vm.VmDetailConstants;
import com.cloud.vm.dao.NicDao;
import com.cloud.vm.dao.VMInstanceDao;
import com.google.common.base.Strings;
import com.google.gson.Gson;

public class VmImportManagerImpl implements VmImportService {
    public static final String VM_IMPORT_DEFAULT_TEMPLATE_NAME = "system-default-vm-import-dummy-template.iso";
    private static final Logger LOGGER = Logger.getLogger(VmImportManagerImpl.class);

    @Inject
    private AgentManager agentManager;
    @Inject
    private DataCenterDao dataCenterDao;
    @Inject
    private ClusterDao clusterDao;
    @Inject
    private HostDao hostDao;
    @Inject
    private AccountService accountService;
    @Inject
    private UserDao userDao;
    @Inject
    private VMTemplateDao templateDao;
    @Inject
    private VMTemplatePoolDao templatePoolDao;
    @Inject
    private ServiceOfferingDao serviceOfferingDao;
    @Inject
    private DiskOfferingDao diskOfferingDao;
    @Inject
    private ResourceManager resourceManager;
    @Inject
    private ResourceLimitService resourceLimitService;
    @Inject
    private UserVmManager userVmManager;
    @Inject
    private ResponseGenerator responseGenerator;
    @Inject
    private VolumeOrchestrationService volumeManager;
    @Inject
    private VolumeDao volumeDao;
    @Inject
    private PrimaryDataStoreDao primaryDataStoreDao;
    @Inject
    private NetworkDao networkDao;
    @Inject
    private NetworkOrchestrationService networkOrchestrationService;
    @Inject
    private VMInstanceDao vmDao;
    @Inject
    private CapacityManager capacityManager;
    @Inject
    private VolumeApiService volumeApiService;
    @Inject
    private DeploymentPlanningManager deploymentPlanningManager;
    @Inject
    private VirtualMachineManager virtualMachineManager;
    @Inject
    private ManagementService managementService;
    @Inject
    private NicDao nicDao;
    @Inject
    private NetworkModel networkModel;
    @Inject
    private ConfigurationDao configurationDao;
    @Inject
    private GuestOSDao guestOSDao;
    @Inject
    private GuestOSHypervisorDao guestOSHypervisorDao;

    protected Gson gson;

    public VmImportManagerImpl() {
        gson = GsonHelper.getGsonLogger();
    }

    private VMTemplateVO createDefaultDummyVmImportTemplate() {
        VMTemplateVO template = null;
        try {
            template = VMTemplateVO.createSystemIso(templateDao.getNextInSequence(Long.class, "id"), VM_IMPORT_DEFAULT_TEMPLATE_NAME, VM_IMPORT_DEFAULT_TEMPLATE_NAME, true,
                    "", true, 64, Account.ACCOUNT_ID_SYSTEM, "",
                    "VM Import Default Template", false, 1);
            template.setState(VirtualMachineTemplate.State.Inactive);
            template = templateDao.persist(template);
            if (template == null) {
                return null;
            }
            templateDao.remove(template.getId());
            template = templateDao.findByName(VM_IMPORT_DEFAULT_TEMPLATE_NAME);
        } catch (Exception e) {
            LOGGER.error("Unable to create default dummy template for VM import", e);
        }
        return template;
    }

    private UnmanagedInstanceResponse createUnmanagedInstanceResponse(UnmanagedInstanceTO instance, Cluster cluster, Host host) {
        UnmanagedInstanceResponse response = new UnmanagedInstanceResponse();
        response.setName(instance.getName());
        if (cluster != null) {
            response.setClusterId(cluster.getUuid());
        }
        if (host != null) {
            response.setHostId(host.getUuid());
        }
        response.setPowerState(instance.getPowerState().toString());
        response.setCpuCores(instance.getCpuCores());
        response.setCpuSpeed(instance.getCpuSpeed());
        response.setCpuCoresPerSocket(instance.getCpuCoresPerSocket());
        response.setMemory(instance.getMemory());
        response.setOperatingSystemId(instance.getOperatingSystemId());
        response.setOperatingSystem(instance.getOperatingSystem());
        response.setObjectName("unmanagedinstance");

        if (instance.getDisks() != null) {
            for (UnmanagedInstanceTO.Disk disk : instance.getDisks()) {
                UnmanagedInstanceDiskResponse diskResponse = new UnmanagedInstanceDiskResponse();
                diskResponse.setDiskId(disk.getDiskId());
                if (!Strings.isNullOrEmpty(disk.getLabel())) {
                    diskResponse.setLabel(disk.getLabel());
                }
                diskResponse.setCapacity(disk.getCapacity());
                diskResponse.setController(disk.getController());
                diskResponse.setControllerUnit(disk.getControllerUnit());
                diskResponse.setPosition(disk.getPosition());
                diskResponse.setImagePath(disk.getImagePath());
                diskResponse.setDatastoreName(disk.getDatastoreName());
                diskResponse.setDatastoreHost(disk.getDatastoreHost());
                diskResponse.setDatastorePath(disk.getDatastorePath());
                diskResponse.setDatastoreType(disk.getDatastoreType());
                response.addDisk(diskResponse);
            }
        }

        if (instance.getNics() != null) {
            for (UnmanagedInstanceTO.Nic nic : instance.getNics()) {
                NicResponse nicResponse = new NicResponse();
                nicResponse.setId(nic.getNicId());
                nicResponse.setNetworkName(nic.getNetwork());
                nicResponse.setMacAddress(nic.getMacAddress());
                if (!Strings.isNullOrEmpty(nic.getAdapterType())) {
                    nicResponse.setAdapterType(nic.getAdapterType());
                }
                if (!CollectionUtils.isEmpty(nic.getIpAddress())) {
                    nicResponse.setIpAddresses(nic.getIpAddress());
                }
                nicResponse.setVlanId(nic.getVlan());
                nicResponse.setIsolatedPvlanId(nic.getPvlan());
                nicResponse.setIsolatedPvlanType(nic.getPvlanType());
                response.addNic(nicResponse);
            }
        }
        return response;
    }

    private List<String> getAdditionalNameFilters(Cluster cluster) {
        List<String> additionalNameFilter = new ArrayList<>();
        if (cluster == null) {
            return additionalNameFilter;
        }
        if (cluster.getHypervisorType() == Hypervisor.HypervisorType.VMware) {
            // VMWare considers some templates as VM and they are not filtered by VirtualMachineMO.isTemplate()
            List<VMTemplateStoragePoolVO> templates = templatePoolDao.listAll();
            for (VMTemplateStoragePoolVO template : templates) {
                additionalNameFilter.add(template.getInstallPath());
            }

            // VMWare considers some removed volumes as VM
            List<VolumeVO> volumes = volumeDao.findIncludingRemovedByZone(cluster.getDataCenterId());
            for (VolumeVO volumeVO : volumes) {
                if (volumeVO.getRemoved() == null) {
                    continue;
                }
                if (Strings.isNullOrEmpty(volumeVO.getChainInfo())) {
                    continue;
                }
                List<String> volumeFileNames = new ArrayList<>();
                try {
                    VirtualMachineDiskInfo diskInfo = gson.fromJson(volumeVO.getChainInfo(), VirtualMachineDiskInfo.class);
                    String[] files = diskInfo.getDiskChain();
                    if (files.length == 1) {
                        continue;
                    }
                    boolean firstFile = true;
                    for (final String file : files) {
                        if (firstFile) {
                            firstFile = false;
                            continue;
                        }
                        String path = file;
                        String[] split = path.split(" ");
                        path = split[split.length - 1];
                        split = path.split("/");
                        ;
                        path = split[split.length - 1];
                        split = path.split("\\.");
                        path = split[0];
                        if (!Strings.isNullOrEmpty(path)) {
                            if (!additionalNameFilter.contains(path)) {
                                volumeFileNames.add(path);
                            }
                            if (path.contains("-")) {
                                split = path.split("-");
                                path = split[0];
                                if (!Strings.isNullOrEmpty(path) && !path.equals("ROOT") && !additionalNameFilter.contains(path)) {
                                    volumeFileNames.add(path);
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    LOGGER.warn(String.format("Unable to find volume file name for volume ID: %s while adding filters unmanaged VMs", volumeVO.getUuid()), e);
                }
                if (!volumeFileNames.isEmpty()) {
                    additionalNameFilter.addAll(volumeFileNames);
                }
            }
        }
        return additionalNameFilter;
    }

    private List<String> getHostManagedVms(Host host) {
        List<String> managedVms = new ArrayList<>();
        List<VMInstanceVO> instances = vmDao.listByHostId(host.getId());
        for (VMInstanceVO instance : instances) {
            managedVms.add(instance.getInstanceName());
        }
        instances = vmDao.listByLastHostIdAndStates(host.getId(),
                VirtualMachine.State.Stopped, VirtualMachine.State.Destroyed,
                VirtualMachine.State.Expunging, VirtualMachine.State.Error,
                VirtualMachine.State.Unknown, VirtualMachine.State.Shutdown);
        for (VMInstanceVO instance : instances) {
            managedVms.add(instance.getInstanceName());
        }
        return managedVms;
    }

    private boolean hostSupportsServiceOffering(HostVO host, ServiceOffering serviceOffering) {
        if (host == null) {
            return false;
        }
        if (serviceOffering == null) {
            return false;
        }
        if (Strings.isNullOrEmpty(serviceOffering.getHostTag())) {
            return true;
        }
        hostDao.loadHostTags(host);
        return host.getHostTags() != null && host.getHostTags().contains(serviceOffering.getHostTag());
    }

    private boolean storagePoolSupportsDiskOffering(StoragePool pool, DiskOffering diskOffering) {
        if (pool == null) {
            return false;
        }
        if (diskOffering == null) {
            return false;
        }
        return volumeApiService.doesTargetStorageSupportDiskOffering(pool, diskOffering.getTags());
    }

    private boolean storagePoolSupportsServiceOffering(StoragePool pool, ServiceOffering serviceOffering) {
        if (pool == null) {
            return false;
        }
        if (serviceOffering == null) {
            return false;
        }
        return volumeApiService.doesTargetStorageSupportDiskOffering(pool, serviceOffering.getTags());
    }

    private ServiceOfferingVO getUnmanagedInstanceServiceOffering(final UnmanagedInstanceTO instance, ServiceOfferingVO serviceOffering, final Account owner, final DataCenter zone, final Map<String, String> details)
            throws ServerApiException, PermissionDeniedException, ResourceAllocationException {
        if (instance == null) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("VM is not valid"));
        }
        if (serviceOffering == null) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Service offering is not valid"));
        }
        accountService.checkAccess(owner, serviceOffering, zone);
        final Integer cpu = instance.getCpuCores();
        final Integer memory = instance.getMemory();
        Integer cpuSpeed = instance.getCpuSpeed() == null ? 0 : instance.getCpuSpeed();
        if (cpu == null || cpu == 0) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("CPU cores for VM not valid"));
        }
        if (memory == null || memory == 0) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Memory for VM not valid", instance.getName()));
        }
        if (serviceOffering.isDynamic()) {
            if (details.containsKey(VmDetailConstants.CPU_SPEED)) {
                try {
                    cpuSpeed = Integer.parseInt(details.get(VmDetailConstants.CPU_SPEED));
                } catch (Exception e) {
                }
            }
            Map<String, String> parameters = new HashMap<>();
            parameters.put(VmDetailConstants.CPU_NUMBER, String.valueOf(cpu));
            parameters.put(VmDetailConstants.MEMORY, String.valueOf(memory));
            if (serviceOffering.getSpeed() == null && cpuSpeed > 0) {
                parameters.put(VmDetailConstants.CPU_SPEED, String.valueOf(cpuSpeed));
            }
            serviceOffering.setDynamicFlag(true);
            userVmManager.validateCustomParameters(serviceOffering, parameters);
            serviceOffering = serviceOfferingDao.getComputeOffering(serviceOffering, parameters);
        } else {
            if (!cpu.equals(serviceOffering.getCpu()) && !instance.getPowerState().equals(UnmanagedInstanceTO.PowerState.PowerOff)) {
                throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Service offering (%s) %d CPU cores does not matches VM CPU cores %d  and VM is not in powered off state (Power state: %s)", serviceOffering.getUuid(), serviceOffering.getCpu(), cpu, instance.getPowerState()));
            }
            if (!memory.equals(serviceOffering.getRamSize()) && !instance.getPowerState().equals(UnmanagedInstanceTO.PowerState.PowerOff)) {
                throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Service offering (%s) %dMB memory does not matches VM memory %dMB and VM is not in powered off state (Power state: %s)", serviceOffering.getUuid(), serviceOffering.getRamSize(), memory, instance.getPowerState()));
            }
            if (cpuSpeed != null && cpuSpeed > 0 && !cpuSpeed.equals(serviceOffering.getSpeed()) && !instance.getPowerState().equals(UnmanagedInstanceTO.PowerState.PowerOff)) {
                throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Service offering (%s) %dMHz CPU speed does not matches VM CPU speed %dMHz and VM is not in powered off state (Power state: %s)", serviceOffering.getUuid(), serviceOffering.getSpeed(), cpuSpeed, instance.getPowerState()));
            }
        }
        resourceLimitService.checkResourceLimit(owner, Resource.ResourceType.cpu, new Long(serviceOffering.getCpu()));
        resourceLimitService.checkResourceLimit(owner, Resource.ResourceType.memory, new Long(serviceOffering.getRamSize()));
        return serviceOffering;
    }

    private Map<String, Network.IpAddresses> getNicIpAddresses(final List<UnmanagedInstanceTO.Nic> nics, final Map<String, Network.IpAddresses> callerNicIpAddressMap) {
        Map<String, Network.IpAddresses> nicIpAddresses = new HashMap<>();
        for (UnmanagedInstanceTO.Nic nic : nics) {
            Network.IpAddresses ipAddresses = null;
            if (MapUtils.isNotEmpty(callerNicIpAddressMap) && callerNicIpAddressMap.containsKey(nic.getNicId())) {
                ipAddresses = callerNicIpAddressMap.get(nic.getNicId());
            }
            // If IP is set to auto-assign, check NIC doesn't have more that one IP from SDK
            if (ipAddresses != null && ipAddresses.getIp4Address() != null && ipAddresses.getIp4Address().equals("auto") && !CollectionUtils.isEmpty(nic.getIpAddress())) {
                if (nic.getIpAddress().size() > 1) {
                    throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Multiple IP addresses (%s, %s) present for nic ID: %s. IP address cannot be assigned automatically, only single IP address auto-assigning supported", nic.getIpAddress().get(0), nic.getIpAddress().get(1), nic.getNicId()));
                }
                String address = nic.getIpAddress().get(0);
                if (NetUtils.isValidIp4(address)) {
                    ipAddresses.setIp4Address(address);
                }
            }
            if (ipAddresses != null) {
                nicIpAddresses.put(nic.getNicId(), ipAddresses);
            }
        }
        return nicIpAddresses;
    }

    private StoragePool getStoragePool(final UnmanagedInstanceTO.Disk disk, final DataCenter zone, final Cluster cluster) {
        StoragePool storagePool = null;
        final String dsHost = disk.getDatastoreHost();
        final String dsPath = disk.getDatastorePath();
        final String dsType = disk.getDatastoreType();
        final String dsName = disk.getDatastoreName();
        if (dsType.equals("VMFS")) {
            List<StoragePoolVO> pools = primaryDataStoreDao.listPoolsByCluster(cluster.getId());
            pools.addAll(primaryDataStoreDao.listByDataCenterId(zone.getId()));
            for (StoragePool pool : pools) {
                if (pool.getPoolType() != Storage.StoragePoolType.VMFS) {
                    continue;
                }
                if (pool.getPath().endsWith(dsName)) {
                    storagePool = pool;
                    break;
                }
            }
        } else {
            List<StoragePoolVO> pools = primaryDataStoreDao.listPoolByHostPath(dsHost, dsPath);
            for (StoragePool pool : pools) {
                if (pool.getDataCenterId() == zone.getId() &&
                        (pool.getClusterId() == null || pool.getClusterId().equals(cluster.getId()))) {
                    storagePool = pool;
                    break;
                }
            }
        }
        if (storagePool == null) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Storage pool for disk %s(%s) with datastore: %s not found in zone ID: %s", disk.getLabel(), disk.getDiskId(), disk.getDatastoreName(), zone.getUuid()));
        }
        return storagePool;
    }

    private void checkUnmanagedDiskAndOfferingForImport(UnmanagedInstanceTO.Disk disk, DiskOffering diskOffering, ServiceOffering serviceOffering, final Account owner, final DataCenter zone, final Cluster cluster, final boolean migrateAllowed)
            throws ServerApiException, PermissionDeniedException, ResourceAllocationException {
        if (serviceOffering == null && diskOffering == null) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Disk offering for disk ID: %s not found during VM import", disk.getDiskId()));
        }
        if (diskOffering != null) {
            accountService.checkAccess(owner, diskOffering, zone);
        }
        resourceLimitService.checkResourceLimit(owner, Resource.ResourceType.volume);
        if (disk.getCapacity() == null || disk.getCapacity() == 0) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Size of disk(ID: %s) is found invalid during VM import", disk.getDiskId()));
        }
        if (diskOffering != null && !diskOffering.isCustomized() && diskOffering.getDiskSize() == 0) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Size of fixed disk offering(ID: %s) is found invalid during VM import", diskOffering.getUuid()));
        }
        if (diskOffering != null && !diskOffering.isCustomized() && diskOffering.getDiskSize() < disk.getCapacity()) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Size of disk offering(ID: %s) %dGB is found less than the size of disk(ID: %s) %dGB during VM import", diskOffering.getUuid(), (diskOffering.getDiskSize() / Resource.ResourceType.bytesToGiB), disk.getDiskId(), (disk.getCapacity() / (Resource.ResourceType.bytesToGiB))));
        }
        StoragePool storagePool = getStoragePool(disk, zone, cluster);
        if (diskOffering != null && !migrateAllowed && !storagePoolSupportsDiskOffering(storagePool, diskOffering)) {
            throw new InvalidParameterValueException(String.format("Disk offering: %s is not compatible with storage pool: %s of unmanaged disk: %s", diskOffering.getUuid(), storagePool.getUuid(), disk.getDiskId()));
        }
        if (serviceOffering != null && !migrateAllowed && !storagePoolSupportsServiceOffering(storagePool, serviceOffering)) {
            throw new InvalidParameterValueException(String.format("Service offering: %s is not compatible with storage pool: %s of unmanaged disk: %s", serviceOffering.getUuid(), storagePool.getUuid(), disk.getDiskId()));
        }
    }

    private void checkUnmanagedDiskAndOfferingForImport(List<UnmanagedInstanceTO.Disk> disks, final Map<String, Long> diskOfferingMap, final Account owner, final DataCenter zone, final Cluster cluster, final boolean migrateAllowed)
            throws ServerApiException, PermissionDeniedException, ResourceAllocationException {
        String diskController = null;
        for (UnmanagedInstanceTO.Disk disk : disks) {
            if (disk == null) {
                throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Unable to retrieve disk details for VM"));
            }
            if (!diskOfferingMap.containsKey(disk.getDiskId())) {
                throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Disk offering for disk ID: %s not found during VM import", disk.getDiskId()));
            }
            if (Strings.isNullOrEmpty(diskController)) {
                diskController = disk.getController();
            } else {
                if (!diskController.equals(disk.getController())) {
                    throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Multiple data disk controllers of different type (%s, %s) are not supported for import. Please make sure that all data disk controllers are of the same type", diskController, disk.getController()));
                }
            }
            checkUnmanagedDiskAndOfferingForImport(disk, diskOfferingDao.findById(diskOfferingMap.get(disk.getDiskId())), null, owner, zone, cluster, migrateAllowed);
        }
    }

    private void checkUnmanagedNicAndNetworkForImport(UnmanagedInstanceTO.Nic nic, Network network, final DataCenter zone, final Account owner, final boolean autoAssign) throws ServerApiException {
        if (nic == null) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Unable to retrieve NIC details during VM import"));
        }
        if (network == null) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Network for nic ID: %s not found during VM import", nic.getNicId()));
        }
        if (network.getDataCenterId() != zone.getId()) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Network(ID: %s) for nic(ID: %s) belongs to a different zone than VM to be imported", network.getUuid(), nic.getNicId()));
        }
        networkModel.checkNetworkPermissions(owner, network);
        if (!autoAssign && network.getGuestType().equals(Network.GuestType.Isolated)) {
            return;
        }

        String networkBroadcastUri = network.getBroadcastUri() == null ? null : network.getBroadcastUri().toString();
        if (nic.getVlan() != null && nic.getVlan() != 0 && nic.getPvlan() == null &&
                (Strings.isNullOrEmpty(networkBroadcastUri) ||
                        !networkBroadcastUri.equals(String.format("vlan://%d", nic.getVlan())))) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("VLAN of network(ID: %s) %s is found different from the VLAN of nic(ID: %s) vlan://%d during VM import", network.getUuid(), networkBroadcastUri, nic.getNicId(), nic.getVlan()));
        }
        if (nic.getVlan() != null && nic.getVlan() != 0 && nic.getPvlan() != null && nic.getPvlan() != 0 &&
                (Strings.isNullOrEmpty(network.getBroadcastUri().toString()) ||
                        !networkBroadcastUri.equals(String.format("pvlan://%d-i%d", nic.getVlan(), nic.getPvlan())))) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("PVLAN of network(ID: %s) %s is found different from the VLAN of nic(ID: %s) pvlan://%d-i%d during VM import", network.getUuid(), networkBroadcastUri, nic.getNicId(), nic.getVlan(), nic.getPvlan()));
        }
    }

    private void checkUnmanagedNicAndNetworkHostnameForImport(UnmanagedInstanceTO.Nic nic, Network network, final String hostName) throws ServerApiException {
        if (nic == null) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Unable to retrieve NIC details during VM import"));
        }
        if (network == null) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Network for nic ID: %s not found during VM import", nic.getNicId()));
        }
        // Check for duplicate hostname in network, get all vms hostNames in the network
        List<String> hostNames = vmDao.listDistinctHostNames(network.getId());
        if (CollectionUtils.isNotEmpty(hostNames) && hostNames.contains(hostName)) {
            throw new InvalidParameterValueException("The vm with hostName " + hostName + " already exists in the network domain: " + network.getNetworkDomain() + "; network="
                    + network);
        }
    }

    private void checkUnmanagedNicIpAndNetworkForImport(UnmanagedInstanceTO.Nic nic, Network network, final Network.IpAddresses ipAddresses) throws ServerApiException {
        if (nic == null) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Unable to retrieve NIC details during VM import"));
        }
        if (network == null) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Network for nic ID: %s not found during VM import", nic.getNicId()));
        }
        // Check IP is assigned for non L2 networks
        if (!network.getGuestType().equals(Network.GuestType.L2) && (ipAddresses == null || Strings.isNullOrEmpty(ipAddresses.getIp4Address()))) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("NIC(ID: %s) needs a valid IP address for it to be associated with network(ID: %s). %s parameter of API can be used for this", nic.getNicId(), network.getUuid(), ApiConstants.NIC_IP_ADDRESS_LIST));
        }
        // If network is non L2, IP v4 is assigned and not set to auto-assign, check it is available for network
        if (!network.getGuestType().equals(Network.GuestType.L2) && ipAddresses != null && !Strings.isNullOrEmpty(ipAddresses.getIp4Address()) && !ipAddresses.getIp4Address().equals("auto")) {
            Set<Long> ips = networkModel.getAvailableIps(network, ipAddresses.getIp4Address());
            if (CollectionUtils.isEmpty(ips) || !ips.contains(NetUtils.ip2Long(ipAddresses.getIp4Address()))) {
                throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("IP address %s for NIC(ID: %s) is not available in network(ID: %s)", ipAddresses.getIp4Address(), nic.getNicId(), network.getUuid()));
            }
        }
    }

    private Map<String, Long> getUnmanagedNicNetworkMap(List<UnmanagedInstanceTO.Nic> nics, final Map<String, Long> callerNicNetworkMap, final Map<String, Network.IpAddresses> callerNicIpAddressMap, final DataCenter zone, final String hostName, final Account owner) throws ServerApiException {
        Map<String, Long> nicNetworkMap = new HashMap<>();
        String nicAdapter = null;
        for (UnmanagedInstanceTO.Nic nic : nics) {
            if (Strings.isNullOrEmpty(nicAdapter)) {
                nicAdapter = nic.getAdapterType();
            } else {
                if (!nicAdapter.equals(nic.getAdapterType())) {
                    throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Multiple network adapter of different type (%s, %s) are not supported for import. Please make sure that all network adapters are of the same type", nicAdapter, nic.getAdapterType()));
                }
            }
            Network network = null;
            Network.IpAddresses ipAddresses = null;
            if (MapUtils.isNotEmpty(callerNicIpAddressMap) && callerNicIpAddressMap.containsKey(nic.getNicId())) {
                ipAddresses = callerNicIpAddressMap.get(nic.getNicId());
            }
            if (!callerNicNetworkMap.containsKey(nic.getNicId())) {
                if (nic.getVlan() != null && nic.getVlan() != 0) {
                    // Find a suitable network
                    List<NetworkVO> networks = networkDao.listByZone(zone.getId());
                    for (NetworkVO networkVO : networks) {
                        if (networkVO.getTrafficType() == Networks.TrafficType.None || Networks.TrafficType.isSystemNetwork(networkVO.getTrafficType())) {
                            continue;
                        }
                        try {
                            checkUnmanagedNicAndNetworkForImport(nic, networkVO, zone, owner, true);
                            network = networkVO;
                        } catch (Exception e) {
                        }
                        if (network != null) {
                            checkUnmanagedNicAndNetworkHostnameForImport(nic, network, hostName);
                            checkUnmanagedNicIpAndNetworkForImport(nic, network, ipAddresses);
                            break;
                        }
                    }
                }
            } else {
                network = networkDao.findById(callerNicNetworkMap.get(nic.getNicId()));
                checkUnmanagedNicAndNetworkForImport(nic, network, zone, owner, false);
                checkUnmanagedNicAndNetworkHostnameForImport(nic, network, hostName);
                checkUnmanagedNicIpAndNetworkForImport(nic, network, ipAddresses);
            }
            if (network == null) {
                throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Suitable network for nic(ID: %s) not found during VM import", nic.getNicId()));
            }
            nicNetworkMap.put(nic.getNicId(), network.getId());
        }
        return nicNetworkMap;
    }

    private Pair<DiskProfile, StoragePool> importDisk(UnmanagedInstanceTO.Disk disk, VirtualMachine vm, Cluster cluster, DiskOffering diskOffering,
                                                      Volume.Type type, String name, Long diskSize, Long minIops, Long maxIops, VirtualMachineTemplate template,
                                                      Account owner, Long deviceId) {
        final DataCenter zone = dataCenterDao.findById(vm.getDataCenterId());
        final String path = Strings.isNullOrEmpty(disk.getFileBaseName()) ? disk.getImagePath() : disk.getFileBaseName();
        String chainInfo = disk.getChainInfo();
        if (Strings.isNullOrEmpty(chainInfo)) {
            VirtualMachineDiskInfo diskInfo = new VirtualMachineDiskInfo();
            diskInfo.setDiskDeviceBusName(String.format("%s%d:%d", disk.getController(), disk.getControllerUnit(), disk.getPosition()));
            diskInfo.setDiskChain(new String[]{disk.getImagePath()});
            chainInfo = gson.toJson(diskInfo);
        }
        StoragePool storagePool = getStoragePool(disk, zone, cluster);
        DiskProfile profile = volumeManager.importVolume(type, name, diskOffering, diskSize,
                minIops, maxIops, vm, template, owner, deviceId, storagePool.getId(), path, chainInfo);

        return new Pair<DiskProfile, StoragePool>(profile, storagePool);
    }

    private NicProfile importNic(UnmanagedInstanceTO.Nic nic, VirtualMachine vm, Network network, Network.IpAddresses ipAddresses, boolean isDefaultNic) throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException {
        Pair<NicProfile, Integer> result = networkOrchestrationService.importNic(nic.getMacAddress(), 0, network, isDefaultNic, vm, ipAddresses);
        if (result == null) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("NIC ID: %s import failed", nic.getNicId()));
        }
        return result.first();
    }

    private void cleanupFailedImportVM(final UserVm userVm) {
        if (userVm == null) {
            return;
        }
        VirtualMachineProfile profile = new VirtualMachineProfileImpl(userVm);
        // Remove all volumes
        volumeDao.deleteVolumesByInstance(userVm.getId());
        // Remove all nics
        try {
            networkOrchestrationService.release(profile, true);
        } catch (Exception e) {
            LOGGER.error(String.format("Unable to release NICs for unsuccessful import unmanaged VM: %s", userVm.getInstanceName()), e);
            nicDao.removeNicsForInstance(userVm.getId());
        }
        // Remove vm
        vmDao.remove(userVm.getId());
    }

    private UserVm migrateImportedVM(HostVO sourceHost, VirtualMachineTemplate template, ServiceOfferingVO serviceOffering, UserVm userVm, final Account owner, List<Pair<DiskProfile, StoragePool>> diskProfileStoragePoolList) {
        UserVm vm = userVm;
        if (vm == null) {
            LOGGER.error(String.format("Failed to check migrations need during VM import"));
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Failed to check migrations need during VM import"));
        }
        if (sourceHost == null || serviceOffering == null || diskProfileStoragePoolList == null) {
            LOGGER.error(String.format("Failed to check migrations need during import, VM: %s", userVm.getInstanceName()));
            cleanupFailedImportVM(vm);
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Failed to check migrations need during import, VM: %s", userVm.getInstanceName()));
        }
        if (!hostSupportsServiceOffering(sourceHost, serviceOffering)) {
            LOGGER.debug(String.format("VM %s needs to be migrated", vm.getUuid()));
            final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm, template, serviceOffering, owner, null);
            DeploymentPlanner.ExcludeList excludeList = new DeploymentPlanner.ExcludeList();
            excludeList.addHost(sourceHost.getId());
            final DataCenterDeployment plan = new DataCenterDeployment(sourceHost.getDataCenterId(), sourceHost.getPodId(), sourceHost.getClusterId(), null, null, null);
            DeployDestination dest = null;
            try {
                dest = deploymentPlanningManager.planDeployment(profile, plan, excludeList, null);
            } catch (Exception e) {
                LOGGER.warn(String.format("VM import failed for unmanaged vm: %s during vm migration, finding deployment destination", vm.getInstanceName()), e);
                cleanupFailedImportVM(vm);
                throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("VM import failed for unmanaged vm: %s during vm migration, finding deployment destination", vm.getInstanceName()));
            }
            if (dest != null) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(" Found " + dest + " for migrating the vm to");
                }
            }
            if (dest == null) {
                cleanupFailedImportVM(vm);
                throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("VM import failed for unmanaged vm: %s during vm migration, no deployment destination found", vm.getInstanceName()));
            }
            try {
                if (vm.getState().equals(VirtualMachine.State.Stopped)) {
                    VMInstanceVO vmInstanceVO = vmDao.findById(userVm.getId());
                    vmInstanceVO.setHostId(dest.getHost().getId());
                    vmInstanceVO.setLastHostId(dest.getHost().getId());
                    vmDao.update(vmInstanceVO.getId(), vmInstanceVO);
                } else {
                    virtualMachineManager.migrate(vm.getUuid(), sourceHost.getId(), dest);
                }
                vm = userVmManager.getUserVm(vm.getId());
            } catch (Exception e) {
                LOGGER.error(String.format("VM import failed for unmanaged vm: %s during vm migration", vm.getInstanceName()), e);
                cleanupFailedImportVM(vm);
                throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("VM import failed for unmanaged vm: %s during vm migration. %s", userVm.getInstanceName(), e.getMessage()));
            }
        }
        for (Pair<DiskProfile, StoragePool> diskProfileStoragePool : diskProfileStoragePoolList) {
            if (diskProfileStoragePool == null ||
                    diskProfileStoragePool.first() == null ||
                    diskProfileStoragePool.second() == null) {
                continue;
            }
            DiskProfile profile = diskProfileStoragePool.first();
            DiskOffering dOffering = diskOfferingDao.findById(profile.getDiskOfferingId());
            if (dOffering == null) {
                continue;
            }
            VolumeVO volumeVO = volumeDao.findById(profile.getVolumeId());
            if (volumeVO == null) {
                continue;
            }
            boolean poolSupportsOfferings = storagePoolSupportsDiskOffering(diskProfileStoragePool.second(), dOffering);
            if (poolSupportsOfferings && profile.getType() == Volume.Type.ROOT) {
                poolSupportsOfferings = storagePoolSupportsServiceOffering(diskProfileStoragePool.second(), serviceOffering);
            }
            if (poolSupportsOfferings) {
                continue;
            }
            LOGGER.debug(String.format("Volume %s needs to be migrated", volumeVO.getUuid()));
            Pair<List<? extends StoragePool>, List<? extends StoragePool>> poolsPair = managementService.listStoragePoolsForMigrationOfVolume(profile.getVolumeId());
            if (CollectionUtils.isEmpty(poolsPair.first()) && CollectionUtils.isEmpty(poolsPair.second())) {
                cleanupFailedImportVM(vm);
                throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("VM import failed for unmanaged vm: %s during volume ID: %s migration as no suitable pool(s) found", userVm.getInstanceName(), volumeVO.getUuid()));
            }
            List<? extends StoragePool> storagePools = poolsPair.second();
            StoragePool storagePool = null;
            if (CollectionUtils.isNotEmpty(storagePools)) {
                for (StoragePool pool : storagePools) {
                    if (diskProfileStoragePool.second().getId() != pool.getId() &&
                            storagePoolSupportsDiskOffering(pool, dOffering) &&
                            (!profile.getType().equals(Volume.Type.ROOT) ||
                                    profile.getType().equals(Volume.Type.ROOT) && storagePoolSupportsServiceOffering(pool, serviceOffering))) {
                        storagePool = pool;
                        break;
                    }
                }
            }
            // For zone-wide pools, at times, suitable storage pools are not returned therefore consider all pools.
            if (storagePool == null && CollectionUtils.isNotEmpty(poolsPair.first())) {
                storagePools = poolsPair.first();
                for (StoragePool pool : storagePools) {
                    if (diskProfileStoragePool.second().getId() != pool.getId() &&
                            storagePoolSupportsDiskOffering(pool, dOffering) &&
                            (!profile.getType().equals(Volume.Type.ROOT) ||
                                    profile.getType().equals(Volume.Type.ROOT) && storagePoolSupportsServiceOffering(pool, serviceOffering))) {
                        storagePool = pool;
                        break;
                    }
                }
            }
            if (storagePool == null) {
                cleanupFailedImportVM(vm);
                throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("VM import failed for unmanaged vm: %s during volume ID: %s migration as no suitable pool found", userVm.getInstanceName(), volumeVO.getUuid()));
            } else {
                LOGGER.debug(String.format("Found storage pool %s(%s) for migrating the volume %s to", storagePool.getName(), storagePool.getUuid(), volumeVO.getUuid()));
            }
            try {
                Volume volume = null;
                if (vm.getState().equals(VirtualMachine.State.Running)) {
                    volume = volumeManager.liveMigrateVolume(volumeVO, storagePool);
                } else {
                    volume = volumeManager.migrateVolume(volumeVO, storagePool);
                }
                if (volume == null) {
                    String msg = "";
                    if (vm.getState().equals(VirtualMachine.State.Running)) {
                        msg = String.format("Live migration for volume ID: %s to destination pool ID: %s failed", volumeVO.getUuid(), storagePool.getUuid());
                    } else {
                        msg = String.format("Migration for volume ID: %s to destination pool ID: %s failed", volumeVO.getUuid(), storagePool.getUuid());
                    }
                    LOGGER.error(msg);
                    throw new CloudRuntimeException(msg);
                }
            } catch (Exception e) {
                LOGGER.error(String.format("VM import failed for unmanaged vm: %s during volume migration", vm.getInstanceName()), e);
                cleanupFailedImportVM(vm);
                throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("VM import failed for unmanaged vm: %s during volume migration. %s", userVm.getInstanceName(), Strings.nullToEmpty(e.getMessage())));
            }
        }
        return userVm;
    }

    private void publishVMUsageUpdateResourceCount(final UserVm userVm, ServiceOfferingVO serviceOfferingVO) {
        if (userVm == null || serviceOfferingVO == null) {
            LOGGER.error("Failed to publish usage records during VM import");
            cleanupFailedImportVM(userVm);
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("VM import failed for unmanaged vm during publishing usage records"));
        }
        try {
            if (!serviceOfferingVO.isDynamic()) {
                UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_IMPORT, userVm.getAccountId(), userVm.getDataCenterId(), userVm.getId(), userVm.getHostName(), serviceOfferingVO.getId(), userVm.getTemplateId(),
                        userVm.getHypervisorType().toString(), VirtualMachine.class.getName(), userVm.getUuid(), userVm.isDisplayVm());
            } else {
                UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_IMPORT, userVm.getAccountId(), userVm.getAccountId(), userVm.getDataCenterId(), userVm.getHostName(), serviceOfferingVO.getId(), userVm.getTemplateId(),
                        userVm.getHypervisorType().toString(), VirtualMachine.class.getName(), userVm.getUuid(), userVm.getDetails(), userVm.isDisplayVm());
            }
        } catch (Exception e) {
            LOGGER.error(String.format("Failed to publish usage records during VM import for unmanaged vm %s", userVm.getInstanceName()), e);
            cleanupFailedImportVM(userVm);
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("VM import failed for unmanaged vm %s during publishing usage records", userVm.getInstanceName()));
        }
        resourceLimitService.incrementResourceCount(userVm.getAccountId(), Resource.ResourceType.user_vm, userVm.isDisplayVm());
        resourceLimitService.incrementResourceCount(userVm.getAccountId(), Resource.ResourceType.cpu, userVm.isDisplayVm(), new Long(serviceOfferingVO.getCpu()));
        resourceLimitService.incrementResourceCount(userVm.getAccountId(), Resource.ResourceType.memory, userVm.isDisplayVm(), new Long(serviceOfferingVO.getRamSize()));
        // Save usage event and update resource count for user vm volumes
        List<VolumeVO> volumes = volumeDao.findByInstance(userVm.getId());
        for (VolumeVO volume : volumes) {
            try {
                UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), volume.getDiskOfferingId(), null, volume.getSize(),
                        Volume.class.getName(), volume.getUuid(), volume.isDisplayVolume());
            } catch (Exception e) {
                LOGGER.error(String.format("Failed to publish volume ID: %s usage records during VM import", volume.getUuid()), e);
            }
            resourceLimitService.incrementResourceCount(userVm.getAccountId(), Resource.ResourceType.volume, volume.isDisplayVolume());
            resourceLimitService.incrementResourceCount(userVm.getAccountId(), Resource.ResourceType.primary_storage, volume.isDisplayVolume(), volume.getSize());
        }
    }

    private UserVm importVirtualMachineInternal(final UnmanagedInstanceTO unmanagedInstance, final String instanceName, final DataCenter zone, final Cluster cluster, final HostVO host,
                                                final VirtualMachineTemplate template, final String displayName, final String hostName, final Account caller, final Account owner, final Long userId,
                                                final ServiceOfferingVO serviceOffering, final Map<String, Long> dataDiskOfferingMap,
                                                final Map<String, Long> nicNetworkMap, final Map<String, Network.IpAddresses> callerNicIpAddressMap,
                                                final Map<String, String> details, final boolean migrateAllowed) {
        UserVm userVm = null;

        ServiceOfferingVO validatedServiceOffering = null;
        try {
            validatedServiceOffering = getUnmanagedInstanceServiceOffering(unmanagedInstance, serviceOffering, owner, zone, details);
        } catch (Exception e) {
            LOGGER.error("Service offering for VM import not compatible", e);
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Failed to import VM: %s. %s", unmanagedInstance.getName(), Strings.nullToEmpty(e.getMessage())));
        }

        Map<String, String> allDetails = new HashMap<>(details);
        if (validatedServiceOffering.isDynamic()) {
            allDetails.put(VmDetailConstants.CPU_NUMBER, String.valueOf(validatedServiceOffering.getCpu()));
            allDetails.put(VmDetailConstants.MEMORY, String.valueOf(validatedServiceOffering.getRamSize()));
            if (serviceOffering.getSpeed() == null) {
                allDetails.put(VmDetailConstants.CPU_SPEED, String.valueOf(validatedServiceOffering.getSpeed()));
            }
        }

        if (!migrateAllowed && !hostSupportsServiceOffering(host, validatedServiceOffering)) {
            throw new InvalidParameterValueException(String.format("Service offering: %s is not compatible with host: %s of unmanaged VM: %s", serviceOffering.getUuid(), host.getUuid(), instanceName));
        }
        // Check disks and supplied disk offerings
        List<UnmanagedInstanceTO.Disk> unmanagedInstanceDisks = unmanagedInstance.getDisks();
        if (CollectionUtils.isEmpty(unmanagedInstanceDisks)) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("No attached disks found for the unmanaged VM: %s", instanceName));
        }
        final UnmanagedInstanceTO.Disk rootDisk = unmanagedInstance.getDisks().get(0);
        if (rootDisk == null || Strings.isNullOrEmpty(rootDisk.getController())) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("VM import failed. Unable to retrieve root disk details for VM: %s ", instanceName));
        }
        allDetails.put(VmDetailConstants.ROOT_DISK_CONTROLLER, rootDisk.getController());
        List<UnmanagedInstanceTO.Disk> dataDisks = new ArrayList<>();
        try {
            checkUnmanagedDiskAndOfferingForImport(rootDisk, null, validatedServiceOffering, owner, zone, cluster, migrateAllowed);
            if (unmanagedInstanceDisks.size() > 1) { // Data disk(s) present
                dataDisks.addAll(unmanagedInstanceDisks);
                dataDisks.remove(0);
                checkUnmanagedDiskAndOfferingForImport(dataDisks, dataDiskOfferingMap, owner, zone, cluster, migrateAllowed);
                allDetails.put(VmDetailConstants.DATA_DISK_CONTROLLER, dataDisks.get(0).getController());
            }
            resourceLimitService.checkResourceLimit(owner, Resource.ResourceType.volume, unmanagedInstanceDisks.size());
        } catch (ResourceAllocationException e) {
            LOGGER.error(String.format("Volume resource allocation error for owner: %s", owner.getUuid()), e);
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Volume resource allocation error for owner: %s. %s", owner.getUuid(), Strings.nullToEmpty(e.getMessage())));
        }
        // Check NICs and supplied networks
        Map<String, Network.IpAddresses> nicIpAddressMap = getNicIpAddresses(unmanagedInstance.getNics(), callerNicIpAddressMap);
        Map<String, Long> allNicNetworkMap = getUnmanagedNicNetworkMap(unmanagedInstance.getNics(), nicNetworkMap, nicIpAddressMap, zone, hostName, owner);
        if (!CollectionUtils.isEmpty(unmanagedInstance.getNics())) {
            allDetails.put(VmDetailConstants.NIC_ADAPTER, unmanagedInstance.getNics().get(0).getAdapterType());
        }
        VirtualMachine.PowerState powerState = VirtualMachine.PowerState.PowerOff;
        if (unmanagedInstance.getPowerState().equals(UnmanagedInstanceTO.PowerState.PowerOn)) {
            powerState = VirtualMachine.PowerState.PowerOn;
        }
        try {
            userVm = userVmManager.importVM(zone, host, template, instanceName, displayName, owner,
                    null, caller, true, null, owner.getAccountId(), userId,
                    validatedServiceOffering, null, hostName,
                    cluster.getHypervisorType(), allDetails, powerState);
        } catch (InsufficientCapacityException ice) {
            LOGGER.error(String.format("Failed to import vm name: %s", instanceName), ice);
            throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ice.getMessage());
        }
        if (userVm == null) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Failed to import vm name: %s", instanceName));
        }
        List<Pair<DiskProfile, StoragePool>> diskProfileStoragePoolList = new ArrayList<>();
        try {
            if (rootDisk.getCapacity() == null || rootDisk.getCapacity() == 0) {
                throw new InvalidParameterValueException(String.format("Root disk ID: %s size is invalid", rootDisk.getDiskId()));
            }
            Long minIops = null;
            if (details.containsKey("minIops")) {
                minIops = Long.parseLong(details.get("minIops"));
            }
            Long maxIops = null;
            if (details.containsKey("maxIops")) {
                maxIops = Long.parseLong(details.get("maxIops"));
            }
            diskProfileStoragePoolList.add(importDisk(rootDisk, userVm, cluster, serviceOffering, Volume.Type.ROOT, String.format("ROOT-%d", userVm.getId()),
                    (rootDisk.getCapacity() / Resource.ResourceType.bytesToGiB), minIops, maxIops,
                    template, owner, null));
            for (UnmanagedInstanceTO.Disk disk : dataDisks) {
                if (disk.getCapacity() == null || disk.getCapacity() == 0) {
                    throw new InvalidParameterValueException(String.format("Disk ID: %s size is invalid", rootDisk.getDiskId()));
                }
                DiskOffering offering = diskOfferingDao.findById(dataDiskOfferingMap.get(disk.getDiskId()));
                diskProfileStoragePoolList.add(importDisk(disk, userVm, cluster, offering, Volume.Type.DATADISK, String.format("DATA-%d-%s", userVm.getId(), disk.getDiskId()),
                        (disk.getCapacity() / Resource.ResourceType.bytesToGiB), offering.getMinIops(), offering.getMaxIops(),
                        template, owner, null));
            }
        } catch (Exception e) {
            LOGGER.error(String.format("Failed to import volumes while importing vm: %s", instanceName), e);
            cleanupFailedImportVM(userVm);
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Failed to import volumes while importing vm: %s. %s", instanceName, Strings.nullToEmpty(e.getMessage())));
        }
        try {
            boolean firstNic = true;
            for (UnmanagedInstanceTO.Nic nic : unmanagedInstance.getNics()) {
                Network network = networkDao.findById(allNicNetworkMap.get(nic.getNicId()));
                Network.IpAddresses ipAddresses = nicIpAddressMap.get(nic.getNicId());
                importNic(nic, userVm, network, ipAddresses, firstNic);
                firstNic = false;
            }
        } catch (Exception e) {
            LOGGER.error(String.format("Failed to import NICs while importing vm: %s", instanceName), e);
            cleanupFailedImportVM(userVm);
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Failed to import NICs while importing vm: %s. %s", instanceName, Strings.nullToEmpty(e.getMessage())));
        }
        if (migrateAllowed) {
            userVm = migrateImportedVM(host, template, validatedServiceOffering, userVm, owner, diskProfileStoragePoolList);
        }
        publishVMUsageUpdateResourceCount(userVm, validatedServiceOffering);
        return userVm;
    }

    @Override
    public ListResponse<UnmanagedInstanceResponse> listUnmanagedInstances(ListUnmanagedInstancesCmd cmd) {
        final Account caller = CallContext.current().getCallingAccount();
        if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
            throw new PermissionDeniedException(String.format("Cannot perform this operation, Calling account is not root admin: %s", caller.getUuid()));
        }
        final Long clusterId = cmd.getClusterId();
        if (clusterId == null) {
            throw new InvalidParameterValueException(String.format("Cluster ID cannot be null"));
        }
        final Cluster cluster = clusterDao.findById(clusterId);
        if (cluster == null) {
            throw new InvalidParameterValueException(String.format("Cluster ID: %d cannot be found", clusterId));
        }
        if (cluster.getHypervisorType() != Hypervisor.HypervisorType.VMware) {
            throw new InvalidParameterValueException(String.format("VM ingestion is currently not supported for hypervisor: %s", cluster.getHypervisorType().toString()));
        }
        List<HostVO> hosts = resourceManager.listHostsInClusterByStatus(clusterId, Status.Up);
        List<String> additionalNameFilters = getAdditionalNameFilters(cluster);
        List<UnmanagedInstanceResponse> responses = new ArrayList<>();
        for (HostVO host : hosts) {
            if (host.isInMaintenanceStates()) {
                continue;
            }
            List<String> managedVms = new ArrayList<>();
            managedVms.addAll(additionalNameFilters);
            managedVms.addAll(getHostManagedVms(host));

            GetUnmanagedInstancesCommand command = new GetUnmanagedInstancesCommand();
            command.setInstanceName(cmd.getName());
            command.setManagedInstancesNames(managedVms);
            Answer answer = agentManager.easySend(host.getId(), command);
            if (!(answer instanceof GetUnmanagedInstancesAnswer)) {
                continue;
            }
            GetUnmanagedInstancesAnswer unmanagedInstancesAnswer = (GetUnmanagedInstancesAnswer) answer;
            HashMap<String, UnmanagedInstanceTO> unmanagedInstances = new HashMap<>();
            unmanagedInstances.putAll(unmanagedInstancesAnswer.getUnmanagedInstances());
            Set<String> keys = unmanagedInstances.keySet();
            for (String key : keys) {
                responses.add(createUnmanagedInstanceResponse(unmanagedInstances.get(key), cluster, host));
            }
        }
        ListResponse<UnmanagedInstanceResponse> listResponses = new ListResponse<>();
        listResponses.setResponses(responses, responses.size());
        return listResponses;
    }

    @Override
    public UserVmResponse importUnmanagedInstance(ImportUnmanagedInstanceCmd cmd) {
        final Account caller = CallContext.current().getCallingAccount();
        if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
            throw new PermissionDeniedException(String.format("Cannot perform this operation, Calling account is not root admin: %s", caller.getUuid()));
        }
        final Long clusterId = cmd.getClusterId();
        if (clusterId == null) {
            throw new InvalidParameterValueException(String.format("Cluster ID cannot be null"));
        }
        final Cluster cluster = clusterDao.findById(clusterId);
        if (cluster == null) {
            throw new InvalidParameterValueException(String.format("Cluster ID: %d cannot be found", clusterId));
        }
        if (cluster.getHypervisorType() != Hypervisor.HypervisorType.VMware) {
            throw new InvalidParameterValueException(String.format("VM import is currently not supported for hypervisor: %s", cluster.getHypervisorType().toString()));
        }
        final DataCenter zone = dataCenterDao.findById(cluster.getDataCenterId());
        final String instanceName = cmd.getName();
        if (Strings.isNullOrEmpty(instanceName)) {
            throw new InvalidParameterValueException(String.format("Instance name cannot be empty"));
        }
        if (cmd.getDomainId() != null && Strings.isNullOrEmpty(cmd.getAccountName())) {
            throw new InvalidParameterValueException("domainid parameter must be specified with account parameter");
        }
        final Account owner = accountService.getActiveAccountById(cmd.getEntityOwnerId());
        long userId = CallContext.current().getCallingUserId();
        List<UserVO> userVOs = userDao.listByAccount(owner.getAccountId());
        if (CollectionUtils.isNotEmpty(userVOs)) {
            userId = userVOs.get(0).getId();
        }
        VMTemplateVO template = null;
        final Long templateId = cmd.getTemplateId();
        if (templateId == null) {
            template = templateDao.findByName(VM_IMPORT_DEFAULT_TEMPLATE_NAME);
            if (template == null) {
                template = createDefaultDummyVmImportTemplate();
                if (template == null) {
                    throw new InvalidParameterValueException(String.format("Default VM import template with unique name: %s for hypervisor: %s cannot be created. Please use templateid paramter for import", VM_IMPORT_DEFAULT_TEMPLATE_NAME, cluster.getHypervisorType().toString()));
                }
            }
        } else {
            template = templateDao.findById(templateId);
        }
        if (template == null) {
            throw new InvalidParameterValueException(String.format("Template ID: %d cannot be found", templateId));
        }
        final Long serviceOfferingId = cmd.getServiceOfferingId();
        if (serviceOfferingId == null) {
            throw new InvalidParameterValueException(String.format("Service offering ID cannot be null"));
        }
        final ServiceOfferingVO serviceOffering = serviceOfferingDao.findById(serviceOfferingId);
        if (serviceOffering == null) {
            throw new InvalidParameterValueException(String.format("Service offering ID: %d cannot be found", serviceOfferingId));
        }
        accountService.checkAccess(owner, serviceOffering, zone);
        try {
            resourceLimitService.checkResourceLimit(owner, Resource.ResourceType.user_vm, 1);
        } catch (ResourceAllocationException e) {
            LOGGER.error(String.format("VM resource allocation error for account: %s", owner.getUuid()), e);
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("VM resource allocation error for account: %s. %s", owner.getUuid(), Strings.nullToEmpty(e.getMessage())));
        }
        String displayName = cmd.getDisplayName();
        if (Strings.isNullOrEmpty(displayName)) {
            displayName = instanceName;
        }
        String hostName = cmd.getHostName();
        if (Strings.isNullOrEmpty(hostName)) {
            if (!NetUtils.verifyDomainNameLabel(instanceName, true)) {
                throw new InvalidParameterValueException(String.format("Please provide hostname for the VM. VM name contains unsupported characters for it to be used as hostname"));
            }
            hostName = instanceName;
        }
        if (!NetUtils.verifyDomainNameLabel(hostName, true)) {
            throw new InvalidParameterValueException("Invalid VM hostname. VM hostname can contain ASCII letters 'a' through 'z', the digits '0' through '9', "
                    + "and the hyphen ('-'), must be between 1 and 63 characters long, and can't start or end with \"-\" and can't start with digit");
        }
        if (cluster.getHypervisorType().equals(Hypervisor.HypervisorType.VMware) &&
                Boolean.parseBoolean(configurationDao.getValue(Config.SetVmInternalNameUsingDisplayName.key()))) {
            // If global config vm.instancename.flag is set to true, then CS will set guest VM's name as it appears on the hypervisor, to its hostname.
            // In case of VMware since VM name must be unique within a DC, check if VM with the same hostname already exists in the zone.
            VMInstanceVO vmByHostName = vmDao.findVMByHostNameInZone(hostName, zone.getId());
            if (vmByHostName != null && vmByHostName.getState() != VirtualMachine.State.Expunging) {
                throw new InvalidParameterValueException(String.format("Failed to import VM: %s. There already exists a VM by the hostname: %s in zone: %s", instanceName, hostName, zone.getUuid()));
            }
        }
        final Map<String, Long> nicNetworkMap = cmd.getNicNetworkList();
        final Map<String, Network.IpAddresses> nicIpAddressMap = cmd.getNicIpAddressList();
        final Map<String, Long> dataDiskOfferingMap = cmd.getDataDiskToDiskOfferingList();
        final Map<String, String> details = cmd.getDetails();
        List<HostVO> hosts = resourceManager.listHostsInClusterByStatus(clusterId, Status.Up);
        UserVm userVm = null;
        List<String> additionalNameFilters = getAdditionalNameFilters(cluster);
        for (HostVO host : hosts) {
            if (host.isInMaintenanceStates()) {
                continue;
            }
            List<String> managedVms = new ArrayList<>();
            managedVms.addAll(additionalNameFilters);
            managedVms.addAll(getHostManagedVms(host));
            GetUnmanagedInstancesCommand command = new GetUnmanagedInstancesCommand(instanceName);
            command.setManagedInstancesNames(managedVms);
            Answer answer = agentManager.easySend(host.getId(), command);
            if (!(answer instanceof GetUnmanagedInstancesAnswer)) {
                continue;
            }
            GetUnmanagedInstancesAnswer unmanagedInstancesAnswer = (GetUnmanagedInstancesAnswer) answer;
            HashMap<String, UnmanagedInstanceTO> unmanagedInstances = unmanagedInstancesAnswer.getUnmanagedInstances();
            if (MapUtils.isEmpty(unmanagedInstances)) {
                continue;
            }
            Set<String> names = unmanagedInstances.keySet();
            for (String name : names) {
                if (instanceName.equals(name)) {
                    UnmanagedInstanceTO unmanagedInstance = unmanagedInstances.get(name);
                    if (unmanagedInstance == null) {
                        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Unable to retrieve details for unmanaged VM: %s", name));
                    }
                    if (template.getName().equals(VM_IMPORT_DEFAULT_TEMPLATE_NAME)) {
                        String osName = unmanagedInstance.getOperatingSystem();
                        GuestOS guestOS = null;
                        if (!Strings.isNullOrEmpty(osName)) {
                            guestOS = guestOSDao.listByDisplayName(osName);
                        }
                        GuestOSHypervisor guestOSHypervisor = null;
                        if (guestOS != null) {
                            guestOSHypervisor = guestOSHypervisorDao.findByOsIdAndHypervisor(guestOS.getId(), host.getHypervisorType().toString(), host.getHypervisorVersion());
                        }
                        if (guestOSHypervisor == null && !Strings.isNullOrEmpty(unmanagedInstance.getOperatingSystemId())) {
                            guestOSHypervisor = guestOSHypervisorDao.findByOsNameAndHypervisor(unmanagedInstance.getOperatingSystemId(), host.getHypervisorType().toString(), host.getHypervisorVersion());
                        }
                        if (guestOSHypervisor == null) {
                            if (guestOS != null) {
                                throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Unable to find hypervisor guest OS ID: %s details for unmanaged VM: %s for hypervisor: %s version: %s. templateid parameter can be used to assign template for VM", guestOS.getUuid(), name, host.getHypervisorType().toString(), host.getHypervisorVersion()));
                            }
                            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Unable to retrieve guest OS details for unmanaged VM: %s with OS name: %s, OS ID: %s for hypervisor: %s version: %s. templateid parameter can be used to assign template for VM", name, osName, unmanagedInstance.getOperatingSystemId(), host.getHypervisorType().toString(), host.getHypervisorVersion()));
                        }
                        template.setGuestOSId(guestOSHypervisor.getGuestOsId());
                    }
                    userVm = importVirtualMachineInternal(unmanagedInstance, instanceName, zone, cluster, host,
                            template, displayName, hostName, caller, owner, userId,
                            serviceOffering, dataDiskOfferingMap,
                            nicNetworkMap, nicIpAddressMap,
                            details, cmd.getMigrateAllowed());
                    break;
                }
            }
            if (userVm != null) {
                break;
            }
        }
        if (userVm == null) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Failed to find unmanaged vm with name: %s in cluster: %s", instanceName, cluster.getUuid()));
        }
        return responseGenerator.createUserVmResponse(ResponseObject.ResponseView.Full, "virtualmachine", userVm).get(0);
    }

    @Override
    public List<Class<?>> getCommands() {
        final List<Class<?>> cmdList = new ArrayList<Class<?>>();
        cmdList.add(ListUnmanagedInstancesCmd.class);
        cmdList.add(ImportUnmanagedInstanceCmd.class);
        return cmdList;
    }
}

redpajama_set_name: RedPajamaGithub


text:
Addison Allen Bedford Cleburne Dallas Ennis Forney Grand Prairie Highland Park Lancaster Mansfield Murphy Rowlett Sherman Waxahachie Rockwall Arlington Balch Springs Burleson Carrollton Cedar Hill Colleyville Coppell Corinth Denton Desoto Euless Farmers Branch Fort Worth Frisco Grapevine Greenville Hurst Irving Lavon Lewisville McKinney Mesquite North Richland Hills Plano Royse City Sachse Southlake The Colony Weatherford Wichita Falls Kaufman Duncanville Flower Mound Garland Heath Keller Little Elm Midlothian Richardson Seagoville University Park Wylie Westlake
$25,000 $50,000 $75,000 $100,000 $110,000 $120,000 $130,000 $140,000 $150,000 $160,000 $170,000 $180,000 $190,000 $200,000 $225,000 $250,000 $275,000 $300,000 $325,000 $350,000 $375,000 $400,000 $450,000 $500,000 $550,000 $600,000 $650,000 $700,000 $750,000 $800,000 $850,000 $900,000 $950,000 $1,000,000 $1,500,000 $2,000,000 $3,000,000 $4,000,000 $5,000,000 $10,000,000
600 800 1000 1200 1400 1600 1800 2000 2200 2400 2600 2800 3000 3200 3400 3600 3800 4000 4200 4400 4600 4800 5000 5200 5400 5600 5800 6000 6200 6400 6600 6800 7000 7200 7400 7600 7800 8000 8200 8400 8600 8800 9000 9200 9400 9600 9800 10000

redpajama_set_name: RedPajamaCommonCrawl


Be the best parent, aunt, uncle, cousin or family friend and get the kid in your life a scooter. Hours and hours of fun are guaranteed with our range of kids' scooters. We have two-wheelers, and three-wheelers - they're powered purely by your feet on the front bar and are great for your core and balance - as well as colourful covers so they can change up how their scooter looks. They're easy to transport too.


text:
Q: Determine all SVG elements on a certain coordinate (mouseclick) What i need is a clickhandler to be able to work on multiple layered objects in an SVG, paths or lines for example. What would be the best approach to determine all the elements that pass through a certain coordinate.

A: *

*Call document.elementFromPoint - that will tell you the frontmost element under the mouse

*If any element is found in step 1, set that element to be pointer-events: none and return to step 1.

*If not quit, you will have found all the elements in the above loop. Don't forget to delete the pointer-events property you've set on all the elements you found or you won't find them next time.

A: Probably the simplest solution is to use document.elementsFromPoint():

The elementsFromPoint() property of the DocumentOrShadowRoot interface returns an array of all elements at the specified coordinates (relative to the viewport).

The browser compatibility is good and it will give you all the elements with a single call.

redpajama_set_name: RedPajamaStackExchange


Learn the tested and proven health benefits of positive thinking right now.
Find Pageant Supplies. Search Now!
Tired of Endless Searching? Find Pageant on DealsNow.
What Are The Benefits Of Beauty Pageants?
For the person whose only exposure to beauty pageants is from what they see on television, it's difficult to understand why anyone would choose to do a beauty pageant. After all, showcasing the benefits of doing a beauty pageant wouldn't get the ratings that the drama does.
Many people argue the negative aspects of these contests, but there are just as many benefits that play a huge role in the psychological effects these children encounter. Positive features such as a growth in confidence, outgoing personality, and a positive self-image are seen widely within the pageant world today.
One of the benefits of joining beauty competitions is learning about self-worth. It encourages young women to look into their inner self and explore their skills and talents like public speaking, singing and dancing. Conquering stage fright is also one of the good aspects of beauty pageants.
But why should they be encouraged to enter the pageant? I, Gail Clark, State Director of Miss Texas USA ® and Miss Texas Teen USA ® pageants, would like to share a few of my personal observations from my 30 years of experience in the pageant business – as a former contestant and as a producer of over 75 pageants.
I did recently compete in the District Convention for the state title to no avail, but I realized the experience brought about so many opportunities and benefits regardless of winning. CONFIDENCE. In the midst of being in a pageant I learned that people can be destructive or supportive.
This past year, Miss America corporation publicly apologized to Williams. Pageants give young women the advantage to become a woman with higher standards of living. There are many positives when it comes to competing in beauty pageants. Many young girls can compete for scholarship money to attend college.
The Positives of Beauty Pageants By Jade Dando • Falmouth Contributor November 8, 2016 at 5:07am It's easy to get completely lost in the media's view of beauty pageants; from Toddlers in Tiaras to the Miss Universe 2015 wrong winner announcement, these hardly promote pageants and quite frankly give people the wrong impression.
The Benefits of Participating in Pageants - Chantelle Wright - Read Christian homeschooling help and advice with home school resources and Biblical guidance for home education.


The location of our first dental clinic in 2001, Nepal, has only a few hundred dentists to serve a population of 28 million. Our journey to South Asia and one of the poorest countries in the world begins in the bustling capital city of Kathmandu, where we set up a field dental clinic at our local host school, Shree Mangal Dvip.
The clinic is a five-minute walk to Boudhnath Stupa, a UNESCO World Heritage and Buddhist religious site. In partnership with Shree Mangil Dvip and assisted by local Nepali students, we operate out of a large classroom and serve children from charity schools, orphanages, and remote mountain areas.
Days off from the clinic are spent visiting the seven UNESCO World Heritage Sites in the Kathmandu Valley and taking in the local Tibetan and Nepali culture.
Following a week of working in the clinic in Kathmandu, volunteers board a domestic flight to Baratpur in the Nepali lowlands. They then travel overland to the Chitwan Jungle National Park, where they will spend the next two days embarking on safaris at sunrise and sunset, spotting wildlife, including rhinoceros and tigers; learning about and bathing elephants; and exploring the majestic surroundings on foot.


text:
Billy Elliot (2000)
Dir. Stephen Daldry
Feat. Jamie Bell, Julie Walters
While his father and brother bare the burden of the protracted miner's strike in early 80s Yorkshire, an 11–year–old lad skives off from…
Undertow (2004)
Dir. David Gordon Green
Feat. Jamie Bell, Josh Lucas, Dermot Mulroney
Southern Gothic melodrama from dir. Green (GEORGE WASHINGTON) who here applies his off–centre visual tics to a story of family inheritances,…
Dear Wendy (2005)
Dir. Thomas Vinterberg
Feat. Jamie Bell, Bill Pullman
Pressed from the same pattern as DOGVILLE, this stylised allegory scripted by Lars Von Trier also proffers a tale set in some timeless era of the…
King Kong (2005)
Dir. Peter Jackson
Feat. Naomi Watts, Adrien Brody, Jack Black…
Peter Jackson's colossal remake lavishes one of the cinema's greatest legends in 21st century technology and ratchets up the emotional stakes to…
Chumscrubber, The (2005)
Dir. Arie Posin
Feat. Jamie Bell, Camilla Belle, Glenn Close…
A sadsack teenager (Bell) living in a sterile new suburb in Southern California discovers his best friend has committed suicide, an event which seems…
Flags of our Fathers (2006)
Dir. Clint Eastwood
Feat. Ryan Phillippe, Jesse Bradford, Adam Beach…
Part one of Clint Eastwood's Pacific double–bill trades unrelenting battle scenes for an insightful and crucially honest back–story…
Hallam Foe (Mister Foe) (2007)
Dir. David Mackenzie
Feat. Jamie Bell, Sophia Myles, Ciaran Hinds…
Jamie Bell plays the film's titular voyeur, a compulsive rooftop snoop in pursuit of justice and love, in this breezy, twisted romance. Fleeing…
Dir. Doug Liman
Feat. Hayden Christensen, Samuel L. Jackson, Jamie Bell
Pea–brained, wildly disjointed sci–fi chase flick from the director of THE BOURNE IDENTITY centres on a 'jumper' (Christensen) whose…
Defiance (2008)
Dir. Edward Zwick
Feat. Daniel Craig, Liev Schreiber, Jamie Bell…
Edward Zwick (GLORY) delivers big, earnest moments in this true story of four brothers who launch an all–Jewish resistance against the Nazis…
Eagle, The (2011)
Dir. Kevin MacDonald
Feat. Channing Tatum, Jamie Bell, Donald Sutherland…
Rousing, decidedly old–school epic with Tatum as a Roman soldier who journeys to occupied Britain to discover what caused the disappearance of…
Results Page | 1 | 2 | 3 | Next Show All


text:
Actress Jill Clayburgh dies of cancer
Jill Clayburgh, an actress who's career spanned five decades, has died in her home in Connecticut after a twenty-one year battle with lymphocytic leukemia. She was aged 66.
Clayburgh starred in films such as An Unmarried Woman and It's My Turn and was married to David Rabe, an award winning playwright.
Daughter, Lily Rabe who was appearing in A Merchant of Venice on Broadway took compassionate leave to be with her mother.
Husband David Rabe reported that his wife had died on Friday surrounded by her family at her home in Lakeville, Connecticut, after a 21-year battle with the disease. He added proudly that she dealt with the disease courageously, and with a quiet dignity, "and made it into an opportunity for her children to grow and be human."
The actress helped usher in a new era of confident Hollywood actress, alongside peers such as Anne Bancroft, Shirley MacLaine and Jane Fonda.
The pinnacle of her success came courtesy of her role as a divorcee in An Unmarried Woman, a role in which free from the shackles of a sixteen year marriage, the protagonist went on to explore her sexuality.
She leaves behind three children: daughter Lily Rabe and two sons, Michael and Jason.
RIP Jill.
image: n2fan.net


MacOS High Sierra, the latest version of Apple's desktop OS, is finally here. One of the biggest changes is under the hood, switching the OS over to a new, more efficient file system called Apple File System (APFS). Such a major change is always going to come with weird bugs and quirks, but that still doesn't excuse a new security bug exposed by researchers.
Software developer Matheus Mariano has found a serious bug that reveals the passwords for encrypted APFS volumes when you click "show password hint" within Disk Utility. This isn't your kind of deep-down zero-day hacking vulnerability; it just looks like a simple oversight, but the end result is that anyone with access to your device can open encrypted volumes on your MacBook.
All Mariano had to do in a demonstration was set up a new encrypted volume from within Disk Utility, unmount and remount the volume to force a password prompt, and hit "show hint." His password for the volume then showed up in plain text.
Felix Schwarz, another software developer, managed to reproduce the bug on his device. He also showed that it's a bug within Disk Utility, not the underlying software, as doing the same steps from the command line shows the password hint, rather than the actual password.
The issue is still present in the most recent beta version of macOS High Sierra, which means any fix will take a while to roll out. In the meantime, disable any password hints, as that seems to band-aid fix the issue.


Text Reference Number debut19 What's this?
This 16" x 20" photograph has been personally hand-signed by John Gibson with the inscriptions "NHL DEBUT 4-7-14/18 SAVE SHUTOUT/1ST NHL WIN." It is officially licensed by the National Hockey League and comes with an individually numbered, tamper-evident hologram from Fanatics Authentic. To ensure authenticity, the hologram can be reviewed online. This process helps to ensure that the product purchased is authentic and eliminates any possibility of duplication or fraud. This is a limited edition 1 of 14.
Click here to login and register your phone number for Text bidding. If already registered, text debut19;<bidAmount> (e.g., debut19;20) to +19049901334 to bid.


Black Celebrity Gossip - 41-year-old rapper from the Bronx, Jimmy Jones, just revealed that he had a horrible Christmas, apparently he came home to a burnt down house. He is happy that nobody was injured plus he said he is going to buy his family the biggest house he can afford, Worldwide Spotlight will keep you updated with Jimmy Jones' burnt down house.
Sandman Esquire releases "Roll in Peace" Freestyle and everyone say's it's Fire !


text:
AVID News
The Pacer
October 7Pfizer asks US to allow COVID shots for kids ages 5 to 11
Bishop Sycamore
Eli Morkert|September 20, 2021
IMG Academy in Florida, one of the largest athlete factory high schools in the country had their first game of the year on Sunday, August 29th broadcasted live on ESPN. IMG Academy is one of the highest ranked football programs in the nation; They are loaded with division 1 talent. Their opposition, however, was not.
They played against a team named Bishop Sycamore. There is a lack of information about the team, the school, the players, and their history as a program in general. The team was reportedly just as good as IMG Academy, with "many" division 1 athletes on the roster. However, you can't find a roster online of the team or any information whatsoever.
When the game was broadcasted live on ESPN, there was still no team roster given and the announcers were clueless about the players on the field. That didn't seem to matter however, because they knew IMG Academy's roster. That's all they needed. The final score of the game was 58-0 IMG Academy.
In the following days after the game, more and more information came out regarding both Bishop Sycamore as a school and a football program. It turns out that Bishop Sycamore is an online charter school based in Columbus, Ohio. Information came out that there are several players over the age of 20 and not one of them is a division 1 recruit like the team said.
However, once players started to speak out, the narrative started to shift. Hearing information and stories from players rather than the media seemed to make this story much deeper than just a fake football team. This information was much harder to find than the information previously stated.
Some players have come out to say that despite all of the controversy following their team, they stand with each other 100%. A lot of players have gotten upset with the media because they don't know the full story, there is a lot more behind it than seems. Players have slept on floors and stolen from grocery stores in order to eat. Their ex head coach wrote multiple fraudulent checks to pay for hotel rooms for the team as well.
The common factor between all of the narratives is that the people running the organization have done terrible things. Players stand as a team and as a family; including their ex head coach. These people stand together as a team, against the organization.
I give these players so much credit for doing this, because it's not easy. However, I think the media gives these players a bad reputation like they are all criminals and scums who tried to fake their way into a high level football game. In reality, these are some football players who were promised a chance to play at a high level and sacrificed so much in order to do so.
The Importance of Martin Luther King Jr.
New Year New Variant
Spiderman No Way Home: A Look Into the Hype
NFLWeek 13 Predictions
A Teaching Inspiration – Mark Maxwell
NFL Week 11 Predictions
Lives Lost at Travis Scott's "Astroworld"
RMHS Tennis Wrap-Up
RMHS Soccer Wrap-Up
RMHS Cross Country Wrap Up
The online edition of the award-winning student newspaper at Rolling Meadows High School
Give us your input on stories you would like to see in the paper for upcoming issues!
All The Pacer Picks Reader Picks Sort: Newest


text:
Q: TabLayout without AppCompat? I've got a (working) Android App. I don't care about older versions of Android OS; the app is aimed strictly at the latest versions only.
Recently I decided to add a TabLayout to the App's UI. I was following
https://android.jlelse.eu/tablayout-and-viewpager-in-your-android-app-738b8840c38a
Now I got it working, but one problem is that the tutorial above assumes you're going to extend your Activity from
android.support.v7.app.AppCompatActivity

(rather than the simple android.app.Activity) and keeps using various 'AppCompat' things, like
android.support.v4.app.Fragment
android.support.v4.app.FragmentManager
android.support.v4.app.FragmentPagerAdapter

Now, what is even worse, this forces me to use an 'AppCompat' theme (I've tried a few default ones and all of them look like s**t)
setTheme(R.style.Theme_AppCompat_Light_NoActionBar);

I'd like to add a TabLayout to my app while keeping its Activity extended from android.app.Activity. Is that possible?


text:
Home >Politics >Policy >The present Haryana govt is a non-performing asset: Bhupinder Singh Hooda
With more than a year to go for Haryana elections, former chief minister and Congress leader Bhupinder Singh Hooda has started an expansive campaign in the state focused on the issues of rural distress and unemployment. Photo: Ramesh Pathania/Mint
The present Haryana govt is a non-performing asset: Bhupinder Singh Hooda
5 min read . Updated: 16 Jul 2018, 12:42 AM IST Anuja, Gyan Varma
Former Haryana CM and Congress Bhupinder Singh Hooda on issues faced by farmers and the demand for reservation in government jobs by the Jat community
New Delhi: With a little more than a year to go for assembly elections in Haryana, former chief minister and senior Congress leader Bhupinder Singh Hooda has started an expansive campaign in the state focused on the issues of rural distress and unemployment.
In an interview, the 70-year-old leader spoke about the ongoing campaign, issues faced by farmers and the demand for reservation in government jobs by the Jat community. Edited excerpts:
You have already started an extensive campaign in Haryana including a series of rallies. What is your reason for starting so early and what is the campaign focused on?
It will take a long time to cover the whole of Haryana, actually these are the "Jan Kranti Yatras". When this (state) government was formed by BJP (Bharatiya Janata Party) in 2014, at the time I had said I would wait for one year, we will watch the performance of the government. I had said that if they fulfil what they have promised in their manifesto, then I'll certainly appreciate their work but if they don't perform well, don't fulfil their promise, we will raise those issues.
What happened after one year was that the crop of paddy came, what money they (farmers) were getting during our days they were getting almost half of it. Next, wheat season came and the farmer had to wait for four days at the mandis to get the minimum support price (MSP).
But I don't know what type of policy they (the government) are following neither in the benefit of producers nor consumers. So I started "kisan panchayat" to get feedback—they (farmers) are on the brink of destruction, cost of input has risen, they are not getting the right price.
The cost of production is going high, they are not getting the proper income, so I came to the conclusion that the other section also comprises fairly poor people—labourers are mostly from the scheduled caste.
There is frustration... Unemployment is on the rise. After GST (goods and services tax) and note ban, the small and medium industry has got affected. Thousands of people got unemployed.
The hope which they gave in 2014 in their manifesto, that hope has become hopeless now. So every section of society, whether it is farmer, labour, trader, government servant or old men, all are feeling hopeless.
After holding "kisan panchayat" we conducted "dailt panchayat" and then a traders' conference. After that I reached the conclusion that this time people are fed up with the government, its failure should reach everyone and the policy of our government, the Congress and its achievements should also reach everyone.
For that I have started this "Jan Kranti Yatra" to reach almost every person. That is why it is taking such a long time, it might take six months, eight months to complete. Because my concept is: I go to every district and supposing there are three assembly constituencies, then I spend three days in that district, then I take some other district. Likewise, in a month I take about two districts, that's why I reach everywhere and listen to everyone, else we will just go and have a public meeting.
Have you started your campaign early because there is a possibility of holding Haryana elections along with general elections?
I can't say talks are on; that depends on whether elections of Madhya Pradesh and Rajasthan will be held with the Lok Sabha or not. But talks are going on.
With Manohar Lal Khattar at the top post, after a long time, there is a chief minister in Haryana who is not from a dominant caste as he is a non-Jat…
This is one line of thinking, but caste is not important. This concept was built by people with vested interest. I don't believe in caste politics, a farmer is a farmer, whether it is "A" caste or "B" caste. If a farmer from my community is affected, a farmer from another community will also be affected. Similarly, all traders will be affected, whichever caste they belong to.
For development, if you construct a road, that will be used by all. You can't stick to one caste, it's a myth created by a few. The present Haryana government is not running a government. It is working like an event management company. This government is a non-performing asset. That is why I am getting a good response wherever I go.
Apart from rural distress, what do you think would be the key electoral issues in the next one year before state polls?
They (BJP government) do not have any pro-poor agenda. The only achievement of this government is the projects which were started by me and were 90% completed, they are inaugurating them. They are only a fita-kaatu (ribbon cutters) government. Haryana has gone worse on its law and order situation. This government is completely directionless.
There has been a lot of debate on Jat reservation and Haryana saw a spate of violence on the issue in the last three years. What are your views?
Our policy was perfect to deal with reservation because everybody was given reservation and nobody was left out. We didn't reduce the share in reservation of any community. We gave reservation on the basis of the Gupta Commission report. But the present government in Haryana changed the affidavit, it didn't mention about the Gupta Commission report and failed to represent the state before the Supreme Court. The intent of the government is not right. We wanted to bring together communities but this government is dividing people on caste lines. I was in power for 10 years and there was never the need to call the army, whereas this government has been in power for four years and the army was deployed twice. BJP wants a rift in society and it was the failure of the government that led to the deaths of so many people. The responsibility for the loss of life and property is totally with the government.
Is Congress planning to announce farm loan waiver in Haryana?
Congress has already passed a resolution in AICC (All India Congress Committee) session and I was the chairman of the committee that drafted the resolution. Congress had waived off loans of farmers earlier also. When the party was in power, we had waived off ₹ 72,000 crore by the UPA (United Progressive Alliance) government. We will repeat the resolution on farm loan waiver in Haryana. UPA performed well. It was during UPA when crop loan was reduced to 4%. In Haryana, it was made 0% during the Congress government. We started the process of implementing the Swaminathan Commission report. NDA (National Democratic Alliance) had promised that Swaminathan panel report would be implemented, but it hasn't done so.
Is Congress looking for any alliances with smaller parties in the Haryana polls?
Congress doesn't need help from any regional party. It is strong enough to win elections and form the government on its own. Alliances will be at the national level and can be implemented in the state. A lot will depend on what type of alliance is being worked out.
Aindrila Paul contributed to this story.


text:
package org.ql.views.listview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * 类名称:QLSuperTouchListView

 * 类描述:解决listview与其他滚动view冲突

 * 创建者:anan

 * 创建时间:2013-1-25 上午11:52:29

 * 修改者:anan

 * 修改时间:2013-1-25 上午11:52:29

 * 修改备注:

 *
 * @version
 */
public class QLSuperTouchListView extends QLXListView {
	private int flowViewPosition=-1;

	public QLSuperTouchListView(Context context) {
		super(context);
	}

	public QLSuperTouchListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		setFadingEdgeLength(0);
	}

	public QLSuperTouchListView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public int getFlowViewPosition() {
		return flowViewPosition;
	}

	public void setFlowViewPosition(int flowViewPosition) {
		this.flowViewPosition = flowViewPosition;
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		final int y = (int) ev.getY();
		final int x = (int) ev.getX();
		int position = pointToPosition(x, y);
		if (flowViewPosition!=-1&&position == flowViewPosition) {
				int firstVisablePos = getFirstVisiblePosition();
				View firstView = this.getChildAt(firstVisablePos);
				int bottom = firstView.getBottom();
				if (bottom == firstView.getHeight()) {
					return false;
				} else if (bottom < firstView.getHeight()) {
					smoothScrollToPosition(0);
					return false;
				}
		}
		return super.onInterceptTouchEvent(ev);
	}
}


So it's safe to say that Battle For The Grid will focus on this massive crossover between Power Rangers to save the source of their power. It features simplified controls and a wealth of depth for more experienced players to explore their competitive side.
Support for the mobile OS is ending later this year. For now, this interface change is part of the latest build (18317) for Windows 10 to be tested by insiders as part of the 19H1 development cycle, which is the next major update to Windows 10 planned for April.
Samsung has announced that it will be launching its new Galaxy M series of smartphones in India on January 28. Samsung has been sharpening its focus on India, home to more than a billion wireless subscribers and where roughly 350 million users still do not use smartphones.
Quantum computing rely on a different approach to solving problem, unlike classical computers. While quantum computing is still in its infancy and is mostly just a part of books and research papers, IBM at CES 2019 unveiled the Q System One that is touted to be the world's first quantum computer for commercial use.
Nvidia has announced the launch of its GeForce RTX 2060 graphics card family, new Turing-based RTX-capable laptop models, and partial support for running AMD FreeSync monitors - referred to under their cross-vendor Adaptive Sync terminology - from Nvidia graphics cards.