cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From r...@apache.org
Subject [02/11] git commit: updated refs/heads/master to 7e902cd
Date Thu, 03 Dec 2015 19:43:31 GMT
CLOUDSTACK-6276 Fixing affinity groups for projects


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/c76d3171
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/c76d3171
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/c76d3171

Branch: refs/heads/master
Commit: c76d31715023070165b30c9c76300c4fdc3da15d
Parents: 92913a1
Author: Patrick Dube <pdube@cloudops.com>
Authored: Fri Nov 27 14:12:28 2015 -0500
Committer: Patrick Dube <pdube@cloudops.com>
Committed: Fri Nov 27 14:43:02 2015 -0500

----------------------------------------------------------------------
 .../affinity/AffinityGroupResponse.java         |   16 +-
 .../affinity/AffinityGroupService.java          |   32 +-
 .../affinitygroup/CreateAffinityGroupCmd.java   |   38 +-
 .../affinitygroup/DeleteAffinityGroupCmd.java   |   52 +-
 .../affinitygroup/ListAffinityGroupsCmd.java    |   14 +-
 .../apache/cloudstack/query/QueryService.java   |    6 +-
 .../cloud/entity/api/VMEntityManagerImpl.java   |    2 +-
 .../affinity/dao/AffinityGroupDao.java          |    7 +-
 .../affinity/dao/AffinityGroupDaoImpl.java      |    7 +-
 .../dedicated/DedicatedResourceManagerImpl.java |    4 +-
 .../IntegrationTestConfiguration.java           |    2 +-
 .../cloud/acl/AffinityGroupAccessChecker.java   |   22 +-
 .../com/cloud/api/query/QueryManagerImpl.java   |  111 +-
 .../cloud/api/query/vo/AffinityGroupJoinVO.java |   35 +-
 .../configuration/ConfigurationManagerImpl.java |    6 +-
 .../src/com/cloud/user/AccountManagerImpl.java  |   92 +-
 .../affinity/AffinityGroupServiceImpl.java      |  258 ++---
 .../affinity/AffinityApiUnitTest.java           |   13 +-
 .../affinity/AffinityGroupServiceImplTest.java  |  358 ++++++
 setup/db/db/schema-460to461.sql                 |   32 +
 .../component/test_affinity_groups_projects.py  | 1083 ++++++++++++++++++
 .../smoke/test_affinity_groups_projects.py      |  188 +++
 tools/marvin/marvin/lib/base.py                 |    4 +-
 23 files changed, 1955 insertions(+), 427 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c76d3171/api/src/org/apache/cloudstack/affinity/AffinityGroupResponse.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/affinity/AffinityGroupResponse.java b/api/src/org/apache/cloudstack/affinity/AffinityGroupResponse.java
index aa0b4e6..22842b8 100644
--- a/api/src/org/apache/cloudstack/affinity/AffinityGroupResponse.java
+++ b/api/src/org/apache/cloudstack/affinity/AffinityGroupResponse.java
@@ -56,12 +56,20 @@ public class AffinityGroupResponse extends BaseResponse implements ControlledVie
     @Param(description = "the domain name of the affinity group")
     private String domainName;
 
+    @SerializedName(ApiConstants.PROJECT_ID)
+    @Param(description = "the project ID of the affinity group")
+    private String projectId;
+
+    @SerializedName(ApiConstants.PROJECT)
+    @Param(description = "the project name of the affinity group")
+    private String projectName;
+
     @SerializedName(ApiConstants.TYPE)
     @Param(description = "the type of the affinity group")
     private String type;
 
     @SerializedName("virtualmachineIds")
