Search in sources :

Example 36 with AccountVO

use of com.cloud.user.AccountVO in project cloudstack by apache.

the class AccountDaoImpl method findUserAccountByApiKey.

@Override
public Pair<User, Account> findUserAccountByApiKey(String apiKey) {
    TransactionLegacy txn = TransactionLegacy.currentTxn();
    PreparedStatement pstmt = null;
    Pair<User, Account> userAcctPair = null;
    try {
        String sql = FIND_USER_ACCOUNT_BY_API_KEY;
        pstmt = txn.prepareAutoCloseStatement(sql);
        pstmt.setString(1, apiKey);
        ResultSet rs = pstmt.executeQuery();
        // TODO:  make sure we don't have more than 1 result?  ApiKey had better be unique
        if (rs.next()) {
            User u = new UserVO(rs.getLong(1));
            u.setUsername(rs.getString(2));
            u.setAccountId(rs.getLong(3));
            u.setSecretKey(DBEncryptionUtil.decrypt(rs.getString(4)));
            u.setState(State.valueOf(rs.getString(5)));
            AccountVO a = new AccountVO(rs.getLong(6));
            a.setAccountName(rs.getString(7));
            a.setType(rs.getShort(8));
            a.setRoleId(rs.getLong(9));
            a.setDomainId(rs.getLong(10));
            a.setState(State.valueOf(rs.getString(11)));
            userAcctPair = new Pair<User, Account>(u, a);
        }
    } catch (Exception e) {
        s_logger.warn("Exception finding user/acct by api key: " + apiKey, e);
    }
    return userAcctPair;
}
Also used : TransactionLegacy(com.cloud.utils.db.TransactionLegacy) Account(com.cloud.user.Account) User(com.cloud.user.User) UserVO(com.cloud.user.UserVO) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) AccountVO(com.cloud.user.AccountVO)

Example 37 with AccountVO

use of com.cloud.user.AccountVO in project cloudstack by apache.

the class AccountDaoImpl method getDomainIdForGivenAccountId.

@Override
public long getDomainIdForGivenAccountId(long id) {
    long domain_id = -1;
    try {
        AccountVO account_vo = findById(id);
        domain_id = account_vo.getDomainId();
    } catch (Exception e) {
        s_logger.warn("getDomainIdForGivenAccountId: Exception :" + e.getMessage());
    } finally {
        return domain_id;
    }
}
Also used : AccountVO(com.cloud.user.AccountVO)

Example 38 with AccountVO

use of com.cloud.user.AccountVO in project cloudstack by apache.

the class QuotaAlertManagerImpl method checkAndSendQuotaAlertEmails.

