Search in sources :

Example 1 with QuotaBalanceVO

use of org.apache.cloudstack.quota.vo.QuotaBalanceVO in project cloudstack by apache.

the class QuotaServiceImpl method findQuotaBalanceVO.

@Override
public List<QuotaBalanceVO> findQuotaBalanceVO(Long accountId, String accountName, Long domainId, Date startDate, Date endDate) {
    if ((accountId == null) && (accountName != null) && (domainId != null)) {
        Account userAccount = null;
        Account caller = CallContext.current().getCallingAccount();
        if (_domainDao.isChildDomain(caller.getDomainId(), domainId)) {
            Filter filter = new Filter(AccountVO.class, "id", Boolean.FALSE, null, null);
            List<AccountVO> accounts = _accountDao.listAccounts(accountName, domainId, filter);
            if (!accounts.isEmpty()) {
                userAccount = accounts.get(0);
            }
            if (userAccount != null) {
                accountId = userAccount.getId();
            } else {
                throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId);
            }
        } else {
            throw new PermissionDeniedException("Invalid Domain Id or Account");
        }
    }
    startDate = startDate == null ? new Date() : startDate;
    if (endDate == null) {
        // adjust start date to end of day as there is no end date
        Date adjustedStartDate = computeAdjustedTime(_respBldr.startOfNextDay(startDate));
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("getQuotaBalance1: Getting quota balance records for account: " + accountId + ", domainId: " + domainId + ", on or before " + adjustedStartDate);
        }
        List<QuotaBalanceVO> qbrecords = _quotaBalanceDao.lastQuotaBalanceVO(accountId, domainId, adjustedStartDate);
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Found records size=" + qbrecords.size());
        }
        if (qbrecords.isEmpty()) {
            s_logger.info("Incorrect Date there are no quota records before this date " + adjustedStartDate);
            return qbrecords;
        } else {
            return qbrecords;
        }
    } else {
        Date adjustedStartDate = computeAdjustedTime(startDate);
        if (endDate.after(_respBldr.startOfNextDay())) {
            throw new InvalidParameterValueException("Incorrect Date Range. End date:" + endDate + " should not be in future. ");
        } else if (startDate.before(endDate)) {
            Date adjustedEndDate = computeAdjustedTime(endDate);
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("getQuotaBalance2: Getting quota balance records for account: " + accountId + ", domainId: " + domainId + ", between " + adjustedStartDate + " and " + adjustedEndDate);
            }
            List<QuotaBalanceVO> qbrecords = _quotaBalanceDao.findQuotaBalance(accountId, domainId, adjustedStartDate, adjustedEndDate);
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("getQuotaBalance3: Found records size=" + qbrecords.size());
            }
            if (qbrecords.isEmpty()) {
                s_logger.info("There are no quota records between these dates start date " + adjustedStartDate + " and end date:" + endDate);
                return qbrecords;
            } else {
                return qbrecords;
            }
        } else {
            throw new InvalidParameterValueException("Incorrect Date Range. Start date: " + startDate + " is after end date:" + endDate);
        }
    }
}
Also used : Account(com.cloud.user.Account) Filter(com.cloud.utils.db.Filter) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) QuotaBalanceVO(org.apache.cloudstack.quota.vo.QuotaBalanceVO) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ArrayList(java.util.ArrayList) List(java.util.List) QuotaAccountVO(org.apache.cloudstack.quota.vo.QuotaAccountVO) AccountVO(com.cloud.user.AccountVO) Date(java.util.Date)

Example 2 with QuotaBalanceVO

use of org.apache.cloudstack.quota.vo.QuotaBalanceVO in project cloudstack by apache.

the class QuotaBalanceCmdTest method testQuotaBalanceCmd.

@Test
public void testQuotaBalanceCmd() throws NoSuchFieldException, IllegalAccessException {
    QuotaBalanceCmd cmd = new QuotaBalanceCmd();
    Field rbField = QuotaBalanceCmd.class.getDeclaredField("_responseBuilder");
    rbField.setAccessible(true);
    rbField.set(cmd, responseBuilder);
    List<QuotaBalanceVO> quotaBalanceVOList = new ArrayList<QuotaBalanceVO>();
    Mockito.when(responseBuilder.getQuotaBalance(Mockito.any(cmd.getClass()))).thenReturn(quotaBalanceVOList);
    Mockito.when(responseBuilder.createQuotaLastBalanceResponse(Mockito.eq(quotaBalanceVOList), Mockito.any(Date.class))).thenReturn(new QuotaBalanceResponse());
    Mockito.when(responseBuilder.createQuotaBalanceResponse(Mockito.eq(quotaBalanceVOList), Mockito.any(Date.class), Mockito.any(Date.class))).thenReturn(new QuotaBalanceResponse());
    Mockito.when(responseBuilder.startOfNextDay(Mockito.any(Date.class))).thenReturn(new Date());
    // end date not specified
    cmd.setStartDate(new Date());
    cmd.setEndDate(null);
    cmd.execute();
    Mockito.verify(responseBuilder, Mockito.times(1)).createQuotaLastBalanceResponse(Mockito.eq(quotaBalanceVOList), Mockito.any(Date.class));
    Mockito.verify(responseBuilder, Mockito.times(0)).createQuotaBalanceResponse(Mockito.eq(quotaBalanceVOList), Mockito.any(Date.class), Mockito.any(Date.class));
    // end date specified
    cmd.setEndDate(new Date());
    cmd.execute();
    Mockito.verify(responseBuilder, Mockito.times(1)).createQuotaBalanceResponse(Mockito.eq(quotaBalanceVOList), Mockito.any(Date.class), Mockito.any(Date.class));
}
Also used : Field(java.lang.reflect.Field) QuotaBalanceResponse(org.apache.cloudstack.api.response.QuotaBalanceResponse) ArrayList(java.util.ArrayList) QuotaBalanceVO(org.apache.cloudstack.quota.vo.QuotaBalanceVO) Date(java.util.Date) Test(org.junit.Test)

