@Override
  public void deployVirtualMachine(
      String reservationId, String caller, Map<VirtualMachineProfile.Param, Object> params)
      throws InsufficientCapacityException, ResourceUnavailableException {
    // grab the VM Id and destination using the reservationId.

    VMReservationVO vmReservation = _reservationDao.findByReservationId(reservationId);
    long vmId = vmReservation.getVmId();

    VMInstanceVO vm = _vmDao.findById(vmId);
    // Pass it down
    Long poolId = null;
    Map<Long, Long> storage = vmReservation.getVolumeReservation();
    if (storage != null) {
      List<Long> volIdList = new ArrayList<Long>(storage.keySet());
      if (volIdList != null && !volIdList.isEmpty()) {
        poolId = storage.get(volIdList.get(0));
      }
    }

    DataCenterDeployment reservedPlan =
        new DataCenterDeployment(
            vm.getDataCenterId(),
            vmReservation.getPodId(),
            vmReservation.getClusterId(),
            vmReservation.getHostId(),
            null,
            null);
    try {
      VMInstanceVO vmDeployed =
          _itMgr.start(
              vm,
              params,
              _userDao.findById(new Long(caller)),
              _accountDao.findById(vm.getAccountId()),
              reservedPlan);
    } catch (Exception ex) {
      // Retry the deployment without using the reservation plan
      DataCenterDeployment plan =
          new DataCenterDeployment(vm.getDataCenterId(), null, null, null, null, null);
      _itMgr.start(
          vm,
          params,
          _userDao.findById(new Long(caller)),
          _accountDao.findById(vm.getAccountId()),
          plan);
    }
  }
  public TemplateProfile prepareDelete(DeleteTemplateCmd cmd) {
    Long templateId = cmd.getId();
    Long userId = UserContext.current().getCallerUserId();
    Account account = UserContext.current().getCaller();
    Long zoneId = cmd.getZoneId();

    VMTemplateVO template = _tmpltDao.findById(templateId.longValue());
    if (template == null) {
      throw new InvalidParameterValueException("unable to find template with id " + templateId);
    }

    userId =
        accountAndUserValidation(account, userId, null, template, "Unable to delete template ");

    UserVO user = _userDao.findById(userId);
    if (user == null) {
      throw new InvalidParameterValueException("Please specify a valid user.");
    }

    if (template.getFormat() == ImageFormat.ISO) {
      throw new InvalidParameterValueException("Please specify a valid template.");
    }

    return new TemplateProfile(userId, template, zoneId);
  }
  @Override
  public boolean destroyVirtualMachine(VMEntityVO vmEntityVO, String caller)
      throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException {

    VMInstanceVO vm = _vmDao.findByUuid(vmEntityVO.getUuid());
    return _itMgr.destroy(
        vm, _userDao.findById(new Long(caller)), _accountDao.findById(vm.getAccountId()));
  }
  @Override
  public boolean stopvirtualmachine(VMEntityVO vmEntityVO, String caller)
      throws ResourceUnavailableException {

    VMInstanceVO vm = _vmDao.findByUuid(vmEntityVO.getUuid());
    return _itMgr.stop(
        vm, _userDao.findById(new Long(caller)), _accountDao.findById(vm.getAccountId()));
  }
 @Bean
 public EntityManager entityManager() {
   EntityManager mock = Mockito.mock(EntityManager.class);
   try {
     Mockito.when(mock.findById(Matchers.same(Account.class), Matchers.anyLong()))
         .thenReturn(_accountDao.findById(Account.ACCOUNT_ID_SYSTEM));
     Mockito.when(mock.findById(Matchers.same(User.class), Matchers.anyLong()))
         .thenReturn(_userDao.findById(User.UID_SYSTEM));
     Mockito.when(mock.findById(Matchers.same(NetworkOffering.class), Matchers.any(Long.class)))
         .thenAnswer(
             new Answer<NetworkOffering>() {
               @Override
               public NetworkOffering answer(final InvocationOnMock invocation) throws Throwable {
                 Long id = (Long) invocation.getArguments()[1];
                 return _networkOfferingDao.findById(id);
               }
             });
     Mockito.when(mock.findById(Matchers.same(IpAddress.class), Matchers.any(Long.class)))
         .thenAnswer(
             new Answer<IpAddress>() {
               @Override
               public IpAddress answer(final InvocationOnMock invocation) throws Throwable {
                 Long id = (Long) invocation.getArguments()[1];
                 return _ipAddressDao.findById(id);
               }
             });
     Mockito.when(mock.findById(Matchers.same(DataCenter.class), Matchers.any(Long.class)))
         .thenAnswer(
             new Answer<DataCenter>() {
               @Override
               public DataCenter answer(final InvocationOnMock invocation) throws Throwable {
                 Long id = (Long) invocation.getArguments()[1];
                 return _zoneDao.findById(id);
               }
             });
   } catch (Exception e) {
     e.printStackTrace();
   }
   CallContext.init(mock);
   return mock;
 }
  public TemplateProfile prepare(
      boolean isIso,
      Long userId,
      String name,
      String displayText,
      Integer bits,
      Boolean passwordEnabled,
      Boolean requiresHVM,
      String url,
      Boolean isPublic,
      Boolean featured,
      Boolean isExtractable,
      String format,
      Long guestOSId,
      Long zoneId,
      HypervisorType hypervisorType,
      String chksum,
      Boolean bootable,
      String templateTag,
      Account templateOwner,
      Map details)
      throws ResourceAllocationException {
    // Long accountId = null;
    // parameters verification

    if (isPublic == null) {
      isPublic = Boolean.FALSE;
    }

    if (zoneId.longValue() == -1) {
      zoneId = null;
    }

    if (isIso) {
      if (bootable == null) {
        bootable = Boolean.TRUE;
      }
      GuestOS noneGuestOs = ApiDBUtils.findGuestOSByDisplayName(ApiConstants.ISO_GUEST_OS_NONE);
      if ((guestOSId == null || guestOSId == noneGuestOs.getId()) && bootable == true) {
        throw new InvalidParameterValueException("Please pass a valid GuestOS Id");
      }
      if (bootable == false) {
        guestOSId = noneGuestOs.getId(); // Guest os id of None.
      }
    } else {
      if (bits == null) {
        bits = Integer.valueOf(64);
      }
      if (passwordEnabled == null) {
        passwordEnabled = false;
      }
      if (requiresHVM == null) {
        requiresHVM = true;
      }
    }

    if (isExtractable == null) {
      isExtractable = Boolean.FALSE;
    }

    boolean isAdmin =
        _accountDao.findById(templateOwner.getId()).getType() == Account.ACCOUNT_TYPE_ADMIN;

    if (!isAdmin && zoneId == null) {
      throw new InvalidParameterValueException("Please specify a valid zone Id.");
    }

    if (url.toLowerCase().contains("file://")) {
      throw new InvalidParameterValueException("File:// type urls are currently unsupported");
    }

    boolean allowPublicUserTemplates =
        Boolean.parseBoolean(_configDao.getValue("allow.public.user.templates"));
    if (!isAdmin && !allowPublicUserTemplates && isPublic) {
      throw new InvalidParameterValueException("Only private templates/ISO can be created.");
    }

    if (!isAdmin || featured == null) {
      featured = Boolean.FALSE;
    }

    // If command is executed via 8096 port, set userId to the id of System
    // account (1)
    if (userId == null) {
      userId = Long.valueOf(1);
    }

    ImageFormat imgfmt = ImageFormat.valueOf(format.toUpperCase());
    if (imgfmt == null) {
      throw new IllegalArgumentException(
          "Image format is incorrect "
              + format
              + ". Supported formats are "
              + EnumUtils.listValues(ImageFormat.values()));
    }

    // Check that the resource limit for templates/ISOs won't be exceeded
    UserVO user = _userDao.findById(userId);
    if (user == null) {
      throw new IllegalArgumentException("Unable to find user with id " + userId);
    }

    _resourceLimitMgr.checkResourceLimit(templateOwner, ResourceType.template);

    if (templateOwner.getType() != Account.ACCOUNT_TYPE_ADMIN && zoneId == null) {
      throw new IllegalArgumentException("Only admins can create templates in all zones");
    }

    // If a zoneId is specified, make sure it is valid
    if (zoneId != null) {
      DataCenterVO zone = _dcDao.findById(zoneId);
      if (zone == null) {
        throw new IllegalArgumentException("Please specify a valid zone.");
      }
      Account caller = UserContext.current().getCaller();
      if (Grouping.AllocationState.Disabled == zone.getAllocationState()
          && !_accountMgr.isRootAdmin(caller.getType())) {
        throw new PermissionDeniedException(
            "Cannot perform this operation, Zone is currently disabled: " + zoneId);
      }
    }

    List<VMTemplateVO> systemvmTmplts = _tmpltDao.listAllSystemVMTemplates();
    for (VMTemplateVO template : systemvmTmplts) {
      if (template.getName().equalsIgnoreCase(name)
          || template.getDisplayText().equalsIgnoreCase(displayText)) {
        throw new IllegalArgumentException("Cannot use reserved names for templates");
      }
    }

    Long id = _tmpltDao.getNextInSequence(Long.class, "id");
    UserContext.current().setEventDetails("Id: " + id + " name: " + name);
    return new TemplateProfile(
        id,
        userId,
        name,
        displayText,
        bits,
        passwordEnabled,
        requiresHVM,
        url,
        isPublic,
        featured,
        isExtractable,
        imgfmt,
        guestOSId,
        zoneId,
        hypervisorType,
        templateOwner.getAccountName(),
        templateOwner.getDomainId(),
        templateOwner.getAccountId(),
        chksum,
        bootable,
        templateTag,
        details);
  }