@Override
public void checkAndSendQuotaAlertEmails() {
    List<DeferredQuotaEmail> deferredQuotaEmailList = new ArrayList<DeferredQuotaEmail>();
    final BigDecimal zeroBalance = new BigDecimal(0);
    for (final QuotaAccountVO quotaAccount : _quotaAcc.listAllQuotaAccount()) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("checkAndSendQuotaAlertEmails accId=" + quotaAccount.getId());
        }
        BigDecimal accountBalance = quotaAccount.getQuotaBalance();
        Date balanceDate = quotaAccount.getQuotaBalanceDate();
        Date alertDate = quotaAccount.getQuotaAlertDate();
        int lockable = quotaAccount.getQuotaEnforce();
        BigDecimal thresholdBalance = quotaAccount.getQuotaMinBalance();
        if (accountBalance != null) {
            AccountVO account = _accountDao.findById(quotaAccount.getId());
            // the account is removed
            if (account == null)
                continue;
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("checkAndSendQuotaAlertEmails: Check id=" + account.getId() + " bal=" + accountBalance + ", alertDate=" + alertDate + ", lockable=" + lockable);
            }
            if (accountBalance.compareTo(zeroBalance) < 0) {
                if (_lockAccountEnforcement && (lockable == 1)) {
                    if (_quotaManager.isLockable(account)) {
                        s_logger.info("Locking account " + account.getAccountName() + " due to quota < 0.");
                        lockAccount(account.getId());
                    }
                }
                if (alertDate == null || (balanceDate.after(alertDate) && getDifferenceDays(alertDate, new Date()) > 1)) {
                    s_logger.info("Sending alert " + account.getAccountName() + " due to quota < 0.");
                    deferredQuotaEmailList.add(new DeferredQuotaEmail(account, quotaAccount, QuotaConfig.QuotaEmailTemplateTypes.QUOTA_EMPTY));
                }
            } else if (accountBalance.compareTo(thresholdBalance) < 0) {
                if (alertDate == null || (balanceDate.after(alertDate) && getDifferenceDays(alertDate, new Date()) > 1)) {
                    s_logger.info("Sending alert " + account.getAccountName() + " due to quota below threshold.");
                    deferredQuotaEmailList.add(new DeferredQuotaEmail(account, quotaAccount, QuotaConfig.QuotaEmailTemplateTypes.QUOTA_LOW));
                }
            }
        }
    }
    for (DeferredQuotaEmail emailToBeSent : deferredQuotaEmailList) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("checkAndSendQuotaAlertEmails: Attempting to send quota alert email to users of account: " + emailToBeSent.getAccount().getAccountName());
        }
        sendQuotaAlert(emailToBeSent);
    }
}
Also used : ArrayList(java.util.ArrayList) QuotaAccountVO(org.apache.cloudstack.quota.vo.QuotaAccountVO) QuotaAccountVO(org.apache.cloudstack.quota.vo.QuotaAccountVO) AccountVO(com.cloud.user.AccountVO) BigDecimal(java.math.BigDecimal) Date(java.util.Date)

Example 39 with AccountVO

use of com.cloud.user.AccountVO in project cloudstack by apache.

the class QuotaAlertManagerImpl method sendQuotaAlert.

