Search in sources :

Example 31 with DomainVO

use of com.cloud.domain.DomainVO in project cloudstack by apache.

the class ServerEventHandlerImpl method onDomainCreate.

public void onDomainCreate(String subject, String topic, org.apache.cloudstack.framework.events.Event event) {
    s_logger.info("onDomainCreate; topic: " + topic + "; subject: " + subject);
    try {
        long id = parseForId(event.getResourceType(), event.getDescription());
        if (id != 0) {
            DomainVO domain = _domainDao.findById(id);
            if (domain != null) {
                s_logger.info("createDomain for name: " + domain.getName() + "; uuid: " + domain.getUuid());
                StringBuffer logMesg = new StringBuffer();
                _dbSync.createDomain(domain, logMesg);
            } else {
                /* could not find db record, resync complete class */
                _dbSync.syncClass(net.juniper.contrail.api.types.Domain.class);
            }
        } else {
            /* Unknown id, resync complete class */
            _dbSync.syncClass(net.juniper.contrail.api.types.Domain.class);
        }
    } catch (Exception e) {
        s_logger.debug(e);
    }
}
Also used : DomainVO(com.cloud.domain.DomainVO)

Example 32 with DomainVO

use of com.cloud.domain.DomainVO in project cloudstack by apache.

the class ListAndSwitchSAMLAccountCmdTest method testListAndSwitchSAMLAccountCmd.