-    @Param(description = "virtual machine Ids associated with this affinity group ")
+    @Param(description = "virtual machine IDs associated with this affinity group")
     private List<String> vmIdList;
 
     public AffinityGroupResponse() {
@@ -134,14 +142,12 @@ public class AffinityGroupResponse extends BaseResponse implements ControlledVie
 
     @Override
     public void setProjectId(String projectId) {
-        // TODO Auto-generated method stub
-
+        this.projectId = projectId;
     }
 
     @Override
     public void setProjectName(String projectName) {
-        // TODO Auto-generated method stub
-
+        this.projectName = projectName;
     }
 
     public void setVMIdList(List<String> vmIdList) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c76d3171/api/src/org/apache/cloudstack/affinity/AffinityGroupService.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/affinity/AffinityGroupService.java b/api/src/org/apache/cloudstack/affinity/AffinityGroupService.java
index 8ffc3b2..018e5f5 100644
--- a/api/src/org/apache/cloudstack/affinity/AffinityGroupService.java
+++ b/api/src/org/apache/cloudstack/affinity/AffinityGroupService.java
@@ -18,47 +18,36 @@ package org.apache.cloudstack.affinity;
 
 import java.util.List;
 
+import org.apache.cloudstack.api.command.user.affinitygroup.CreateAffinityGroupCmd;
+
 import com.cloud.uservm.UserVm;
-import com.cloud.utils.Pair;
 
 public interface AffinityGroupService {
 
     /**
      * Creates an affinity/anti-affinity group for the given account/domain.
      *
-     * @param account
+     * @param accountName
+     * @param projectId
      * @param domainId
-     * @param name
-     * @param type
+     * @param affinityGroupName
+     * @param affinityGroupType
      * @param description
      * @return AffinityGroup
      */
+    AffinityGroup createAffinityGroup(String accountName, Long projectId, Long domainId, String affinityGroupName, String affinityGroupType, String description);
 
-    AffinityGroup createAffinityGroup(String account, Long domainId, String affinityGroupName, String affinityGroupType, String description);
+    AffinityGroup createAffinityGroup(CreateAffinityGroupCmd createAffinityGroupCmd);
 
     /**
      * Creates an affinity/anti-affinity group.
      *
      * @param affinityGroupId
-     * @param account
-     * @param domainId
-     * @param affinityGroupName
-     */
-    boolean deleteAffinityGroup(Long affinityGroupId, String account, Long domainId, String affinityGroupName);
-
-    /** Lists Affinity Groups in your account
-     * @param account
+     * @param accountName
      * @param domainId
-     * @param affinityGroupId
      * @param affinityGroupName
-     * @param affinityGroupType
-     * @param vmId
-     * @param startIndex
-     * @param pageSize
-     * @return
      */
-    Pair<List<? extends AffinityGroup>, Integer> listAffinityGroups(Long affinityGroupId, String affinityGroupName, String affinityGroupType, Long vmId, Long startIndex,
-        Long pageSize);
+    boolean deleteAffinityGroup(Long affinityGroupId, String accountName, Long projectId, Long domainId, String affinityGroupName);
 
     /**
      * List group types available in deployment
@@ -77,6 +66,5 @@ public interface AffinityGroupService {
 
     boolean isAffinityGroupAvailableInDomain(long affinityGroupId, long domainId);
 
-    AffinityGroup createAffinityGroupInternal(String account, Long domainId, String affinityGroupName, String affinityGroupType, String description);
 
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c76d3171/api/src/org/apache/cloudstack/api/command/user/affinitygroup/CreateAffinityGroupCmd.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/command/user/affinitygroup/CreateAffinityGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/affinitygroup/CreateAffinityGroupCmd.java
index 96d8bec..8cc3d69 100644
--- a/api/src/org/apache/cloudstack/api/command/user/affinitygroup/CreateAffinityGroupCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/affinitygroup/CreateAffinityGroupCmd.java
@@ -17,7 +17,6 @@
 package org.apache.cloudstack.api.command.user.affinitygroup;
 
 import org.apache.log4j.Logger;
-
 import org.apache.cloudstack.affinity.AffinityGroup;
 import org.apache.cloudstack.affinity.AffinityGroupResponse;
 import org.apache.cloudstack.api.APICommand;
@@ -28,6 +27,7 @@ import org.apache.cloudstack.api.BaseAsyncCreateCmd;
 import org.apache.cloudstack.api.Parameter;
 import org.apache.cloudstack.api.ServerApiException;
 import org.apache.cloudstack.api.response.DomainResponse;
+import org.apache.cloudstack.api.response.ProjectResponse;
 import org.apache.cloudstack.context.CallContext;
 
 import com.cloud.event.EventTypes;
@@ -54,6 +54,12 @@ public class CreateAffinityGroupCmd extends BaseAsyncCreateCmd {
                entityType = DomainResponse.class)
     private Long domainId;
 
+    @Parameter(name = ApiConstants.PROJECT_ID,
+               type = CommandType.UUID,
+               entityType = ProjectResponse.class,
+               description = "create affinity group for project")
+    private Long projectId;
+
     @Parameter(name = ApiConstants.DESCRIPTION, type = CommandType.STRING, description = "optional description of the affinity group")
     private String description;
 
@@ -90,6 +96,10 @@ public class CreateAffinityGroupCmd extends BaseAsyncCreateCmd {
         return affinityGroupType;
     }
 
+    public Long getProjectId() {
+        return projectId;
+    }
+
     // ///////////////////////////////////////////////////
     // ///////////// API Implementation///////////////////
     // ///////////////////////////////////////////////////
@@ -101,23 +111,17 @@ public class CreateAffinityGroupCmd extends BaseAsyncCreateCmd {
 
     @Override
     public long getEntityOwnerId() {
-        Account account = CallContext.current().getCallingAccount();
-        if ((account == null) || _accountService.isAdmin(account.getId())) {
-            if ((domainId != null) && (accountName != null)) {
-                Account userAccount = _responseGenerator.findAccountByNameDomain(accountName, domainId);
-                if (userAccount != null) {
-                    return userAccount.getId();
-                }
-            }
-        }
+        Account caller = CallContext.current().getCallingAccount();
 
-        if (account != null) {
-            return account.getId();
+        //For domain wide affinity groups (if the affinity group processor type allows it)
+        if(projectId == null && domainId != null && accountName == null && _accountService.isRootAdmin(caller.getId())){
+            return Account.ACCOUNT_ID_SYSTEM;
         }
-
-        return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this
-                                          // command to SYSTEM so ERROR events
-                                          // are tracked
+        Account owner = _accountService.finalizeOwner(caller, accountName, domainId, projectId);
+        if(owner == null){
+            return caller.getAccountId();
+        }
+        return owner.getAccountId();
     }
 
     @Override
@@ -134,7 +138,7 @@ public class CreateAffinityGroupCmd extends BaseAsyncCreateCmd {
 
     @Override
     public void create() throws ResourceAllocationException {
-        AffinityGroup result = _affinityGroupService.createAffinityGroup(accountName, domainId, affinityGroupName, affinityGroupType, description);
+        AffinityGroup result = _affinityGroupService.createAffinityGroup(this);
         if (result != null) {
             setEntityId(result.getId());
             setEntityUuid(result.getUuid());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c76d3171/api/src/org/apache/cloudstack/api/command/user/affinitygroup/DeleteAffinityGroupCmd.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/command/user/affinitygroup/DeleteAffinityGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/affinitygroup/DeleteAffinityGroupCmd.java
index 4eeff06..e8884b4 100644
--- a/api/src/org/apache/cloudstack/api/command/user/affinitygroup/DeleteAffinityGroupCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/affinitygroup/DeleteAffinityGroupCmd.java
@@ -17,8 +17,8 @@
 package org.apache.cloudstack.api.command.user.affinitygroup;
 
 
+import org.apache.cloudstack.api.response.ProjectResponse;
 import org.apache.log4j.Logger;
-
 import org.apache.cloudstack.acl.SecurityChecker.AccessType;
 import org.apache.cloudstack.affinity.AffinityGroup;
 import org.apache.cloudstack.affinity.AffinityGroupResponse;
@@ -35,7 +35,6 @@ import org.apache.cloudstack.api.response.SuccessResponse;
 import org.apache.cloudstack.context.CallContext;
 
 import com.cloud.event.EventTypes;
-import com.cloud.exception.InvalidParameterValueException;
 import com.cloud.user.Account;
 
 @APICommand(name = "deleteAffinityGroup", description = "Deletes affinity group", responseObject = SuccessResponse.class, entityType = {AffinityGroup.class},
@@ -67,6 +66,9 @@ public class DeleteAffinityGroupCmd extends BaseAsyncCmd {
     @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "The name of the affinity group. Mutually exclusive with ID parameter")
     private String name;
 
+    @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, description = "the project of the affinity group", entityType = ProjectResponse.class)
+    private Long projectId;
+
     /////////////////////////////////////////////////////
     /////////////////// Accessors ///////////////////////
     /////////////////////////////////////////////////////
@@ -79,22 +81,11 @@ public class DeleteAffinityGroupCmd extends BaseAsyncCmd {
         return domainId;
     }
 
-    public Long getId() {
-        if (id != null && name != null) {
-            throw new InvalidParameterValueException("name and id parameters are mutually exclusive");
-        }
-
-        if (name != null) {
-            id = _responseGenerator.getAffinityGroupId(name, getEntityOwnerId());
-            if (id == null) {
-                throw new InvalidParameterValueException("Unable to find affinity group by name " + name + " for the account ID=" + getEntityOwnerId());
-            }
-        }
-
-        if (id == null) {
-            throw new InvalidParameterValueException("Either ID or name parameter is required by deleteAffinityGroup command");
-        }
+    public Long getProjectId() {
+        return projectId;
+    }
 
+    public Long getId() {
         return id;
     }
 
@@ -109,29 +100,22 @@ public class DeleteAffinityGroupCmd extends BaseAsyncCmd {
 
     @Override
     public long getEntityOwnerId() {
-        Account account = CallContext.current().getCallingAccount();
-        if ((account == null) || _accountService.isAdmin(account.getId())) {
-            if ((domainId != null) && (accountName != null)) {
-                Account userAccount = _responseGenerator.findAccountByNameDomain(accountName, domainId);
-                if (userAccount != null) {
-                    return userAccount.getId();
-                }
-            }
-        }
+        Account caller = CallContext.current().getCallingAccount();
 
-        if (account != null) {
-            return account.getId();
+        //For domain wide affinity groups (if the affinity group processor type allows it)
+        if(projectId == null && domainId != null && accountName == null && _accountService.isRootAdmin(caller.getId())){
+            return Account.ACCOUNT_ID_SYSTEM;
         }
-
-        return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this
-                                          // command to SYSTEM so ERROR events
-                                          // are tracked
-
+        Account owner = _accountService.finalizeOwner(caller, accountName, domainId, projectId);
+        if(owner == null){
+            return caller.getAccountId();
+        }
+        return owner.getAccountId();
     }
 
     @Override
     public void execute() {
-        boolean result = _affinityGroupService.deleteAffinityGroup(id, accountName, domainId, name);
+        boolean result = _affinityGroupService.deleteAffinityGroup(id, accountName, projectId, domainId, name);
         if (result) {
             SuccessResponse response = new SuccessResponse(getCommandName());
             setResponseObject(response);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c76d3171/api/src/org/apache/cloudstack/api/command/user/affinitygroup/ListAffinityGroupsCmd.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/command/user/affinitygroup/ListAffinityGroupsCmd.java b/api/src/org/apache/cloudstack/api/command/user/affinitygroup/ListAffinityGroupsCmd.java
index 41ed6fb..fa7935b 100644
--- a/api/src/org/apache/cloudstack/api/command/user/affinitygroup/ListAffinityGroupsCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/affinitygroup/ListAffinityGroupsCmd.java
@@ -23,14 +23,14 @@ import org.apache.cloudstack.affinity.AffinityGroupResponse;
 import org.apache.cloudstack.api.APICommand;
 import org.apache.cloudstack.api.ApiCommandJobType;
 import org.apache.cloudstack.api.ApiConstants;
-import org.apache.cloudstack.api.BaseListAccountResourcesCmd;
+import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd;
 import org.apache.cloudstack.api.Parameter;
 import org.apache.cloudstack.api.response.ListResponse;
 import org.apache.cloudstack.api.response.UserVmResponse;
 
 @APICommand(name = "listAffinityGroups", description = "Lists affinity groups", responseObject = AffinityGroupResponse.class, entityType = {AffinityGroup.class},
         requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
-public class ListAffinityGroupsCmd extends BaseListAccountResourcesCmd {
+public class ListAffinityGroupsCmd extends BaseListProjectAndAccountResourcesCmd {
     public static final Logger s_logger = Logger.getLogger(ListAffinityGroupsCmd.class.getName());
 
     private static final String s_name = "listaffinitygroupsresponse";
@@ -69,6 +69,10 @@ public class ListAffinityGroupsCmd extends BaseListAccountResourcesCmd {
         return id;
     }
 
+    public String getAffinityGroupType() {
+        return affinityGroupType;
+    }
+
     /////////////////////////////////////////////////////
     /////////////// API Implementation///////////////////
     /////////////////////////////////////////////////////
@@ -80,13 +84,9 @@ public class ListAffinityGroupsCmd extends BaseListAccountResourcesCmd {
 
     @Override
     public void execute() {
-
-        ListResponse<AffinityGroupResponse> response = _queryService.listAffinityGroups(id, affinityGroupName,
-                affinityGroupType, virtualMachineId, getAccountName(), getDomainId(), isRecursive(),
-                listAll(), getStartIndex(), getPageSizeVal(), getKeyword());
+        ListResponse<AffinityGroupResponse> response = _queryService.searchForAffinityGroups(this);
         response.setResponseName(getCommandName());
         setResponseObject(response);
-
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c76d3171/api/src/org/apache/cloudstack/query/QueryService.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/query/QueryService.java b/api/src/org/apache/cloudstack/query/QueryService.java
index 1a5ac11..de9fbb5 100644
--- a/api/src/org/apache/cloudstack/query/QueryService.java
+++ b/api/src/org/apache/cloudstack/query/QueryService.java
@@ -31,6 +31,7 @@ import org.apache.cloudstack.api.command.admin.storage.ListStorageTagsCmd;
 import org.apache.cloudstack.api.command.admin.user.ListUsersCmd;
 import org.apache.cloudstack.api.command.user.account.ListAccountsCmd;
 import org.apache.cloudstack.api.command.user.account.ListProjectAccountsCmd;
+import org.apache.cloudstack.api.command.user.affinitygroup.ListAffinityGroupsCmd;
 import org.apache.cloudstack.api.command.user.event.ListEventsCmd;
 import org.apache.cloudstack.api.command.user.iso.ListIsosCmd;
 import org.apache.cloudstack.api.command.user.job.ListAsyncJobsCmd;
@@ -131,9 +132,7 @@ public interface QueryService {
 
     ListResponse<TemplateResponse> listIsos(ListIsosCmd cmd);
 
-    ListResponse<AffinityGroupResponse> listAffinityGroups(Long affinityGroupId, String affinityGroupName,
-            String affinityGroupType, Long vmId, String accountName, Long domainId, boolean isRecursive,
-            boolean listAll, Long startIndex, Long pageSize, String keyword);
+    ListResponse<AffinityGroupResponse> searchForAffinityGroups(ListAffinityGroupsCmd cmd);
 
     List<ResourceDetailResponse> listResourceDetails(ListResourceDetailsCmd cmd);
 
@@ -142,5 +141,4 @@ public interface QueryService {
     ListResponse<StorageTagResponse> searchForStorageTags(ListStorageTagsCmd cmd);
 
     ListResponse<HostTagResponse> searchForHostTags(ListHostTagsCmd cmd);
-
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c76d3171/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VMEntityManagerImpl.java
----------------------------------------------------------------------
diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VMEntityManagerImpl.java b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VMEntityManagerImpl.java
index b1ac2f8..829ed10 100644
--- a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VMEntityManagerImpl.java
+++ b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VMEntityManagerImpl.java
@@ -192,7 +192,7 @@ public class VMEntityManagerImpl implements VMEntityManager {
             try {
                 dest = _dpMgr.planDeployment(vmProfile, plan, exclude, plannerToUse);
             } catch (AffinityConflictException e) {
-                throw new CloudRuntimeException("Unable to create deployment, affinity rules associted to the VM conflict");
+                throw new CloudRuntimeException("Unable to create deployment, affinity rules associated to the VM conflict");
             }
 
             if (dest != null) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c76d3171/engine/schema/src/org/apache/cloudstack/affinity/dao/AffinityGroupDao.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/org/apache/cloudstack/affinity/dao/AffinityGroupDao.java b/engine/schema/src/org/apache/cloudstack/affinity/dao/AffinityGroupDao.java
index 76a8144..010720b 100644
--- a/engine/schema/src/org/apache/cloudstack/affinity/dao/AffinityGroupDao.java
+++ b/engine/schema/src/org/apache/cloudstack/affinity/dao/AffinityGroupDao.java
@@ -18,7 +18,6 @@ package org.apache.cloudstack.affinity.dao;
 
 import java.util.List;
 
-import org.apache.cloudstack.affinity.AffinityGroup;
 import org.apache.cloudstack.affinity.AffinityGroupVO;
 
 import com.cloud.utils.db.GenericDao;
@@ -34,9 +33,9 @@ public interface AffinityGroupDao extends GenericDao<AffinityGroupVO, Long> {
 
     int removeByAccountId(long accountId);
 
-    AffinityGroup findDomainLevelGroupByName(Long domainId, String affinityGroupName);
+    AffinityGroupVO findDomainLevelGroupByName(Long domainId, String affinityGroupName);
 
-    AffinityGroup findByAccountAndType(Long accountId, String string);
+    AffinityGroupVO findByAccountAndType(Long accountId, String string);
 
-    AffinityGroup findDomainLevelGroupByType(Long domainId, String string);
+    AffinityGroupVO findDomainLevelGroupByType(Long domainId, String string);
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c76d3171/engine/schema/src/org/apache/cloudstack/affinity/dao/AffinityGroupDaoImpl.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/org/apache/cloudstack/affinity/dao/AffinityGroupDaoImpl.java b/engine/schema/src/org/apache/cloudstack/affinity/dao/AffinityGroupDaoImpl.java
index c63b04b..1fda52e 100644
--- a/engine/schema/src/org/apache/cloudstack/affinity/dao/AffinityGroupDaoImpl.java
+++ b/engine/schema/src/org/apache/cloudstack/affinity/dao/AffinityGroupDaoImpl.java
@@ -23,7 +23,6 @@ import javax.ejb.Local;
 import javax.inject.Inject;
 
 import org.apache.cloudstack.acl.ControlledEntity;
-import org.apache.cloudstack.affinity.AffinityGroup;
 import org.apache.cloudstack.affinity.AffinityGroupDomainMapVO;
 import org.apache.cloudstack.affinity.AffinityGroupVO;
 
@@ -136,7 +135,7 @@ public class AffinityGroupDaoImpl extends GenericDaoBase<AffinityGroupVO, Long>
     }
 
     @Override
-    public AffinityGroup findDomainLevelGroupByName(Long domainId, String affinityGroupName) {
+    public AffinityGroupVO findDomainLevelGroupByName(Long domainId, String affinityGroupName) {
         SearchCriteria<AffinityGroupVO> sc = DomainLevelNameSearch.create();
         sc.setParameters("aclType", ControlledEntity.ACLType.Domain);
         sc.setParameters("name", affinityGroupName);
@@ -145,7 +144,7 @@ public class AffinityGroupDaoImpl extends GenericDaoBase<AffinityGroupVO, Long>
     }
 
     @Override
-    public AffinityGroup findByAccountAndType(Long accountId, String type) {
+    public AffinityGroupVO findByAccountAndType(Long accountId, String type) {
         SearchCriteria<AffinityGroupVO> sc = AccountIdTypeSearch.create();
         sc.setParameters("accountId", accountId);
         sc.setParameters("type", type);
@@ -154,7 +153,7 @@ public class AffinityGroupDaoImpl extends GenericDaoBase<AffinityGroupVO, Long>
     }
 
     @Override
-    public AffinityGroup findDomainLevelGroupByType(Long domainId, String type) {
+    public AffinityGroupVO findDomainLevelGroupByType(Long domainId, String type) {
         SearchCriteria<AffinityGroupVO> sc = DomainLevelTypeSearch.create();
         sc.setParameters("aclType", ControlledEntity.ACLType.Domain);
         sc.setParameters("type", type);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c76d3171/plugins/dedicated-resources/src/org/apache/cloudstack/dedicated/DedicatedResourceManagerImpl.java
----------------------------------------------------------------------
diff --git a/plugins/dedicated-resources/src/org/apache/cloudstack/dedicated/DedicatedResourceManagerImpl.java b/plugins/dedicated-resources/src/org/apache/cloudstack/dedicated/DedicatedResourceManagerImpl.java
index 1e584c3..35bcfc6 100644
--- a/plugins/dedicated-resources/src/org/apache/cloudstack/dedicated/DedicatedResourceManagerImpl.java
+++ b/plugins/dedicated-resources/src/org/apache/cloudstack/dedicated/DedicatedResourceManagerImpl.java
@@ -639,7 +639,7 @@ public class DedicatedResourceManagerImpl implements DedicatedService {
             affinityGroupName = "DedicatedGrp-domain-" + domainName;
         }
 
-        group = _affinityGroupService.createAffinityGroupInternal(accountName, domainId, affinityGroupName, "ExplicitDedication", "dedicated resources group");
+        group = _affinityGroupService.createAffinityGroup(accountName, null, domainId, affinityGroupName, "ExplicitDedication", "dedicated resources group");
 
         return group;
 
@@ -948,7 +948,7 @@ public class DedicatedResourceManagerImpl implements DedicatedService {
             List<DedicatedResourceVO> resourcesInGroup = _dedicatedDao.listByAffinityGroupId(resource.getAffinityGroupId());
             if (resourcesInGroup.isEmpty()) {
                 // delete the group
-                _affinityGroupService.deleteAffinityGroup(resource.getAffinityGroupId(), null, null, null);
+                _affinityGroupService.deleteAffinityGroup(resource.getAffinityGroupId(), null, null, null, null);
             }
 
         }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c76d3171/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/IntegrationTestConfiguration.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/IntegrationTestConfiguration.java b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/IntegrationTestConfiguration.java
index 954a37e..77abb65 100644
--- a/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/IntegrationTestConfiguration.java
+++ b/plugins/network-elements/juniper-contrail/test/org/apache/cloudstack/network/contrail/management/IntegrationTestConfiguration.java
@@ -389,7 +389,7 @@ public class IntegrationTestConfiguration {
                 }
             });
             Mockito.when(
-                mock.createAffinityGroupInternal(Matchers.any(String.class), Matchers.any(Long.class), Matchers.any(String.class), Matchers.any(String.class),
+                mock.createAffinityGroup(Matchers.any(String.class), Matchers.any(Long.class), Matchers.any(Long.class), Matchers.any(String.class), Matchers.any(String.class),
                     Matchers.any(String.class))).thenReturn(gmock);
         } catch (Exception e) {
             e.printStackTrace();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c76d3171/server/src/com/cloud/acl/AffinityGroupAccessChecker.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/acl/AffinityGroupAccessChecker.java b/server/src/com/cloud/acl/AffinityGroupAccessChecker.java
index 57f7b37..c836aea 100644
--- a/server/src/com/cloud/acl/AffinityGroupAccessChecker.java
+++ b/server/src/com/cloud/acl/AffinityGroupAccessChecker.java
@@ -19,17 +19,19 @@ package com.cloud.acl;
 import javax.ejb.Local;
 import javax.inject.Inject;
 
-import org.springframework.stereotype.Component;
-
 import org.apache.cloudstack.acl.ControlledEntity;
 import org.apache.cloudstack.acl.ControlledEntity.ACLType;
 import org.apache.cloudstack.acl.SecurityChecker;
 import org.apache.cloudstack.affinity.AffinityGroup;
 import org.apache.cloudstack.affinity.AffinityGroupService;
 import org.apache.cloudstack.affinity.dao.AffinityGroupDomainMapDao;
+import org.springframework.stereotype.Component;
 
 import com.cloud.domain.DomainVO;
 import com.cloud.exception.PermissionDeniedException;
+import com.cloud.projects.ProjectVO;
+import com.cloud.projects.dao.ProjectAccountDao;
+import com.cloud.projects.dao.ProjectDao;
 import com.cloud.user.Account;
 import com.cloud.user.AccountManager;
 import com.cloud.utils.exception.CloudRuntimeException;
@@ -44,6 +46,10 @@ public class AffinityGroupAccessChecker extends DomainChecker {
     AccountManager _accountMgr;
     @Inject
     AffinityGroupDomainMapDao _affinityGroupDomainMapDao;
+    @Inject
+    ProjectDao _projectDao;
+    @Inject
+    ProjectAccountDao _projectAccountDao;
 
     @Override
     public boolean checkAccess(Account caller, ControlledEntity entity, AccessType accessType) throws PermissionDeniedException {
@@ -51,8 +57,7 @@ public class AffinityGroupAccessChecker extends DomainChecker {
             AffinityGroup group = (AffinityGroup)entity;
 
             if (_affinityGroupService.isAdminControlledGroup(group)) {
-                if (accessType != null && accessType == AccessType.OperateEntry
-                        && !_accountMgr.isRootAdmin(caller.getId())) {
+                if (accessType == AccessType.OperateEntry && !_accountMgr.isRootAdmin(caller.getId())) {
                     throw new PermissionDeniedException(caller + " does not have permission to operate with resource "
                             + entity);
                 }
@@ -72,6 +77,15 @@ public class AffinityGroupAccessChecker extends DomainChecker {
             } else {
                 //acl_type account
                 if (caller.getId() != group.getAccountId()) {
+                  //check if the group belongs to a project
+                    ProjectVO project = _projectDao.findByProjectAccountId(group.getAccountId());
+                    if (project != null) {
+                        if (AccessType.ModifyProject.equals(accessType) && _projectAccountDao.canModifyProjectAccount(caller.getId(), group.getAccountId())) {
+                            return true;
+                        } else if (!AccessType.ModifyProject.equals(accessType) && _projectAccountDao.canAccessProjectAccount(caller.getId(), group.getAccountId())) {
+                            return true;
+                        }
+                    }
                     throw new PermissionDeniedException(caller + " does not have permission to operate with resource " + entity);
                 } else {
                     return true;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c76d3171/server/src/com/cloud/api/query/QueryManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/query/QueryManagerImpl.java b/server/src/com/cloud/api/query/QueryManagerImpl.java
index f853b67..d64b2ac 100644
--- a/server/src/com/cloud/api/query/QueryManagerImpl.java
+++ b/server/src/com/cloud/api/query/QueryManagerImpl.java
@@ -26,9 +26,6 @@ import java.util.Set;
 import javax.ejb.Local;
 import javax.inject.Inject;
 
-import com.cloud.utils.StringUtils;
-import com.cloud.vm.VMInstanceVO;
-import com.cloud.vm.dao.VMInstanceDao;
 import org.apache.cloudstack.acl.ControlledEntity.ACLType;
 import org.apache.cloudstack.affinity.AffinityGroupDomainMapVO;
 import org.apache.cloudstack.affinity.AffinityGroupResponse;
@@ -57,6 +54,7 @@ import org.apache.cloudstack.api.command.admin.volume.ListVolumesCmdByAdmin;
 import org.apache.cloudstack.api.command.admin.zone.ListZonesCmdByAdmin;
 import org.apache.cloudstack.api.command.user.account.ListAccountsCmd;
 import org.apache.cloudstack.api.command.user.account.ListProjectAccountsCmd;
+import org.apache.cloudstack.api.command.user.affinitygroup.ListAffinityGroupsCmd;
 import org.apache.cloudstack.api.command.user.event.ListEventsCmd;
 import org.apache.cloudstack.api.command.user.iso.ListIsosCmd;
 import org.apache.cloudstack.api.command.user.job.ListAsyncJobsCmd;
@@ -196,7 +194,6 @@ import com.cloud.storage.Storage.TemplateType;
 import com.cloud.storage.VMTemplateVO;
 import com.cloud.storage.Volume;
 import com.cloud.storage.dao.VMTemplateDao;
-import com.cloud.storage.dao.VolumeDetailsDao;
 import com.cloud.tags.ResourceTagVO;
 import com.cloud.tags.dao.ResourceTagDao;
 import com.cloud.template.VirtualMachineTemplate.State;
@@ -207,6 +204,7 @@ import com.cloud.user.DomainManager;
 import com.cloud.user.dao.AccountDao;
 import com.cloud.utils.DateUtil;
 import com.cloud.utils.Pair;
+import com.cloud.utils.StringUtils;
 import com.cloud.utils.Ternary;
 import com.cloud.utils.component.ManagerBase;
 import com.cloud.utils.db.Filter;
@@ -217,11 +215,12 @@ import com.cloud.utils.db.SearchCriteria.Func;
 import com.cloud.utils.db.SearchCriteria.Op;
 import com.cloud.vm.DomainRouterVO;
 import com.cloud.vm.UserVmVO;
+import com.cloud.vm.VMInstanceVO;
 import com.cloud.vm.VirtualMachine;
 import com.cloud.vm.dao.DomainRouterDao;
-import com.cloud.vm.dao.NicDetailsDao;
 import com.cloud.vm.dao.UserVmDao;
 import com.cloud.vm.dao.UserVmDetailsDao;
+import com.cloud.vm.dao.VMInstanceDao;
 
 @Component
 @Local(value = {QueryService.class})
@@ -229,6 +228,8 @@ public class QueryManagerImpl extends ManagerBase implements QueryService, Confi
 
     public static final Logger s_logger = Logger.getLogger(QueryManagerImpl.class);
 
+    private static final String ID_FIELD = "id";
+
     @Inject
     private AccountManager _accountMgr;
 
@@ -332,12 +333,6 @@ public class QueryManagerImpl extends ManagerBase implements QueryService, Confi
     private DomainRouterDao _routerDao;
 
     @Inject
-    private VolumeDetailsDao _volumeDetailDao;
-
-    @Inject
-    private NicDetailsDao _nicDetailDao;
-
-    @Inject
     UserVmDetailsDao _userVmDetailDao;
 
     @Inject
@@ -375,11 +370,11 @@ public class QueryManagerImpl extends ManagerBase implements QueryService, Confi
     @Inject
     AffinityGroupDomainMapDao _affinityGroupDomainMapDao;
 
-
     @Inject NetworkDetailsDao _networkDetailsDao;
 
     @Inject
     ResourceTagDao _resourceTagDao;
+
     @Inject
     DataStoreManager dataStoreManager;
 
@@ -3395,55 +3390,60 @@ public class QueryManagerImpl extends ManagerBase implements QueryService, Confi
                 cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags, showRemovedISO);
     }
 
-
     @Override
-    public ListResponse<AffinityGroupResponse> listAffinityGroups(Long affinityGroupId, String affinityGroupName,
-            String affinityGroupType, Long vmId, String accountName, Long domainId, boolean isRecursive,
-            boolean listAll, Long startIndex, Long pageSize, String keyword) {
-        Pair<List<AffinityGroupJoinVO>, Integer> result = listAffinityGroupsInternal(affinityGroupId,
-                affinityGroupName, affinityGroupType, vmId, accountName, domainId, isRecursive, listAll, startIndex,
-                pageSize, keyword);
+    public ListResponse<AffinityGroupResponse> searchForAffinityGroups(ListAffinityGroupsCmd cmd) {
+        Pair<List<AffinityGroupJoinVO>, Integer> result = searchForAffinityGroupsInternal(cmd);
         ListResponse<AffinityGroupResponse> response = new ListResponse<AffinityGroupResponse>();
         List<AffinityGroupResponse> agResponses = ViewResponseHelper.createAffinityGroupResponses(result.first());
         response.setResponses(agResponses, result.second());
         return response;
     }
 
-    public Pair<List<AffinityGroupJoinVO>, Integer> listAffinityGroupsInternal(Long affinityGroupId,
-            String affinityGroupName, String affinityGroupType, Long vmId, String accountName, Long domainId,
-            boolean isRecursive, boolean listAll, Long startIndex, Long pageSize, String keyword) {
+    public Pair<List<AffinityGroupJoinVO>, Integer> searchForAffinityGroupsInternal(ListAffinityGroupsCmd cmd) {
 
-        Account caller = CallContext.current().getCallingAccount();
+        final Long affinityGroupId = cmd.getId();
+        final String affinityGroupName = cmd.getAffinityGroupName();
+        final String affinityGroupType = cmd.getAffinityGroupType();
+        final Long vmId = cmd.getVirtualMachineId();
+        final String accountName = cmd.getAccountName();
+        Long domainId = cmd.getDomainId();
+        final Long projectId = cmd.getProjectId();
+        Boolean isRecursive = cmd.isRecursive();
+        final Boolean listAll = cmd.listAll();
+        final Long startIndex = cmd.getStartIndex();
+        final Long pageSize = cmd.getPageSizeVal();
+        final String keyword = cmd.getKeyword();
 
-        caller.getAccountId();
+        Account caller = CallContext.current().getCallingAccount();
 
         if (vmId != null) {
             UserVmVO userVM = _userVmDao.findById(vmId);
             if (userVM == null) {
-                throw new InvalidParameterValueException("Unable to list affinity groups for virtual machine instance "
-                        + vmId + "; instance not found.");
+                throw new InvalidParameterValueException("Unable to list affinity groups for virtual machine instance " + vmId + "; instance not found.");
             }
             _accountMgr.checkAccess(caller, null, true, userVM);
             return listAffinityGroupsByVM(vmId.longValue(), startIndex, pageSize);
         }
 
         List<Long> permittedAccounts = new ArrayList<Long>();
-        Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
-                domainId, isRecursive, null);
-        _accountMgr.buildACLSearchParameters(caller, affinityGroupId, accountName, null, permittedAccounts,
-                domainIdRecursiveListProject, listAll, true);
-        domainId = domainIdRecursiveListProject.first();
-        isRecursive = domainIdRecursiveListProject.second();
-        ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
+        Ternary<Long, Boolean, ListProjectResourcesCriteria> ternary = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(domainId, isRecursive, null);
+
+        _accountMgr.buildACLSearchParameters(caller, affinityGroupId, accountName, projectId, permittedAccounts, ternary, listAll, false);
+
+        domainId = ternary.first();
+        isRecursive = ternary.second();
+        ListProjectResourcesCriteria listProjectResourcesCriteria = ternary.third();
+
+        Filter searchFilter = new Filter(AffinityGroupJoinVO.class, ID_FIELD, true, startIndex, pageSize);
 
-        Filter searchFilter = new Filter(AffinityGroupJoinVO.class, "id", true, startIndex, pageSize);
-        SearchCriteria<AffinityGroupJoinVO> sc = buildAffinityGroupSearchCriteria(domainId, isRecursive,
-                permittedAccounts, listProjectResourcesCriteria, affinityGroupId, affinityGroupName, affinityGroupType, keyword);
+        SearchCriteria<AffinityGroupJoinVO> sc = buildAffinityGroupSearchCriteria(domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria, affinityGroupId,
+                affinityGroupName, affinityGroupType, keyword);
+
+        Pair<List<AffinityGroupJoinVO>, Integer> uniqueGroupsPair = _affinityGroupJoinDao.searchAndCount(sc, searchFilter);
 
-        Pair<List<AffinityGroupJoinVO>, Integer> uniqueGroupsPair = _affinityGroupJoinDao.searchAndCount(sc,
-                searchFilter);
         // search group details by ids
-        List<AffinityGroupJoinVO> vrs = new ArrayList<AffinityGroupJoinVO>();
+        List<AffinityGroupJoinVO> affinityGroups = new ArrayList<AffinityGroupJoinVO>();
+
         Integer count = uniqueGroupsPair.second();
         if (count.intValue() != 0) {
             List<AffinityGroupJoinVO> uniqueGroups = uniqueGroupsPair.first();
@@ -3452,36 +3452,33 @@ public class QueryManagerImpl extends ManagerBase implements QueryService, Confi
             for (AffinityGroupJoinVO v : uniqueGroups) {
                 vrIds[i++] = v.getId();
             }
-            vrs = _affinityGroupJoinDao.searchByIds(vrIds);
+            affinityGroups = _affinityGroupJoinDao.searchByIds(vrIds);
         }
 
         if (!permittedAccounts.isEmpty()) {
             // add domain level affinity groups
             if (domainId != null) {
-                SearchCriteria<AffinityGroupJoinVO> scDomain = buildAffinityGroupSearchCriteria(null, isRecursive,
-                        new ArrayList<Long>(), listProjectResourcesCriteria, affinityGroupId, affinityGroupName,
-                        affinityGroupType, keyword);
-                vrs.addAll(listDomainLevelAffinityGroups(scDomain, searchFilter, domainId));
+                SearchCriteria<AffinityGroupJoinVO> scDomain = buildAffinityGroupSearchCriteria(null, isRecursive, new ArrayList<Long>(), listProjectResourcesCriteria,
+                        affinityGroupId, affinityGroupName, affinityGroupType, keyword);
+                affinityGroups.addAll(listDomainLevelAffinityGroups(scDomain, searchFilter, domainId));
             } else {
 
                 for (Long permAcctId : permittedAccounts) {
                     Account permittedAcct = _accountDao.findById(permAcctId);
-                    SearchCriteria<AffinityGroupJoinVO> scDomain = buildAffinityGroupSearchCriteria(
-                            null, isRecursive, new ArrayList<Long>(),
-                            listProjectResourcesCriteria, affinityGroupId, affinityGroupName, affinityGroupType, keyword);
+                    SearchCriteria<AffinityGroupJoinVO> scDomain = buildAffinityGroupSearchCriteria(null, isRecursive, new ArrayList<Long>(), listProjectResourcesCriteria,
+                            affinityGroupId, affinityGroupName, affinityGroupType, keyword);
 
-                    vrs.addAll(listDomainLevelAffinityGroups(scDomain, searchFilter, permittedAcct.getDomainId()));
+                    affinityGroups.addAll(listDomainLevelAffinityGroups(scDomain, searchFilter, permittedAcct.getDomainId()));
                 }
             }
         } else if (((permittedAccounts.isEmpty()) && (domainId != null) && isRecursive)) {
             // list all domain level affinity groups for the domain admin case
-            SearchCriteria<AffinityGroupJoinVO> scDomain = buildAffinityGroupSearchCriteria(null, isRecursive,
-                    new ArrayList<Long>(), listProjectResourcesCriteria, affinityGroupId, affinityGroupName,
-                    affinityGroupType, keyword);
-            vrs.addAll(listDomainLevelAffinityGroups(scDomain, searchFilter, domainId));
+            SearchCriteria<AffinityGroupJoinVO> scDomain = buildAffinityGroupSearchCriteria(null, isRecursive, new ArrayList<Long>(), listProjectResourcesCriteria,
+                    affinityGroupId, affinityGroupName, affinityGroupType, keyword);
+            affinityGroups.addAll(listDomainLevelAffinityGroups(scDomain, searchFilter, domainId));
         }
 
-        return new Pair<List<AffinityGroupJoinVO>, Integer>(vrs, vrs.size());
+        return new Pair<List<AffinityGroupJoinVO>, Integer>(affinityGroups, affinityGroups.size());
 
     }
 
@@ -3526,9 +3523,8 @@ public class QueryManagerImpl extends ManagerBase implements QueryService, Confi
         }
     }
 
-    private SearchCriteria<AffinityGroupJoinVO> buildAffinityGroupSearchCriteria(Long domainId, boolean isRecursive,
-            List<Long> permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria,
-            Long affinityGroupId, String affinityGroupName, String affinityGroupType, String keyword) {
+    private SearchCriteria<AffinityGroupJoinVO> buildAffinityGroupSearchCriteria(Long domainId, boolean isRecursive, List<Long> permittedAccounts,
+            ListProjectResourcesCriteria listProjectResourcesCriteria, Long affinityGroupId, String affinityGroupName, String affinityGroupType, String keyword) {
 
         SearchBuilder<AffinityGroupJoinVO> groupSearch = _affinityGroupJoinDao.createSearchBuilder();
         buildAffinityGroupViewSearchBuilder(groupSearch, domainId, isRecursive, permittedAccounts,
@@ -3538,8 +3534,7 @@ public class QueryManagerImpl extends ManagerBase implements QueryService, Confi
         // distinct
 
         SearchCriteria<AffinityGroupJoinVO> sc = groupSearch.create();
-        buildAffinityGroupViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts,
-                listProjectResourcesCriteria);
+        buildAffinityGroupViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
 
         if (affinityGroupId != null) {
             sc.addAnd("id", SearchCriteria.Op.EQ, affinityGroupId);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c76d3171/server/src/com/cloud/api/query/vo/AffinityGroupJoinVO.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/query/vo/AffinityGroupJoinVO.java b/server/src/com/cloud/api/query/vo/AffinityGroupJoinVO.java
index bcd0fdc..380ad66 100644
--- a/server/src/com/cloud/api/query/vo/AffinityGroupJoinVO.java
+++ b/server/src/com/cloud/api/query/vo/AffinityGroupJoinVO.java
@@ -72,6 +72,15 @@ public class AffinityGroupJoinVO extends BaseViewVO implements ControlledViewEnt
     @Column(name = "domain_path")
     private String domainPath = null;
 
+    @Column(name = "project_id")
+    private long projectId;
+
+    @Column(name = "project_uuid")
+    private String projectUuid;
+
+    @Column(name = "project_name")
+    private String projectName;
+
     @Column(name = "vm_id")
     private long vmId;
 
@@ -153,6 +162,20 @@ public class AffinityGroupJoinVO extends BaseViewVO implements ControlledViewEnt
         return domainPath;
     }
 
+    public long getProjectId() {
+        return projectId;
+    }
+
+    @Override
+    public String getProjectUuid() {
+        return projectUuid;
+    }
+
+    @Override
+    public String getProjectName() {
+        return projectName;
+    }
+
     public String getDescription() {
         return description;
     }
@@ -177,18 +200,6 @@ public class AffinityGroupJoinVO extends BaseViewVO implements ControlledViewEnt
         return vmState;
     }
 
-    @Override
-    public String getProjectUuid() {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public String getProjectName() {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
     public ControlledEntity.ACLType getAclType() {
         return aclType;
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c76d3171/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
index 69e70e6..3a8c77d 100644
--- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
+++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
@@ -1484,7 +1484,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
                         final List<DedicatedResourceVO> resourcesInGroup = _dedicatedDao.listByAffinityGroupId(dr.getAffinityGroupId());
                         if (resourcesInGroup.isEmpty()) {
                             // delete the group
-                            _affinityGroupService.deleteAffinityGroup(dr.getAffinityGroupId(), null, null, null);
+                            _affinityGroupService.deleteAffinityGroup(dr.getAffinityGroupId(), null, null, null, null);
                         }
                     }
                 }
@@ -1702,7 +1702,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
                         final List<DedicatedResourceVO> resourcesInGroup = _dedicatedDao.listByAffinityGroupId(resource.getAffinityGroupId());
                         if (resourcesInGroup.isEmpty()) {
                             // delete the group
-                            _affinityGroupService.deleteAffinityGroup(resource.getAffinityGroupId(), null, null, null);
+                            _affinityGroupService.deleteAffinityGroup(resource.getAffinityGroupId(), null, null, null, null);
                         }
                     }
                 }
@@ -1800,7 +1800,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
             }
         }
 
-        group = _affinityGroupService.createAffinityGroupInternal(accountName, domainId, affinityGroupName, "ExplicitDedication", "dedicated resources group");
+        group = _affinityGroupService.createAffinityGroup(accountName, null, domainId, affinityGroupName, "ExplicitDedication", "dedicated resources group");
 
         return group;
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c76d3171/server/src/com/cloud/user/AccountManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/user/AccountManagerImpl.java b/server/src/com/cloud/user/AccountManagerImpl.java
index 8f3a1b2..ead7735 100644
--- a/server/src/com/cloud/user/AccountManagerImpl.java
+++ b/server/src/com/cloud/user/AccountManagerImpl.java
@@ -2406,98 +2406,10 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
         }
     }
 
-//    @Override
-//    public void buildACLSearchParameters(Account caller, Long id, String accountName, Long projectId, List<Long>
-//    permittedAccounts, Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject,
-//            boolean listAll, boolean forProjectInvitation) {
-//        Long domainId = domainIdRecursiveListProject.first();
-//        if (domainId != null) {
-//            Domain domain = _domainDao.findById(domainId);
-//            if (domain == null) {
-//                throw new InvalidParameterValueException("Unable to find domain by id " + domainId);
-//            }
-//            // check permissions
-//            checkAccess(caller, domain);
-//        }
-//
-//        if (accountName != null) {
-//            if (projectId != null) {
-//                throw new InvalidParameterValueException("Account and projectId can't be specified together");
-//            }
-//
-//            Account userAccount = null;
-//            Domain domain = null;
-//            if (domainId != null) {
-//                userAccount = _accountDao.findActiveAccount(accountName, domainId);
-//                domain = _domainDao.findById(domainId);
-//            } else {
-//                userAccount = _accountDao.findActiveAccount(accountName, caller.getDomainId());
-//                domain = _domainDao.findById(caller.getDomainId());
-//            }
-//
-//            if (userAccount != null) {
-//                checkAccess(caller, null, false, userAccount);
-//                //check permissions
-//                permittedAccounts.add(userAccount.getId());
-//            } else {
-//                throw new InvalidParameterValueException("could not find account " + accountName + " in domain " + domain.getUuid());
-//            }
-//        }
-//
-//        // set project information
-//        if (projectId != null) {
-//            if (!forProjectInvitation) {
-//                if (projectId.longValue() == -1) {
-//                    if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
-//                        permittedAccounts.addAll(_projectMgr.listPermittedProjectAccounts(caller.getId()));
-//                    } else {
-//                        domainIdRecursiveListProject.third(Project.ListProjectResourcesCriteria.ListProjectResourcesOnly);
-//                    }
-//                } else {
-//                    Project project = _projectMgr.getProject(projectId);
-//                    if (project == null) {
-//                        throw new InvalidParameterValueException("Unable to find project by id " + projectId);
-//                    }
-//                    if (!_projectMgr.canAccessProjectAccount(caller, project.getProjectAccountId())) {
-//                        throw new PermissionDeniedException("Account " + caller + " can't access project id=" + projectId);
-//                    }
-//                    permittedAccounts.add(project.getProjectAccountId());
-//                }
-//            }
-//        } else {
-//            if (id == null) {
-//                domainIdRecursiveListProject.third(Project.ListProjectResourcesCriteria.SkipProjectResources);
-//            }
-//            if (permittedAccounts.isEmpty() && domainId == null) {
-//                if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
-//                    permittedAccounts.add(caller.getId());
-//                } else if (!listAll) {
-//                    if (id == null) {
-//                        permittedAccounts.add(caller.getId());
-//                    } else if (!isRootAdmin(caller.getId())) {
-//                        domainIdRecursiveListProject.first(caller.getDomainId());
-//                        domainIdRecursiveListProject.second(true);
-//                    }
-//                } else if (domainId == null) {
-//                    if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) {
-//                        domainIdRecursiveListProject.first(caller.getDomainId());
-//                        domainIdRecursiveListProject.second(true);
-//                    }
-//                }
-//            } else if (domainId != null) {
-//                if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
-//                    permittedAccounts.add(caller.getId());
-//                }
-//            }
-//
-//        }
-//    }
-
     //TODO: deprecate this to use the new buildACLSearchParameters with permittedDomains, permittedAccounts, and permittedResources as return
     @Override
-    public void buildACLSearchParameters(Account caller, Long id, String accountName, Long projectId, List<Long>
-    permittedAccounts, Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject,
-            boolean listAll, boolean forProjectInvitation) {
+    public void buildACLSearchParameters(Account caller, Long id, String accountName, Long projectId, List<Long> permittedAccounts,
+            Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject, boolean listAll, boolean forProjectInvitation) {
         Long domainId = domainIdRecursiveListProject.first();
         if (domainId != null) {
             Domain domain = _domainDao.findById(domainId);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c76d3171/server/src/org/apache/cloudstack/affinity/AffinityGroupServiceImpl.java
----------------------------------------------------------------------
diff --git a/server/src/org/apache/cloudstack/affinity/AffinityGroupServiceImpl.java b/server/src/org/apache/cloudstack/affinity/AffinityGroupServiceImpl.java
index d25bddb..5da1f88 100644
--- a/server/src/org/apache/cloudstack/affinity/AffinityGroupServiceImpl.java
+++ b/server/src/org/apache/cloudstack/affinity/AffinityGroupServiceImpl.java
@@ -27,8 +27,8 @@ import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
 import com.cloud.utils.fsm.StateMachine2;
-import org.apache.log4j.Logger;
 
+import org.apache.log4j.Logger;
 import org.apache.cloudstack.acl.ControlledEntity;
 import org.apache.cloudstack.acl.ControlledEntity.ACLType;
 import org.apache.cloudstack.acl.SecurityChecker.AccessType;
@@ -36,6 +36,7 @@ import org.apache.cloudstack.affinity.dao.AffinityGroupDao;
 import org.apache.cloudstack.affinity.dao.AffinityGroupDomainMapDao;
 import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDao;
 import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.command.user.affinitygroup.CreateAffinityGroupCmd;
 import org.apache.cloudstack.context.CallContext;
 import org.apache.cloudstack.framework.messagebus.MessageBus;
 import org.apache.cloudstack.framework.messagebus.PublishScope;
@@ -55,8 +56,6 @@ import com.cloud.utils.component.Manager;
 import com.cloud.utils.component.ManagerBase;
 import com.cloud.utils.db.DB;
 import com.cloud.utils.db.EntityManager;
-import com.cloud.utils.db.Filter;
-import com.cloud.utils.db.JoinBuilder;
 import com.cloud.utils.db.SearchBuilder;
 import com.cloud.utils.db.SearchCriteria;
 import com.cloud.utils.db.Transaction;
@@ -113,48 +112,29 @@ public class AffinityGroupServiceImpl extends ManagerBase implements AffinityGro
     @DB
     @Override
     @ActionEvent(eventType = EventTypes.EVENT_AFFINITY_GROUP_CREATE, eventDescription = "Creating Affinity Group", create = true)
-    public AffinityGroup createAffinityGroup(String account, Long domainId, String affinityGroupName, String affinityGroupType, String description) {
-
-        Account caller = CallContext.current().getCallingAccount();
-
-        //validate the affinityGroupType
-        Map<String, AffinityGroupProcessor> typeProcessorMap = getAffinityTypeToProcessorMap();
-        if (typeProcessorMap != null && !typeProcessorMap.isEmpty()) {
-            if (!typeProcessorMap.containsKey(affinityGroupType)) {
-                throw new InvalidParameterValueException("Unable to create affinity group, invalid affinity group type" + affinityGroupType);
-            }
-        } else {
-            throw new InvalidParameterValueException("Unable to create affinity group, no Affinity Group Types configured");
-        }
-
-        AffinityGroupProcessor processor = typeProcessorMap.get(affinityGroupType);
-
-        if (processor.isAdminControlledGroup()) {
-            throw new PermissionDeniedException("Cannot create the affinity group");
-        }
-
-        return createAffinityGroupInternal(account, domainId, affinityGroupName, affinityGroupType, description);
+    public AffinityGroup createAffinityGroup(CreateAffinityGroupCmd createAffinityGroupCmd) {
+        return createAffinityGroup(createAffinityGroupCmd.getAccountName(), createAffinityGroupCmd.getProjectId(), createAffinityGroupCmd.getDomainId(), createAffinityGroupCmd.getAffinityGroupName(), createAffinityGroupCmd.getAffinityGroupType(), createAffinityGroupCmd.getDescription());
     }
 
     @DB
     @Override
-    public AffinityGroup createAffinityGroupInternal(String account, final Long domainId, final String affinityGroupName, final String affinityGroupType,
+    public AffinityGroup createAffinityGroup(final String accountName, final Long projectId, final Long domainId, final String affinityGroupName, final String affinityGroupType,
         final String description) {
 
-        Account caller = CallContext.current().getCallingAccount();
-
         // validate the affinityGroupType
         Map<String, AffinityGroupProcessor> typeProcessorMap = getAffinityTypeToProcessorMap();
-        if (typeProcessorMap != null && !typeProcessorMap.isEmpty()) {
-            if (!typeProcessorMap.containsKey(affinityGroupType)) {
-                throw new InvalidParameterValueException("Unable to create affinity group, invalid affinity group type" + affinityGroupType);
-            }
-        } else {
+
+        if (typeProcessorMap == null || typeProcessorMap.isEmpty()) {
             throw new InvalidParameterValueException("Unable to create affinity group, no Affinity Group Types configured");
         }
 
-        final AffinityGroupProcessor processor = typeProcessorMap.get(affinityGroupType);
+        AffinityGroupProcessor processor = typeProcessorMap.get(affinityGroupType);
+
+        if(processor == null){
+            throw new InvalidParameterValueException("Unable to create affinity group, invalid affinity group type" + affinityGroupType);
+        }
 
+        Account caller = CallContext.current().getCallingAccount();
         if (processor.isAdminControlledGroup() && !_accountMgr.isRootAdmin(caller.getId())) {
             throw new PermissionDeniedException("Cannot create the affinity group");
         }
@@ -163,64 +143,60 @@ public class AffinityGroupServiceImpl extends ManagerBase implements AffinityGro
         Account owner = null;
         boolean domainLevel = false;
 
-        if (account != null && domainId != null) {
-
-            owner = _accountMgr.finalizeOwner(caller, account, domainId, null);
-            aclType = ControlledEntity.ACLType.Account;
-
-        } else if (domainId != null && account == null) {
-
-            if (!_accountMgr.isRootAdmin(caller.getId())) {
-                // non root admin need to pass both account and domain
-                throw new InvalidParameterValueException("Unable to create affinity group, account name must be passed with the domainId");
-            } else if (!processor.canBeSharedDomainWide()) {
-                // cannot be domain level
-                throw new InvalidParameterValueException("Unable to create affinity group, account name is needed");
-            }
-
-            DomainVO domain = _domainDao.findById(domainId);
-            if (domain == null) {
-                throw new InvalidParameterValueException("Unable to find domain by specified id");
-            }
+        if (projectId == null && domainId != null && accountName == null) {
+            verifyAccessToDomainWideProcessor(caller, processor);
+            DomainVO domain = getDomain(domainId);
             _accountMgr.checkAccess(caller, domain);
 
             // domain level group, owner is SYSTEM.
             owner = _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM);
             aclType = ControlledEntity.ACLType.Domain;
             domainLevel = true;
-
         } else {
-            owner = caller;
+            owner = _accountMgr.finalizeOwner(caller, accountName, domainId, projectId);
             aclType = ControlledEntity.ACLType.Account;
         }
 
-        if (_affinityGroupDao.isNameInUse(owner.getAccountId(), owner.getDomainId(), affinityGroupName)) {
-            throw new InvalidParameterValueException("Unable to create affinity group, a group with name " + affinityGroupName + " already exists.");
+        verifyAffinityGroupNameInUse(owner.getAccountId(), owner.getDomainId(), affinityGroupName);
+        verifyDomainLevelAffinityGroupName(domainLevel, owner.getDomainId(), affinityGroupName);
+
+        AffinityGroupVO group = createAffinityGroup(processor, owner, aclType, affinityGroupName, affinityGroupType, description);
+
+        if (s_logger.isDebugEnabled()) {
+            s_logger.debug("Created affinity group =" + affinityGroupName);
         }
-        if (domainLevel && _affinityGroupDao.findDomainLevelGroupByName(domainId, affinityGroupName) != null) {
-            throw new InvalidParameterValueException("Unable to create affinity group, a group with name " + affinityGroupName + " already exists under the domain.");
+
+        return group;
+    }
+
+    private void verifyAccessToDomainWideProcessor(Account caller, AffinityGroupProcessor processor) {
+        if (!_accountMgr.isRootAdmin(caller.getId())) {
+            throw new InvalidParameterValueException("Unable to create affinity group, account name must be passed with the domainId");
         }
+        if (!processor.canBeSharedDomainWide()) {
+            throw new InvalidParameterValueException("Unable to create affinity group, account name is needed. Affinity group type "+ processor.getType() +" cannot be shared domain wide");
+        }
+    }
 
-        final Account ownerFinal = owner;
-        final ControlledEntity.ACLType aclTypeFinal = aclType;
-        AffinityGroupVO group = Transaction.execute(new TransactionCallback<AffinityGroupVO>() {
+    private AffinityGroupVO createAffinityGroup(final AffinityGroupProcessor processor, final Account owner, final ACLType aclType, final String affinityGroupName, final String affinityGroupType, final String description) {
+        return Transaction.execute(new TransactionCallback<AffinityGroupVO>() {
             @Override
             public AffinityGroupVO doInTransaction(TransactionStatus status) {
                 AffinityGroupVO group =
-                    new AffinityGroupVO(affinityGroupName, affinityGroupType, description, ownerFinal.getDomainId(), ownerFinal.getId(), aclTypeFinal);
+                    new AffinityGroupVO(affinityGroupName, affinityGroupType, description, owner.getDomainId(), owner.getId(), aclType);
                 _affinityGroupDao.persist(group);
 
-                if (domainId != null && aclTypeFinal == ACLType.Domain) {
+                if (aclType == ACLType.Domain) {
                     boolean subDomainAccess = false;
                     subDomainAccess = processor.subDomainAccess();
-                    AffinityGroupDomainMapVO domainMap = new AffinityGroupDomainMapVO(group.getId(), domainId,
+                    AffinityGroupDomainMapVO domainMap = new AffinityGroupDomainMapVO(group.getId(), owner.getDomainId(),
                             subDomainAccess);
                     _affinityGroupDomainMapDao.persist(domainMap);
                     //send event for storing the domain wide resource access
                     Map<String, Object> params = new HashMap<String, Object>();
                     params.put(ApiConstants.ENTITY_TYPE, AffinityGroup.class);
                     params.put(ApiConstants.ENTITY_ID, group.getId());
-                    params.put(ApiConstants.DOMAIN_ID, domainId);
+                    params.put(ApiConstants.DOMAIN_ID, owner.getDomainId());
                     params.put(ApiConstants.SUBDOMAIN_ACCESS, subDomainAccess);
                     _messageBus.publish(_name, EntityManager.MESSAGE_ADD_DOMAIN_WIDE_ENTITY_EVENT, PublishScope.LOCAL,
                             params);
@@ -229,59 +205,99 @@ public class AffinityGroupServiceImpl extends ManagerBase implements AffinityGro
                 return group;
             }
         });
+    }
 
-        if (s_logger.isDebugEnabled()) {
-            s_logger.debug("Created affinity group =" + affinityGroupName);
+    private DomainVO getDomain(Long domainId) {
+        DomainVO domain = _domainDao.findById(domainId);
+        if (domain == null) {
+            throw new InvalidParameterValueException("Unable to find domain by specified id");
         }
+        return domain;
+    }
 
-        return group;
+    private void verifyAffinityGroupNameInUse(long accountId, long domainId, String affinityGroupName) {
+        if (_affinityGroupDao.isNameInUse(accountId, domainId, affinityGroupName)) {
+            throw new InvalidParameterValueException("Unable to create affinity group, a group with name " + affinityGroupName + " already exists.");
+        }
+    }
+
+    private void verifyDomainLevelAffinityGroupName(boolean domainLevel, long domainId, String affinityGroupName) {
+        if (domainLevel && _affinityGroupDao.findDomainLevelGroupByName(domainId, affinityGroupName) != null) {
+            throw new InvalidParameterValueException("Unable to create affinity group, a group with name " + affinityGroupName + " already exists under the domain.");
+        }
     }
 
     @DB
-    @Override
     @ActionEvent(eventType = EventTypes.EVENT_AFFINITY_GROUP_DELETE, eventDescription = "Deleting affinity group")
-    public boolean deleteAffinityGroup(Long affinityGroupId, String account, Long domainId, String affinityGroupName) {
+    public boolean deleteAffinityGroup(Long affinityGroupId, String account, Long projectId, Long domainId, String affinityGroupName) {
+
+        AffinityGroupVO group = getAffinityGroup(affinityGroupId, account, projectId, domainId, affinityGroupName);
 
+        // check permissions
         Account caller = CallContext.current().getCallingAccount();
-        Account owner = _accountMgr.finalizeOwner(caller, account, domainId, null);
+        _accountMgr.checkAccess(caller, AccessType.OperateEntry, true, group);
 
+        final Long affinityGroupIdFinal = group.getId();
+        deleteAffinityGroup(affinityGroupIdFinal);
+
+        // remove its related ACL permission
+        Pair<Class<?>, Long> params = new Pair<Class<?>, Long>(AffinityGroup.class, affinityGroupIdFinal);
+        _messageBus.publish(_name, EntityManager.MESSAGE_REMOVE_ENTITY_EVENT, PublishScope.LOCAL, params);
+
+        if (s_logger.isDebugEnabled()) {
+            s_logger.debug("Deleted affinity group id=" + affinityGroupIdFinal);
+        }
+        return true;
+    }
+
+    private AffinityGroupVO getAffinityGroup(Long affinityGroupId, String account, Long projectId, Long domainId, String affinityGroupName) {
         AffinityGroupVO group = null;
         if (affinityGroupId != null) {
             group = _affinityGroupDao.findById(affinityGroupId);
-            if (group == null) {
-                throw new InvalidParameterValueException("Unable to find affinity group: " + affinityGroupId + "; failed to delete group.");
-            }
         } else if (affinityGroupName != null) {
-            group = _affinityGroupDao.findByAccountAndName(owner.getAccountId(), affinityGroupName);
-            if (group == null) {
-                throw new InvalidParameterValueException("Unable to find affinity group: " + affinityGroupName + "; failed to delete group.");
-            }
+            group = getAffinityGroupByName(account, projectId, domainId, affinityGroupName);
         } else {
             throw new InvalidParameterValueException("Either the affinity group Id or group name must be specified to delete the group");
         }
-        if (affinityGroupId == null) {
-            affinityGroupId = group.getId();
+        if (group == null) {
+                throw new InvalidParameterValueException("Unable to find affinity group " + (affinityGroupId == null ? affinityGroupName : affinityGroupId));
         }
-        // check permissions
-        _accountMgr.checkAccess(caller, AccessType.OperateEntry, true, group);
+        return group;
+    }
+
+    private AffinityGroupVO getAffinityGroupByName(String account, Long projectId, Long domainId, String affinityGroupName) {
+        AffinityGroupVO group = null;
+        if(account == null && domainId != null){
+            group = _affinityGroupDao.findDomainLevelGroupByName(domainId, affinityGroupName);
+        }else{
+            Long accountId = _accountMgr.finalyzeAccountId(account, domainId, projectId, true);
+            if(accountId == null){
+                Account caller = CallContext.current().getCallingAccount();
+                group = _affinityGroupDao.findByAccountAndName(caller.getAccountId(), affinityGroupName);
+            }else{
+                group = _affinityGroupDao.findByAccountAndName(accountId, affinityGroupName);
+            }
+        }
+        return group;
+    }
 
-        final Long affinityGroupIdFinal = affinityGroupId;
+    private void deleteAffinityGroup(final Long affinityGroupId) {
         Transaction.execute(new TransactionCallbackNoReturn() {
             @Override
             public void doInTransactionWithoutResult(TransactionStatus status) {
 
-                AffinityGroupVO group = _affinityGroupDao.lockRow(affinityGroupIdFinal, true);
+                AffinityGroupVO group = _affinityGroupDao.lockRow(affinityGroupId, true);
                 if (group == null) {
-                            throw new InvalidParameterValueException("Unable to find affinity group by id " + affinityGroupIdFinal);
+                    throw new InvalidParameterValueException("Unable to find affinity group by id " + affinityGroupId);
                 }
 
-                List<AffinityGroupVMMapVO> affinityGroupVmMap = _affinityGroupVMMapDao.listByAffinityGroup(affinityGroupIdFinal);
+                List<AffinityGroupVMMapVO> affinityGroupVmMap = _affinityGroupVMMapDao.listByAffinityGroup(affinityGroupId);
                 if (!affinityGroupVmMap.isEmpty()) {
                     SearchBuilder<AffinityGroupVMMapVO> listByAffinityGroup = _affinityGroupVMMapDao.createSearchBuilder();
                             listByAffinityGroup.and("affinityGroupId", listByAffinityGroup.entity().getAffinityGroupId(), SearchCriteria.Op.EQ);
                     listByAffinityGroup.done();
                     SearchCriteria<AffinityGroupVMMapVO> sc = listByAffinityGroup.create();
-                            sc.setParameters("affinityGroupId", affinityGroupIdFinal);
+                            sc.setParameters("affinityGroupId", affinityGroupId);
 
                     _affinityGroupVMMapDao.lockRows(sc, null, true);
                     _affinityGroupVMMapDao.remove(sc);
@@ -293,77 +309,15 @@ public class AffinityGroupServiceImpl extends ManagerBase implements AffinityGro
                     processor.handleDeleteGroup(group);
                 }
 
-                if(_affinityGroupDao.expunge(affinityGroupIdFinal)){
+                if(_affinityGroupDao.expunge(affinityGroupId)){
                     AffinityGroupDomainMapVO groupDomain = _affinityGroupDomainMapDao
-                            .findByAffinityGroup(affinityGroupIdFinal);
+                            .findByAffinityGroup(affinityGroupId);
                     if (groupDomain != null) {
                         _affinityGroupDomainMapDao.remove(groupDomain.getId());
                     }
                 }
             }
         });
-
-        // remove its related ACL permission
-        Pair<Class<?>, Long> params = new Pair<Class<?>, Long>(AffinityGroup.class, affinityGroupIdFinal);
-        _messageBus.publish(_name, EntityManager.MESSAGE_REMOVE_ENTITY_EVENT, PublishScope.LOCAL, params);
-
-        if (s_logger.isDebugEnabled()) {
-            s_logger.debug("Deleted affinity group id=" + affinityGroupId);
-        }
-        return true;
-    }
-
-    @Override
-    public Pair<List<? extends AffinityGroup>, Integer> listAffinityGroups(Long affinityGroupId, String affinityGroupName, String affinityGroupType, Long vmId,
-        Long startIndex, Long pageSize) {
-        Filter searchFilter = new Filter(AffinityGroupVO.class, "id", Boolean.TRUE, startIndex, pageSize);
-
-        Account caller = CallContext.current().getCallingAccount();
-
-        Long accountId = caller.getAccountId();
-        Long domainId = caller.getDomainId();
-
-        SearchBuilder<AffinityGroupVMMapVO> vmInstanceSearch = _affinityGroupVMMapDao.createSearchBuilder();
-        vmInstanceSearch.and("instanceId", vmInstanceSearch.entity().getInstanceId(), SearchCriteria.Op.EQ);
-
-        SearchBuilder<AffinityGroupVO> groupSearch = _affinityGroupDao.createSearchBuilder();
-
-        SearchCriteria<AffinityGroupVO> sc = groupSearch.create();
-
-        if (accountId != null) {
-            sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId);
-        }
-
-        if (domainId != null) {
-            sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
-        }
-
-        if (affinityGroupId != null) {
-            sc.addAnd("id", SearchCriteria.Op.EQ, affinityGroupId);
-        }
-
-        if (affinityGroupName != null) {
-            sc.addAnd("name", SearchCriteria.Op.EQ, affinityGroupName);
-        }
-
-        if (affinityGroupType != null) {
-            sc.addAnd("type", SearchCriteria.Op.EQ, affinityGroupType);
-        }
-
-        if (vmId != null) {
-            UserVmVO userVM = _userVmDao.findById(vmId);
-            if (userVM == null) {
-                throw new InvalidParameterValueException("Unable to list affinity groups for virtual machine instance " + vmId + "; instance not found.");
-            }
-            _accountMgr.checkAccess(caller, null, true, userVM);
-            // add join to affinity_groups_vm_map
-            groupSearch.join("vmInstanceSearch", vmInstanceSearch, groupSearch.entity().getId(), vmInstanceSearch.entity().getAffinityGroupId(),
-                JoinBuilder.JoinType.INNER);
-            sc.setJoinParameters("vmInstanceSearch", "instanceId", vmId);
-        }
-
-        Pair<List<AffinityGroupVO>, Integer> result =  _affinityGroupDao.searchAndCount(sc, searchFilter);
-        return new Pair<List<? extends AffinityGroup>, Integer>(result.first(), result.second());
     }
 
     @Override
@@ -460,7 +414,7 @@ public class AffinityGroupServiceImpl extends ManagerBase implements AffinityGro
         // Verify input parameters
         UserVmVO vmInstance = _userVmDao.findById(vmId);
         if (vmInstance == null) {
-            throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
+            throw new InvalidParameterValueException("Unable to find a virtual machine with id " + vmId);
         }
 
         // Check that the VM is stopped

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c76d3171/server/test/org/apache/cloudstack/affinity/AffinityApiUnitTest.java
----------------------------------------------------------------------
diff --git a/server/test/org/apache/cloudstack/affinity/AffinityApiUnitTest.java b/server/test/org/apache/cloudstack/affinity/AffinityApiUnitTest.java
index 8cf4cdc..354054a 100644
--- a/server/test/org/apache/cloudstack/affinity/AffinityApiUnitTest.java
+++ b/server/test/org/apache/cloudstack/affinity/AffinityApiUnitTest.java
@@ -167,38 +167,39 @@ public class AffinityApiUnitTest {
     @Test
     public void createAffinityGroupTest() {
         when(_groupDao.isNameInUse(anyLong(), anyLong(), eq("group1"))).thenReturn(false);
-        AffinityGroup group = _affinityService.createAffinityGroup("user", domainId, "group1", "mock", "affinity group one");
+        AffinityGroup group = _affinityService.createAffinityGroup("user", null, domainId, "group1", "mock", "affinity group one");
         assertNotNull("Affinity group 'group1' of type 'mock' failed to create ", group);
 
     }
 
     @Test(expected = InvalidParameterValueException.class)
     public void invalidAffinityTypeTest() {
-        AffinityGroup group = _affinityService.createAffinityGroup("user", domainId, "group1", "invalid", "affinity group one");
+        AffinityGroup group = _affinityService.createAffinityGroup("user", null, domainId, "group1", "invalid", "affinity group one");
 
     }
 
     @Test(expected = InvalidParameterValueException.class)
     public void uniqueAffinityNameTest() {
         when(_groupDao.isNameInUse(anyLong(), anyLong(), eq("group1"))).thenReturn(true);
-        AffinityGroup group2 = _affinityService.createAffinityGroup("user", domainId, "group1", "mock", "affinity group two");
+        AffinityGroup group2 = _affinityService.createAffinityGroup("user", null, domainId, "group1", "mock", "affinity group two");
     }
 
     @Test(expected = InvalidParameterValueException.class)
     public void deleteAffinityGroupInvalidIdTest() throws ResourceInUseException {
         when(_groupDao.findById(20L)).thenReturn(null);
-        _affinityService.deleteAffinityGroup(20L, "user", domainId, "group1");
+        _affinityService.deleteAffinityGroup(20L, "user", null, domainId, "group1");
     }
 
     @Test(expected = InvalidParameterValueException.class)
     public void deleteAffinityGroupInvalidIdName() throws ResourceInUseException {
+        when(_acctMgr.finalyzeAccountId("user", domainId, null, true)).thenReturn(200L);
         when(_groupDao.findByAccountAndName(200L, "group1")).thenReturn(null);
-        _affinityService.deleteAffinityGroup(null, "user", domainId, "group1");
+        _affinityService.deleteAffinityGroup(null, "user", null, domainId, "group1");
     }
 
     @Test(expected = InvalidParameterValueException.class)
     public void deleteAffinityGroupNullIdName() throws ResourceInUseException {
-        _affinityService.deleteAffinityGroup(null, "user", domainId, null);
+        _affinityService.deleteAffinityGroup(null, "user", null, domainId, null);
     }
 
     @Test(expected = InvalidParameterValueException.class)


Mime
View raw message