public void sendQuotaAlert(DeferredQuotaEmail emailToBeSent) {
    final AccountVO account = emailToBeSent.getAccount();
    final BigDecimal balance = emailToBeSent.getQuotaBalance();
    final BigDecimal usage = emailToBeSent.getQuotaUsage();
    final QuotaConfig.QuotaEmailTemplateTypes emailType = emailToBeSent.getEmailTemplateType();
    final List<QuotaEmailTemplatesVO> emailTemplates = _quotaEmailTemplateDao.listAllQuotaEmailTemplates(emailType.toString());
    if (emailTemplates != null && emailTemplates.get(0) != null) {
        final QuotaEmailTemplatesVO emailTemplate = emailTemplates.get(0);
        final DomainVO accountDomain = _domainDao.findByIdIncludingRemoved(account.getDomainId());
        final List<UserVO> usersInAccount = _userDao.listByAccount(account.getId());
        String userNames = "";
        final List<String> emailRecipients = new ArrayList<String>();
        for (UserVO user : usersInAccount) {
            userNames += String.format("%s <%s>,", user.getUsername(), user.getEmail());
            emailRecipients.add(user.getEmail());
        }
        if (userNames.endsWith(",")) {
            userNames = userNames.substring(0, userNames.length() - 1);
        }
        final Map<String, String> optionMap = new HashMap<String, String>();
        optionMap.put("accountName", account.getAccountName());
        optionMap.put("accountID", account.getUuid());
        optionMap.put("accountUsers", userNames);
        optionMap.put("domainName", accountDomain.getName());
        optionMap.put("domainID", accountDomain.getUuid());
        optionMap.put("quotaBalance", QuotaConfig.QuotaCurrencySymbol.value() + " " + balance.toString());
        if (emailType == QuotaEmailTemplateTypes.QUOTA_STATEMENT) {
            optionMap.put("quotaUsage", QuotaConfig.QuotaCurrencySymbol.value() + " " + usage.toString());
        }
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("accountName" + account.getAccountName() + "accountID" + account.getUuid() + "accountUsers" + userNames + "domainName" + accountDomain.getName() + "domainID" + accountDomain.getUuid());
        }
        final StrSubstitutor templateEngine = new StrSubstitutor(optionMap);
        final String subject = templateEngine.replace(emailTemplate.getTemplateSubject());
        final String body = templateEngine.replace(emailTemplate.getTemplateBody());
        try {
            _emailQuotaAlert.sendQuotaAlert(emailRecipients, subject, body);
            emailToBeSent.sentSuccessfully(_quotaAcc);
        } catch (Exception e) {
            s_logger.error(String.format("Unable to send quota alert email (subject=%s; body=%s) to account %s (%s) recipients (%s) due to error (%s)", subject, body, account.getAccountName(), account.getUuid(), emailRecipients, e));
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Exception", e);
            }
        }
    } else {
        s_logger.error(String.format("No quota email template found for type %s, cannot send quota alert email to account %s(%s)", emailType, account.getAccountName(), account.getUuid()));
    }
}
Also used : QuotaEmailTemplatesVO(org.apache.cloudstack.quota.vo.QuotaEmailTemplatesVO) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) QuotaEmailTemplateTypes(org.apache.cloudstack.quota.constant.QuotaConfig.QuotaEmailTemplateTypes) QuotaAccountVO(org.apache.cloudstack.quota.vo.QuotaAccountVO) AccountVO(com.cloud.user.AccountVO) BigDecimal(java.math.BigDecimal) MessagingException(javax.mail.MessagingException) ConfigurationException(javax.naming.ConfigurationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DomainVO(com.cloud.domain.DomainVO) StrSubstitutor(org.apache.commons.lang3.text.StrSubstitutor) UserVO(com.cloud.user.UserVO) QuotaConfig(org.apache.cloudstack.quota.constant.QuotaConfig)

Example 40 with AccountVO

use of com.cloud.user.AccountVO in project cloudstack by apache.

the class QuotaAlertManagerImpl method lockAccount.

protected boolean lockAccount(long accountId) {
    final short opendb = TransactionLegacy.currentTxn().getDatabaseId();
    boolean success = false;
    try (TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB)) {
        Account account = _accountDao.findById(accountId);
        if (account != null) {
            if (account.getState() == State.locked) {
                // already locked, no-op
                return true;
            } else if (account.getState() == State.enabled) {
                AccountVO acctForUpdate = _accountDao.createForUpdate();
                acctForUpdate.setState(State.locked);
                success = _accountDao.update(Long.valueOf(accountId), acctForUpdate);
            } else {
                if (s_logger.isInfoEnabled()) {
                    s_logger.info("Attempting to lock a non-enabled account, current state is " + account.getState() + " (accountId: " + accountId + "), locking failed.");
                }
            }
        } else {
            s_logger.warn("Failed to lock account " + accountId + ", account not found.");
        }
    } catch (Exception e) {
        s_logger.error("Exception occured while locking account by Quota Alert Manager", e);
        throw e;
    } finally {
        TransactionLegacy.open(opendb).close();
    }
    return success;
}
Also used : TransactionLegacy(com.cloud.utils.db.TransactionLegacy) Account(com.cloud.user.Account) QuotaAccountVO(org.apache.cloudstack.quota.vo.QuotaAccountVO) AccountVO(com.cloud.user.AccountVO) MessagingException(javax.mail.MessagingException) ConfigurationException(javax.naming.ConfigurationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Aggregations

AccountVO (com.cloud.user.AccountVO)139 Account (com.cloud.user.Account)65 Test (org.junit.Test)52 UserVO (com.cloud.user.UserVO)44 Field (java.lang.reflect.Field)41 ArrayList (java.util.ArrayList)40 DomainVO (com.cloud.domain.DomainVO)32 AccountManager (com.cloud.user.AccountManager)27 Before (org.junit.Before)22 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)21 TransactionLegacy (com.cloud.utils.db.TransactionLegacy)21 Date (java.util.Date)16 QuotaAccountVO (org.apache.cloudstack.quota.vo.QuotaAccountVO)16 DomainDao (com.cloud.domain.dao.DomainDao)14 SslCertDao (com.cloud.network.dao.SslCertDao)14 AgentManager (com.cloud.agent.AgentManager)13 IPAddressDao (com.cloud.network.dao.IPAddressDao)13 LoadBalancerDao (com.cloud.network.dao.LoadBalancerDao)13 NetworkDao (com.cloud.network.dao.NetworkDao)13 NetworkVO (com.cloud.network.dao.NetworkVO)13