@Test
public void testListAndSwitchSAMLAccountCmd() throws Exception {
    // Setup
    final Map<String, Object[]> params = new HashMap<String, Object[]>();
    final String sessionKeyValue = "someSessionIDValue";
    Mockito.when(session.getAttribute(ApiConstants.SESSIONKEY)).thenReturn(sessionKeyValue);
    Mockito.when(session.getAttribute("userid")).thenReturn(2L);
    params.put(ApiConstants.USER_ID, new String[] { "2" });
    params.put(ApiConstants.DOMAIN_ID, new String[] { "1" });
    Mockito.when(userDao.findByUuid(anyString())).thenReturn(new UserVO(2L));
    Mockito.when(domainDao.findByUuid(anyString())).thenReturn(new DomainVO());
    // Mock/field setup
    ListAndSwitchSAMLAccountCmd cmd = new ListAndSwitchSAMLAccountCmd();
    Field apiServerField = ListAndSwitchSAMLAccountCmd.class.getDeclaredField("_apiServer");
    apiServerField.setAccessible(true);
    apiServerField.set(cmd, apiServer);
    Field managerField = ListAndSwitchSAMLAccountCmd.class.getDeclaredField("_samlAuthManager");
    managerField.setAccessible(true);
    managerField.set(cmd, samlAuthManager);
    Field accountServiceField = BaseCmd.class.getDeclaredField("_accountService");
    accountServiceField.setAccessible(true);
    accountServiceField.set(cmd, accountService);
    Field userAccountDaoField = ListAndSwitchSAMLAccountCmd.class.getDeclaredField("_userAccountDao");
    userAccountDaoField.setAccessible(true);
    userAccountDaoField.set(cmd, userAccountDao);
    Field userDaoField = ListAndSwitchSAMLAccountCmd.class.getDeclaredField("_userDao");
    userDaoField.setAccessible(true);
    userDaoField.set(cmd, userDao);
    Field domainDaoField = ListAndSwitchSAMLAccountCmd.class.getDeclaredField("_domainDao");
    domainDaoField.setAccessible(true);
    domainDaoField.set(cmd, domainDao);
    // invalid session test
    try {
        cmd.authenticate("command", params, null, null, HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
    } catch (ServerApiException exception) {
        assertEquals(exception.getErrorCode(), ApiErrorCode.UNAUTHORIZED);
    } finally {
        Mockito.verify(accountService, Mockito.times(0)).getUserAccountById(Mockito.anyLong());
    }
    // invalid sessionkey value test
    params.put(ApiConstants.SESSIONKEY, new String[] { "someOtherValue" });
    try {
        Mockito.when(session.isNew()).thenReturn(false);
        cmd.authenticate("command", params, session, null, HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
    } catch (ServerApiException exception) {
        assertEquals(exception.getErrorCode(), ApiErrorCode.UNAUTHORIZED);
    } finally {
        Mockito.verify(accountService, Mockito.times(0)).getUserAccountById(Mockito.anyLong());
    }
    // valid sessionkey value test
    params.put(ApiConstants.SESSIONKEY, new String[] { sessionKeyValue });
    try {
        cmd.authenticate("command", params, session, null, HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
    } catch (ServerApiException exception) {
        assertEquals(exception.getErrorCode(), ApiErrorCode.ACCOUNT_ERROR);
    } finally {
        Mockito.verify(accountService, Mockito.times(1)).getUserAccountById(Mockito.anyLong());
    }
    // valid sessionkey, invalid useraccount type (non-saml) value test
    UserAccountVO mockedUserAccount = new UserAccountVO();
    mockedUserAccount.setId(2L);
    mockedUserAccount.setAccountState(Account.State.enabled.toString());
    mockedUserAccount.setUsername("someUsername");
    mockedUserAccount.setExternalEntity("some IDP ID");
    mockedUserAccount.setDomainId(0L);
    mockedUserAccount.setSource(User.Source.UNKNOWN);
    Mockito.when(accountService.getUserAccountById(Mockito.anyLong())).thenReturn(mockedUserAccount);
    try {
        cmd.authenticate("command", params, session, null, HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
    } catch (ServerApiException exception) {
        assertEquals(exception.getErrorCode(), ApiErrorCode.ACCOUNT_ERROR);
    } finally {
        // accountService should have been called twice by now, for this case and the case above
        Mockito.verify(accountService, Mockito.times(2)).getUserAccountById(Mockito.anyLong());
    }
    // all valid test
    mockedUserAccount.setSource(User.Source.SAML2);
    Mockito.when(accountService.getUserAccountById(Mockito.anyLong())).thenReturn(mockedUserAccount);
    Mockito.when(apiServer.verifyUser(Mockito.anyLong())).thenReturn(true);
    LoginCmdResponse loginCmdResponse = new LoginCmdResponse();
    loginCmdResponse.setUserId("1");
    loginCmdResponse.setDomainId("1");
    loginCmdResponse.setType("1");
    loginCmdResponse.setUsername("userName");
    loginCmdResponse.setAccount("someAccount");
    loginCmdResponse.setFirstName("firstName");
    loginCmdResponse.setLastName("lastName");
    loginCmdResponse.setSessionKey("newSessionKeyString");
    Mockito.when(apiServer.loginUser(nullable(HttpSession.class), nullable(String.class), nullable(String.class), nullable(Long.class), nullable(String.class), nullable(InetAddress.class), nullable(Map.class))).thenReturn(loginCmdResponse);
    Mockito.doNothing().when(resp).sendRedirect(nullable(String.class));
    try {
        cmd.authenticate("command", params, session, null, HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
    } catch (ServerApiException exception) {
        fail("SAML list and switch account API failed to pass for all valid data: " + exception.getMessage());
    } finally {
        // accountService should have been called 4 times by now, for this case twice and 2 for cases above
        Mockito.verify(accountService, Mockito.times(4)).getUserAccountById(Mockito.anyLong());
        Mockito.verify(resp, Mockito.times(1)).sendRedirect(anyString());
    }
}
Also used : HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) DomainVO(com.cloud.domain.DomainVO) Field(java.lang.reflect.Field) UserAccountVO(com.cloud.user.UserAccountVO) UserVO(com.cloud.user.UserVO) ServerApiException(org.apache.cloudstack.api.ServerApiException) InetAddress(java.net.InetAddress) HashMap(java.util.HashMap) Map(java.util.Map) LoginCmdResponse(org.apache.cloudstack.api.response.LoginCmdResponse) Test(org.junit.Test)

Example 33 with DomainVO

use of com.cloud.domain.DomainVO in project cloudstack by apache.

the class QueryManagerImpl method listDataCentersInternal.

private Pair<List<DataCenterJoinVO>, Integer> listDataCentersInternal(ListZonesCmd cmd) {
    Account account = CallContext.current().getCallingAccount();
    Long domainId = cmd.getDomainId();
    Long id = cmd.getId();
    String keyword = cmd.getKeyword();
    String name = cmd.getName();
    String networkType = cmd.getNetworkType();
    Map<String, String> resourceTags = cmd.getTags();
    SearchBuilder<DataCenterJoinVO> sb = _dcJoinDao.createSearchBuilder();
    if (resourceTags != null && !resourceTags.isEmpty()) {
        SearchBuilder<ResourceTagVO> tagSearch = _resourceTagDao.createSearchBuilder();
        for (int count = 0; count < resourceTags.size(); count++) {
            tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ);
            tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ);
            tagSearch.cp();
        }
        tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ);
        sb.groupBy(sb.entity().getId());
        sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER);
    }
    Filter searchFilter = new Filter(DataCenterJoinVO.class, "sortKey", SortKeyAscending.value(), cmd.getStartIndex(), cmd.getPageSizeVal());
    searchFilter.addOrderBy(DataCenterJoinVO.class, "id", true);
    SearchCriteria<DataCenterJoinVO> sc = sb.create();
    if (networkType != null) {
        sc.addAnd("networkType", SearchCriteria.Op.EQ, networkType);
    }
    if (id != null) {
        sc.addAnd("id", SearchCriteria.Op.EQ, id);
    } else if (name != null) {
        sc.addAnd("name", SearchCriteria.Op.EQ, name);
    } else {
        if (keyword != null) {
            SearchCriteria<DataCenterJoinVO> ssc = _dcJoinDao.createSearchCriteria();
            ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
            ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%");
            sc.addAnd("name", SearchCriteria.Op.SC, ssc);
        }
        /*
             * List all resources due to Explicit Dedication except the
             * dedicated resources of other account
             */
        if (domainId != null) {
            // 
            // for domainId != null // right now, we made the decision to
            // only list zones associated // with this domain, private zone
            sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
            if (_accountMgr.isNormalUser(account.getId())) {
                // accountId == null (zones dedicated to a domain) or
                // accountId = caller
                SearchCriteria<DataCenterJoinVO> sdc = _dcJoinDao.createSearchCriteria();
                sdc.addOr("accountId", SearchCriteria.Op.EQ, account.getId());
                sdc.addOr("accountId", SearchCriteria.Op.NULL);
                sc.addAnd("accountId", SearchCriteria.Op.SC, sdc);
            }
        } else if (_accountMgr.isNormalUser(account.getId())) {
            // it was decided to return all zones for the user's domain, and
            // everything above till root
            // list all zones belonging to this domain, and all of its
            // parents
            // check the parent, if not null, add zones for that parent to
            // list
            // find all domain Id up to root domain for this account
            List<Long> domainIds = new ArrayList<Long>();
            DomainVO domainRecord = _domainDao.findById(account.getDomainId());
            if (domainRecord == null) {
                s_logger.error("Could not find the domainId for account:" + account.getAccountName());
                throw new CloudAuthenticationException("Could not find the domainId for account:" + account.getAccountName());
            }
            domainIds.add(domainRecord.getId());
            while (domainRecord.getParent() != null) {
                domainRecord = _domainDao.findById(domainRecord.getParent());
                domainIds.add(domainRecord.getId());
            }
            // domainId == null (public zones) or domainId IN [all domain id
            // up to root domain]
            SearchCriteria<DataCenterJoinVO> sdc = _dcJoinDao.createSearchCriteria();
            sdc.addOr("domainId", SearchCriteria.Op.IN, domainIds.toArray());
            sdc.addOr("domainId", SearchCriteria.Op.NULL);
            sc.addAnd("domainId", SearchCriteria.Op.SC, sdc);
            // remove disabled zones
            sc.addAnd("allocationState", SearchCriteria.Op.NEQ, Grouping.AllocationState.Disabled);
            // accountId == null (zones dedicated to a domain) or
            // accountId = caller
            SearchCriteria<DataCenterJoinVO> sdc2 = _dcJoinDao.createSearchCriteria();
            sdc2.addOr("accountId", SearchCriteria.Op.EQ, account.getId());
            sdc2.addOr("accountId", SearchCriteria.Op.NULL);
            sc.addAnd("accountId", SearchCriteria.Op.SC, sdc2);
            // remove Dedicated zones not dedicated to this domainId or
            // subdomainId
            List<Long> dedicatedZoneIds = removeDedicatedZoneNotSuitabe(domainIds);
            if (!dedicatedZoneIds.isEmpty()) {
                sdc.addAnd("id", SearchCriteria.Op.NIN, dedicatedZoneIds.toArray(new Object[dedicatedZoneIds.size()]));
            }
        } else if (_accountMgr.isDomainAdmin(account.getId()) || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
            // it was decided to return all zones for the domain admin, and
            // everything above till root, as well as zones till the domain
            // leaf
            List<Long> domainIds = new ArrayList<Long>();
            DomainVO domainRecord = _domainDao.findById(account.getDomainId());
            if (domainRecord == null) {
                s_logger.error("Could not find the domainId for account:" + account.getAccountName());
                throw new CloudAuthenticationException("Could not find the domainId for account:" + account.getAccountName());
            }
            domainIds.add(domainRecord.getId());
            // find all domain Ids till leaf
            List<DomainVO> allChildDomains = _domainDao.findAllChildren(domainRecord.getPath(), domainRecord.getId());
            for (DomainVO domain : allChildDomains) {
                domainIds.add(domain.getId());
            }
            // then find all domain Id up to root domain for this account
            while (domainRecord.getParent() != null) {
                domainRecord = _domainDao.findById(domainRecord.getParent());
                domainIds.add(domainRecord.getId());
            }
            // domainId == null (public zones) or domainId IN [all domain id
            // up to root domain]
            SearchCriteria<DataCenterJoinVO> sdc = _dcJoinDao.createSearchCriteria();
            sdc.addOr("domainId", SearchCriteria.Op.IN, domainIds.toArray());
            sdc.addOr("domainId", SearchCriteria.Op.NULL);
            sc.addAnd("domainId", SearchCriteria.Op.SC, sdc);
            // remove disabled zones
            sc.addAnd("allocationState", SearchCriteria.Op.NEQ, Grouping.AllocationState.Disabled);
            // remove Dedicated zones not dedicated to this domainId or
            // subdomainId
            List<Long> dedicatedZoneIds = removeDedicatedZoneNotSuitabe(domainIds);
            if (!dedicatedZoneIds.isEmpty()) {
                sdc.addAnd("id", SearchCriteria.Op.NIN, dedicatedZoneIds.toArray(new Object[dedicatedZoneIds.size()]));
            }
        }
        // handle available=FALSE option, only return zones with at least
        // one VM running there
        Boolean available = cmd.isAvailable();
        if (account != null) {
            if ((available != null) && Boolean.FALSE.equals(available)) {
                // data centers with
                Set<Long> dcIds = new HashSet<Long>();
                // at least one VM
                // running
                List<DomainRouterVO> routers = _routerDao.listBy(account.getId());
                for (DomainRouterVO router : routers) {
                    dcIds.add(router.getDataCenterId());
                }
                if (dcIds.size() == 0) {
                    return new Pair<List<DataCenterJoinVO>, Integer>(new ArrayList<DataCenterJoinVO>(), 0);
                } else {
                    sc.addAnd("id", SearchCriteria.Op.IN, dcIds.toArray());
                }
            }
        }
    }
    if (resourceTags != null && !resourceTags.isEmpty()) {
        int count = 0;
        sc.setJoinParameters("tagSearch", "resourceType", ResourceObjectType.Zone.toString());
        for (Map.Entry<String, String> entry : resourceTags.entrySet()) {
            sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), entry.getKey());
            sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), entry.getValue());
            count++;
        }
    }
    return _dcJoinDao.searchAndCount(sc, searchFilter);
}
Also used : DataCenterJoinVO(com.cloud.api.query.vo.DataCenterJoinVO) Account(com.cloud.user.Account) HashSet(java.util.HashSet) Set(java.util.Set) CloudAuthenticationException(com.cloud.exception.CloudAuthenticationException) ArrayList(java.util.ArrayList) ResourceTagVO(com.cloud.tags.ResourceTagVO) ArrayList(java.util.ArrayList) List(java.util.List) SearchCriteria(com.cloud.utils.db.SearchCriteria) DomainVO(com.cloud.domain.DomainVO) TemplateFilter(com.cloud.template.VirtualMachineTemplate.TemplateFilter) Filter(com.cloud.utils.db.Filter) Map(java.util.Map) HashMap(java.util.HashMap) DomainRouterVO(com.cloud.vm.DomainRouterVO)