Example 3 with QuotaBalanceVO

use of org.apache.cloudstack.quota.vo.QuotaBalanceVO in project cloudstack by apache.

the class QuotaResponseBuilderImpl method addQuotaCredits.

@Override
public QuotaCreditsResponse addQuotaCredits(Long accountId, Long domainId, Double amount, Long updatedBy, Boolean enforce) {
    Date despositedOn = _quotaService.computeAdjustedTime(new Date());
    QuotaBalanceVO qb = _quotaBalanceDao.findLaterBalanceEntry(accountId, domainId, despositedOn);
    if (qb != null) {
        throw new InvalidParameterValueException("Incorrect deposit date: " + despositedOn + " there are balance entries after this date");
    }
    QuotaCreditsVO credits = new QuotaCreditsVO(accountId, domainId, new BigDecimal(amount), updatedBy);
    credits.setUpdatedOn(despositedOn);
    QuotaCreditsVO result = _quotaCreditsDao.saveCredits(credits);
    final AccountVO account = _accountDao.findById(accountId);
    if (account == null) {
        throw new InvalidParameterValueException("Account does not exist with account id " + accountId);
    }
    final boolean lockAccountEnforcement = "true".equalsIgnoreCase(QuotaConfig.QuotaEnableEnforcement.value());
    final BigDecimal currentAccountBalance = _quotaBalanceDao.lastQuotaBalance(accountId, domainId, startOfNextDay(new Date(despositedOn.getTime())));
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("AddQuotaCredits: Depositing " + amount + " on adjusted date " + despositedOn + ", current balance " + currentAccountBalance);
    }
    // update quota account with the balance
    _quotaService.saveQuotaAccount(account, currentAccountBalance, despositedOn);
    if (lockAccountEnforcement) {
        if (currentAccountBalance.compareTo(new BigDecimal(0)) >= 0) {
            if (account.getState() == Account.State.locked) {
                s_logger.info("UnLocking account " + account.getAccountName() + " , due to positive balance " + currentAccountBalance);
                _accountMgr.enableAccount(account.getAccountName(), domainId, accountId);
            }
        } else {
            // currentAccountBalance < 0 then lock the account
            if (_quotaManager.isLockable(account) && account.getState() == Account.State.enabled && enforce) {
                s_logger.info("Locking account " + account.getAccountName() + " , due to negative balance " + currentAccountBalance);
                _accountMgr.lockAccount(account.getAccountName(), domainId, accountId);
            }
        }
    }
    String creditor = String.valueOf(Account.ACCOUNT_ID_SYSTEM);
    User creditorUser = _userDao.getUser(updatedBy);
    if (creditorUser != null) {
        creditor = creditorUser.getUsername();
    }
    QuotaCreditsResponse response = new QuotaCreditsResponse(result, creditor);
    response.setCurrency(QuotaConfig.QuotaCurrencySymbol.value());
    return response;
}
Also used : User(com.cloud.user.User) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) QuotaBalanceVO(org.apache.cloudstack.quota.vo.QuotaBalanceVO) QuotaCreditsVO(org.apache.cloudstack.quota.vo.QuotaCreditsVO) QuotaAccountVO(org.apache.cloudstack.quota.vo.QuotaAccountVO) AccountVO(com.cloud.user.AccountVO) Date(java.util.Date) BigDecimal(java.math.BigDecimal)

Example 4 with QuotaBalanceVO

use of org.apache.cloudstack.quota.vo.QuotaBalanceVO in project cloudstack by apache.

the class QuotaResponseBuilderImpl method createQuotaBalanceResponse.

@Override
public QuotaBalanceResponse createQuotaBalanceResponse(List<QuotaBalanceVO> quotaBalance, Date startDate, Date endDate) {
    if (quotaBalance == null || quotaBalance.isEmpty()) {
        throw new InvalidParameterValueException("The request period does not contain balance entries.");
    }
    Collections.sort(quotaBalance, new Comparator<QuotaBalanceVO>() {

        public int compare(QuotaBalanceVO o1, QuotaBalanceVO o2) {
            o1 = o1 == null ? new QuotaBalanceVO() : o1;
            o2 = o2 == null ? new QuotaBalanceVO() : o2;
            // desc
            return o2.getUpdatedOn().compareTo(o1.getUpdatedOn());
        }
    });
    boolean have_balance_entries = false;
    //check that there is at least one balance entry
    for (Iterator<QuotaBalanceVO> it = quotaBalance.iterator(); it.hasNext(); ) {
        QuotaBalanceVO entry = it.next();
        if (entry.isBalanceEntry()) {
            have_balance_entries = true;
            break;
        }
    }
    //accounted for in the starting balance after that entry, note the sort is desc
    if (have_balance_entries) {
        ListIterator<QuotaBalanceVO> li = quotaBalance.listIterator(quotaBalance.size());
        // Iterate in reverse.
        while (li.hasPrevious()) {
            QuotaBalanceVO entry = li.previous();
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("createQuotaBalanceResponse: Entry=" + entry);
            }
            if (entry.getCreditsId() > 0) {
                li.remove();
            } else {
                break;
            }
        }
    }
    int quota_activity = quotaBalance.size();
    QuotaBalanceResponse resp = new QuotaBalanceResponse();
    BigDecimal lastCredits = new BigDecimal(0);
    boolean consecutive = true;
    for (Iterator<QuotaBalanceVO> it = quotaBalance.iterator(); it.hasNext(); ) {
        QuotaBalanceVO entry = it.next();
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("createQuotaBalanceResponse: All Credit Entry=" + entry);
        }
        if (entry.getCreditsId() > 0) {
            if (consecutive) {
                lastCredits = lastCredits.add(entry.getCreditBalance());
            }
            resp.addCredits(entry);
            it.remove();
        } else {
            consecutive = false;
        }
    }
    if (quota_activity > 0 && quotaBalance.size() > 0) {
        // order is desc last item is the start item
        QuotaBalanceVO startItem = quotaBalance.get(quotaBalance.size() - 1);
        QuotaBalanceVO endItem = quotaBalance.get(0);
        resp.setStartDate(startDate);
        resp.setStartQuota(startItem.getCreditBalance());
        resp.setEndDate(endDate);
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("createQuotaBalanceResponse: Start Entry=" + startItem);
            s_logger.debug("createQuotaBalanceResponse: End Entry=" + endItem);
        }
        resp.setEndQuota(endItem.getCreditBalance().add(lastCredits));
    } else if (quota_activity > 0) {
        // order is desc last item is the start item
        resp.setStartDate(startDate);
        resp.setStartQuota(new BigDecimal(0));
        resp.setEndDate(endDate);
        resp.setEndQuota(new BigDecimal(0).add(lastCredits));
    } else {
        resp.setStartDate(startDate);
        resp.setEndDate(endDate);
        resp.setStartQuota(new BigDecimal(0));
        resp.setEndQuota(new BigDecimal(0));
    }
    resp.setCurrency(QuotaConfig.QuotaCurrencySymbol.value());
    resp.setObjectName("balance");
    return resp;
}
Also used : InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) QuotaBalanceVO(org.apache.cloudstack.quota.vo.QuotaBalanceVO) BigDecimal(java.math.BigDecimal)

Example 5 with QuotaBalanceVO

use of org.apache.cloudstack.quota.vo.QuotaBalanceVO in project cloudstack by apache.

the class QuotaBalanceCmd method execute.

@Override
public void execute() {
    List<QuotaBalanceVO> quotaUsage = _responseBuilder.getQuotaBalance(this);
    QuotaBalanceResponse response;
    if (endDate == null) {
        response = _responseBuilder.createQuotaLastBalanceResponse(quotaUsage, getStartDate());
    } else {
        response = _responseBuilder.createQuotaBalanceResponse(quotaUsage, getStartDate(), new Date(endDate.getTime()));
    }
    response.setResponseName(getCommandName());
    setResponseObject(response);
}
Also used : QuotaBalanceResponse(org.apache.cloudstack.api.response.QuotaBalanceResponse) QuotaBalanceVO(org.apache.cloudstack.quota.vo.QuotaBalanceVO) Date(java.util.Date)

Aggregations

QuotaBalanceVO (org.apache.cloudstack.quota.vo.QuotaBalanceVO)11 BigDecimal (java.math.BigDecimal)8 Date (java.util.Date)8 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)5 ArrayList (java.util.ArrayList)4 Test (org.junit.Test)3 AccountVO (com.cloud.user.AccountVO)2 QuotaBalanceResponse (org.apache.cloudstack.api.response.QuotaBalanceResponse)2 QuotaAccountVO (org.apache.cloudstack.quota.vo.QuotaAccountVO)2 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)1 Account (com.cloud.user.Account)1 User (com.cloud.user.User)1 Filter (com.cloud.utils.db.Filter)1 Field (java.lang.reflect.Field)1 List (java.util.List)1 QuotaCreditsVO (org.apache.cloudstack.quota.vo.QuotaCreditsVO)1 QuotaUsageVO (org.apache.cloudstack.quota.vo.QuotaUsageVO)1 DateTime (org.joda.time.DateTime)1