Example 34 with DomainVO

use of com.cloud.domain.DomainVO in project cloudstack by apache.

the class QueryManagerImpl method searchForTemplatesInternal.

private Pair<List<TemplateJoinVO>, Integer> searchForTemplatesInternal(Long templateId, String name, String keyword, TemplateFilter templateFilter, boolean isIso, Boolean bootable, Long pageSize, Long startIndex, Long zoneId, HypervisorType hyperType, boolean showDomr, boolean onlyReady, List<Account> permittedAccounts, Account caller, ListProjectResourcesCriteria listProjectResourcesCriteria, Map<String, String> tags, boolean showRemovedTmpl, List<Long> ids, Long parentTemplateId, Boolean showUnique) {
    // check if zone is configured, if not, just return empty list
    List<HypervisorType> hypers = null;
    if (!isIso) {
        hypers = _resourceMgr.listAvailHypervisorInZone(null, null);
        if (hypers == null || hypers.isEmpty()) {
            return new Pair<List<TemplateJoinVO>, Integer>(new ArrayList<TemplateJoinVO>(), 0);
        }
    }
    VMTemplateVO template = null;
    Filter searchFilter = new Filter(TemplateJoinVO.class, "sortKey", SortKeyAscending.value(), startIndex, pageSize);
    searchFilter.addOrderBy(TemplateJoinVO.class, "tempZonePair", SortKeyAscending.value());
    SearchBuilder<TemplateJoinVO> sb = _templateJoinDao.createSearchBuilder();
    if (showUnique) {
        // select distinct templateId
        sb.select(null, Func.DISTINCT, sb.entity().getId());
    } else {
        // select distinct (templateId, zoneId) pair
        sb.select(null, Func.DISTINCT, sb.entity().getTempZonePair());
    }
    if (ids != null && !ids.isEmpty()) {
        sb.and("idIN", sb.entity().getId(), SearchCriteria.Op.IN);
    }
    SearchCriteria<TemplateJoinVO> sc = sb.create();
    // verify templateId parameter and specially handle it
    if (templateId != null) {
        // Done for backward compatibility - Bug-5221
        template = _templateDao.findByIdIncludingRemoved(templateId);
        if (template == null) {
            throw new InvalidParameterValueException("Please specify a valid template ID.");
        }
        // If ISO requested then it should be ISO.
        if (isIso && template.getFormat() != ImageFormat.ISO) {
            s_logger.error("Template Id " + templateId + " is not an ISO");
            InvalidParameterValueException ex = new InvalidParameterValueException("Specified Template Id is not an ISO");
            ex.addProxyObject(template.getUuid(), "templateId");
            throw ex;
        }
        // If ISO not requested then it shouldn't be an ISO.
        if (!isIso && template.getFormat() == ImageFormat.ISO) {
            s_logger.error("Incorrect format of the template id " + templateId);
            InvalidParameterValueException ex = new InvalidParameterValueException("Incorrect format " + template.getFormat() + " of the specified template id");
            ex.addProxyObject(template.getUuid(), "templateId");
            throw ex;
        }
        if (!template.isPublicTemplate() && caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) {
            Account template_acc = _accountMgr.getAccount(template.getAccountId());
            DomainVO domain = _domainDao.findById(template_acc.getDomainId());
            _accountMgr.checkAccess(caller, domain);
        } else // if template is not public, perform permission check here
        if (!template.isPublicTemplate() && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
            _accountMgr.checkAccess(caller, null, false, template);
        }
        // if templateId is specified, then we will just use the id to
        // search and ignore other query parameters
        sc.addAnd("id", SearchCriteria.Op.EQ, templateId);
    } else {
        DomainVO domain = null;
        if (!permittedAccounts.isEmpty()) {
            domain = _domainDao.findById(permittedAccounts.get(0).getDomainId());
        } else {
            domain = _domainDao.findById(Domain.ROOT_DOMAIN);
        }
        setIdsListToSearchCriteria(sc, ids);
        // add criteria for project or not
        if (listProjectResourcesCriteria == ListProjectResourcesCriteria.SkipProjectResources) {
            sc.addAnd("accountType", SearchCriteria.Op.NEQ, Account.ACCOUNT_TYPE_PROJECT);
        } else if (listProjectResourcesCriteria == ListProjectResourcesCriteria.ListProjectResourcesOnly) {
            sc.addAnd("accountType", SearchCriteria.Op.EQ, Account.ACCOUNT_TYPE_PROJECT);
        }
        // add criteria for domain path in case of domain admin
        if ((templateFilter == TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable) && (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN)) {
            sc.addAnd("domainPath", SearchCriteria.Op.LIKE, domain.getPath() + "%");
        }
        List<Long> relatedDomainIds = new ArrayList<Long>();
        List<Long> permittedAccountIds = new ArrayList<Long>();
        if (!permittedAccounts.isEmpty()) {
            for (Account account : permittedAccounts) {
                permittedAccountIds.add(account.getId());
                boolean publicTemplates = (templateFilter == TemplateFilter.featured || templateFilter == TemplateFilter.community);
                // get all parent domain ID's all the way till root domain
                DomainVO domainTreeNode = null;
                // if template filter is featured, or community, all child domains should be included in search
                if (publicTemplates) {
                    domainTreeNode = _domainDao.findById(Domain.ROOT_DOMAIN);
                } else {
                    domainTreeNode = _domainDao.findById(account.getDomainId());
                }
                relatedDomainIds.add(domainTreeNode.getId());
                while (domainTreeNode.getParent() != null) {
                    domainTreeNode = _domainDao.findById(domainTreeNode.getParent());
                    relatedDomainIds.add(domainTreeNode.getId());
                }
                // get all child domain ID's
                if (_accountMgr.isAdmin(account.getId()) || publicTemplates) {
                    List<DomainVO> allChildDomains = _domainDao.findAllChildren(domainTreeNode.getPath(), domainTreeNode.getId());
                    for (DomainVO childDomain : allChildDomains) {
                        relatedDomainIds.add(childDomain.getId());
                    }
                }
            }
        }
        // control different template filters
        if (templateFilter == TemplateFilter.featured || templateFilter == TemplateFilter.community) {
            sc.addAnd("publicTemplate", SearchCriteria.Op.EQ, true);
            if (templateFilter == TemplateFilter.featured) {
                sc.addAnd("featured", SearchCriteria.Op.EQ, true);
            } else {
                sc.addAnd("featured", SearchCriteria.Op.EQ, false);
            }
            if (!permittedAccounts.isEmpty()) {
                SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
                scc.addOr("domainId", SearchCriteria.Op.IN, relatedDomainIds.toArray());
                scc.addOr("domainId", SearchCriteria.Op.NULL);
                sc.addAnd("domainId", SearchCriteria.Op.SC, scc);
            }
        } else if (templateFilter == TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable) {
            if (!permittedAccounts.isEmpty()) {
                sc.addAnd("accountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
            }
        } else if (templateFilter == TemplateFilter.sharedexecutable || templateFilter == TemplateFilter.shared) {
            // only show templates shared by others
            sc.addAnd("sharedAccountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
        } else if (templateFilter == TemplateFilter.executable) {
            SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
            scc.addOr("publicTemplate", SearchCriteria.Op.EQ, true);
            if (!permittedAccounts.isEmpty()) {
                scc.addOr("accountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
            }
            sc.addAnd("publicTemplate", SearchCriteria.Op.SC, scc);
        } else if (templateFilter == TemplateFilter.all && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
            SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
            scc.addOr("publicTemplate", SearchCriteria.Op.EQ, true);
            if (listProjectResourcesCriteria == ListProjectResourcesCriteria.SkipProjectResources) {
                scc.addOr("domainPath", SearchCriteria.Op.LIKE, _domainDao.findById(caller.getDomainId()).getPath() + "%");
            } else {
                if (!permittedAccounts.isEmpty()) {
                    scc.addOr("accountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
                    scc.addOr("sharedAccountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
                }
            }
            sc.addAnd("publicTemplate", SearchCriteria.Op.SC, scc);
        }
    }
    return templateChecks(isIso, hypers, tags, name, keyword, hyperType, onlyReady, bootable, zoneId, showDomr, showRemovedTmpl, parentTemplateId, showUnique, searchFilter, sc);
}
Also used : Account(com.cloud.user.Account) VMTemplateVO(com.cloud.storage.VMTemplateVO) ArrayList(java.util.ArrayList) SearchCriteria(com.cloud.utils.db.SearchCriteria) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) DomainVO(com.cloud.domain.DomainVO) TemplateFilter(com.cloud.template.VirtualMachineTemplate.TemplateFilter) Filter(com.cloud.utils.db.Filter) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) TemplateJoinVO(com.cloud.api.query.vo.TemplateJoinVO) Pair(com.cloud.utils.Pair)

Example 35 with DomainVO

use of com.cloud.domain.DomainVO in project cloudstack by apache.

the class QueryManagerImpl method searchForAsyncJobsInternal.

private Pair<List<AsyncJobJoinVO>, Integer> searchForAsyncJobsInternal(ListAsyncJobsCmd cmd) {
    Account caller = CallContext.current().getCallingAccount();
    List<Long> permittedAccounts = new ArrayList<Long>();
    Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(cmd.getDomainId(), cmd.isRecursive(), null);
    _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), null, permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
    Long domainId = domainIdRecursiveListProject.first();
    Boolean isRecursive = domainIdRecursiveListProject.second();
    ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
    Filter searchFilter = new Filter(AsyncJobJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
    SearchBuilder<AsyncJobJoinVO> sb = _jobJoinDao.createSearchBuilder();
    sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN);
    boolean accountJoinIsDone = false;
    if (permittedAccounts.isEmpty() && domainId != null) {
        sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ);
        sb.and("path", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE);
        accountJoinIsDone = true;
    }
    if (listProjectResourcesCriteria != null) {
        if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) {
            sb.and("type", sb.entity().getAccountType(), SearchCriteria.Op.EQ);
        } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) {
            sb.and("type", sb.entity().getAccountType(), SearchCriteria.Op.NEQ);
        }
        if (!accountJoinIsDone) {
            sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ);
            sb.and("path", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE);
        }
    }
    Object keyword = cmd.getKeyword();
    Object startDate = cmd.getStartDate();
    SearchCriteria<AsyncJobJoinVO> sc = sb.create();
    if (listProjectResourcesCriteria != null) {
        sc.setParameters("type", Account.ACCOUNT_TYPE_PROJECT);
    }
    if (!permittedAccounts.isEmpty()) {
        sc.setParameters("accountIdIN", permittedAccounts.toArray());
    } else if (domainId != null) {
        DomainVO domain = _domainDao.findById(domainId);
        if (isRecursive) {
            sc.setParameters("path", domain.getPath() + "%");
        } else {
            sc.setParameters("domainId", domainId);
        }
    }
    if (keyword != null) {
        sc.addAnd("cmd", SearchCriteria.Op.LIKE, "%" + keyword + "%");
    }
    if (startDate != null) {
        sc.addAnd("created", SearchCriteria.Op.GTEQ, startDate);
    }
    return _jobJoinDao.searchAndCount(sc, searchFilter);
}
Also used : Account(com.cloud.user.Account) Ternary(com.cloud.utils.Ternary) ArrayList(java.util.ArrayList) ListProjectResourcesCriteria(com.cloud.projects.Project.ListProjectResourcesCriteria) DomainVO(com.cloud.domain.DomainVO) AsyncJobJoinVO(com.cloud.api.query.vo.AsyncJobJoinVO) TemplateFilter(com.cloud.template.VirtualMachineTemplate.TemplateFilter) Filter(com.cloud.utils.db.Filter)

Aggregations

DomainVO (com.cloud.domain.DomainVO)196 Account (com.cloud.user.Account)85 AccountVO (com.cloud.user.AccountVO)64 Test (org.junit.Test)56 ArrayList (java.util.ArrayList)53 DomainDao (com.cloud.domain.dao.DomainDao)30 Field (java.lang.reflect.Field)30 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)29 SslCertDao (com.cloud.network.dao.SslCertDao)29 AccountManager (com.cloud.user.AccountManager)29 SslCertVO (com.cloud.network.dao.SslCertVO)27 List (java.util.List)26 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)24 Pair (com.cloud.utils.Pair)24 Domain (com.cloud.domain.Domain)23 Filter (com.cloud.utils.db.Filter)23 File (java.io.File)23 IOException (java.io.IOException)23 FileUtils.readFileToString (org.apache.commons.io.FileUtils.readFileToString)23 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)22