You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by mc...@apache.org on 2014/01/17 23:40:38 UTC

[36/50] [abbrv] Merge branch 'master' into rbac.

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/org/apache/cloudstack/affinity/AffinityGroupServiceImpl.java
----------------------------------------------------------------------
diff --cc server/src/org/apache/cloudstack/affinity/AffinityGroupServiceImpl.java
index ebcdc60,2a6b7d4..2a6951e
--- a/server/src/org/apache/cloudstack/affinity/AffinityGroupServiceImpl.java
+++ b/server/src/org/apache/cloudstack/affinity/AffinityGroupServiceImpl.java
@@@ -1,563 -1,518 +1,518 @@@
 -// Licensed to the Apache Software Foundation (ASF) under one
 -// or more contributor license agreements.  See the NOTICE file
 -// distributed with this work for additional information
 -// regarding copyright ownership.  The ASF licenses this file
 -// to you under the Apache License, Version 2.0 (the
 -// "License"); you may not use this file except in compliance
 -// with the License.  You may obtain a copy of the License at
 -//
 -//   http://www.apache.org/licenses/LICENSE-2.0
 -//
 -// Unless required by applicable law or agreed to in writing,
 -// software distributed under the License is distributed on an
 -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 -// KIND, either express or implied.  See the License for the
 -// specific language governing permissions and limitations
 -// under the License.
 -package org.apache.cloudstack.affinity;
 -
 -import java.util.ArrayList;
 -import java.util.HashMap;
 -import java.util.List;
 -import java.util.Map;
 -import java.util.Set;
 -
 -import javax.ejb.Local;
 -import javax.inject.Inject;
 -import javax.naming.ConfigurationException;
 -
 +// Licensed to the Apache Software Foundation (ASF) under one
 +// or more contributor license agreements.  See the NOTICE file
 +// distributed with this work for additional information
 +// regarding copyright ownership.  The ASF licenses this file
 +// to you under the Apache License, Version 2.0 (the
 +// "License"); you may not use this file except in compliance
 +// with the License.  You may obtain a copy of the License at
 +//
 +//   http://www.apache.org/licenses/LICENSE-2.0
 +//
 +// Unless required by applicable law or agreed to in writing,
 +// software distributed under the License is distributed on an
 +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 +// KIND, either express or implied.  See the License for the
 +// specific language governing permissions and limitations
 +// under the License.
 +package org.apache.cloudstack.affinity;
 +
 +import java.util.ArrayList;
 +import java.util.HashMap;
 +import java.util.List;
 +import java.util.Map;
 +import java.util.Set;
- import java.util.Map.Entry;
 +
 +import javax.ejb.Local;
 +import javax.inject.Inject;
 +import javax.naming.ConfigurationException;
 +
+ 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;
 -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.context.CallContext;
 -
 -import com.cloud.domain.DomainVO;
 -import com.cloud.domain.dao.DomainDao;
 -import com.cloud.event.ActionEvent;
 -import com.cloud.event.EventTypes;
 -import com.cloud.exception.InvalidParameterValueException;
 -import com.cloud.exception.PermissionDeniedException;
 -import com.cloud.user.Account;
 -import com.cloud.user.AccountManager;
 -import com.cloud.user.DomainManager;
 -import com.cloud.uservm.UserVm;
 -import com.cloud.utils.Pair;
 -import com.cloud.utils.component.Manager;
 -import com.cloud.utils.component.ManagerBase;
 -import com.cloud.utils.db.DB;
 -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;
 -import com.cloud.utils.db.TransactionCallback;
 -import com.cloud.utils.db.TransactionCallbackNoReturn;
 -import com.cloud.utils.db.TransactionStatus;
 -import com.cloud.utils.fsm.StateListener;
 -import com.cloud.vm.UserVmVO;
 -import com.cloud.vm.VirtualMachine;
 -import com.cloud.vm.VirtualMachine.Event;
 -import com.cloud.vm.VirtualMachine.State;
 -import com.cloud.vm.dao.UserVmDao;
 -
 +import org.apache.cloudstack.acl.ControlledEntity;
 +import org.apache.cloudstack.acl.ControlledEntity.ACLType;
 +import org.apache.cloudstack.acl.SecurityChecker.AccessType;
 +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.context.CallContext;
- import org.apache.log4j.Logger;
- import org.springframework.context.annotation.Primary;
 +
- 
- 
- 
- 
- 
- 
- 
- import com.cloud.deploy.DeploymentPlanner;
 +import com.cloud.domain.DomainVO;
 +import com.cloud.domain.dao.DomainDao;
 +import com.cloud.event.ActionEvent;
 +import com.cloud.event.EventTypes;
 +import com.cloud.exception.InvalidParameterValueException;
 +import com.cloud.exception.PermissionDeniedException;
- import com.cloud.exception.ResourceInUseException;
- import com.cloud.network.Network;
- import com.cloud.network.dao.NetworkDomainVO;
- import com.cloud.network.security.SecurityGroup;
 +import com.cloud.user.Account;
 +import com.cloud.user.AccountManager;
 +import com.cloud.user.DomainManager;
 +import com.cloud.uservm.UserVm;
 +import com.cloud.utils.Pair;
- import com.cloud.utils.component.ComponentContext;
 +import com.cloud.utils.component.Manager;
 +import com.cloud.utils.component.ManagerBase;
 +import com.cloud.utils.db.DB;
 +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;
 +import com.cloud.utils.db.TransactionCallback;
 +import com.cloud.utils.db.TransactionCallbackNoReturn;
 +import com.cloud.utils.db.TransactionStatus;
- import com.cloud.utils.exception.CloudRuntimeException;
 +import com.cloud.utils.fsm.StateListener;
 +import com.cloud.vm.UserVmVO;
 +import com.cloud.vm.VirtualMachine;
 +import com.cloud.vm.VirtualMachine.Event;
 +import com.cloud.vm.VirtualMachine.State;
 +import com.cloud.vm.dao.UserVmDao;
 +
- @Local(value = { AffinityGroupService.class })
- public class AffinityGroupServiceImpl extends ManagerBase implements AffinityGroupService, Manager,
-         StateListener<State, VirtualMachine.Event, VirtualMachine> {
+ @Local(value = {AffinityGroupService.class})
+ public class AffinityGroupServiceImpl extends ManagerBase implements AffinityGroupService, Manager, StateListener<State, VirtualMachine.Event, VirtualMachine> {
 -
 -    public static final Logger s_logger = Logger.getLogger(AffinityGroupServiceImpl.class);
 -    private String _name;
 -
 -    @Inject
 -    AccountManager _accountMgr;
 -
 -    @Inject
 -    AffinityGroupDao _affinityGroupDao;
 -
 -    @Inject
 -    AffinityGroupVMMapDao _affinityGroupVMMapDao;
 -
 -    @Inject
 -    AffinityGroupDomainMapDao _affinityGroupDomainMapDao;
 -
 -    @Inject
 -    private UserVmDao _userVmDao;
 -
 -    @Inject
 -    DomainDao _domainDao;
 -
 -    @Inject
 -    DomainManager _domainMgr;
 -
 -    protected List<AffinityGroupProcessor> _affinityProcessors;
 -
 -    public List<AffinityGroupProcessor> getAffinityGroupProcessors() {
 -        return _affinityProcessors;
 -    }
 -
 -    public void setAffinityGroupProcessors(List<AffinityGroupProcessor> affinityProcessors) {
 +
 +    public static final Logger s_logger = Logger.getLogger(AffinityGroupServiceImpl.class);
 +    private String _name;
 +
 +    @Inject
 +    AccountManager _accountMgr;
 +
 +    @Inject
 +    AffinityGroupDao _affinityGroupDao;
 +
 +    @Inject
 +    AffinityGroupVMMapDao _affinityGroupVMMapDao;
 +
 +    @Inject
 +    AffinityGroupDomainMapDao _affinityGroupDomainMapDao;
 +
 +    @Inject
 +    private UserVmDao _userVmDao;
 +
 +    @Inject
 +    DomainDao _domainDao;
 +
 +    @Inject
 +    DomainManager _domainMgr;
 +
 +    protected List<AffinityGroupProcessor> _affinityProcessors;
 +
 +    public List<AffinityGroupProcessor> getAffinityGroupProcessors() {
 +        return _affinityProcessors;
 +    }
 +
 +    public void setAffinityGroupProcessors(List<AffinityGroupProcessor> affinityProcessors) {
-         this._affinityProcessors = affinityProcessors;
+         _affinityProcessors = affinityProcessors;
 -    }
 -
 -    @DB
 -    @Override
 -    @ActionEvent(eventType = EventTypes.EVENT_AFFINITY_GROUP_CREATE, eventDescription = "Creating Affinity Group", create = true)
 +    }
 +
 +    @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) {
+     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)) {
 +
 +        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);
+                 throw new InvalidParameterValueException("Unable to create affinity group, invalid affinity group type" + affinityGroupType);
 -            }
 -        } else {
 +            }
 +        } else {
-             throw new InvalidParameterValueException(
-                     "Unable to create affinity group, no Affinity Group Types configured");
+             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);
 -    }
 -
 -    @DB
 -    @Override
 +        }
 +
 +        AffinityGroupProcessor processor = typeProcessorMap.get(affinityGroupType);
 +
 +        if (processor.isAdminControlledGroup()) {
 +            throw new PermissionDeniedException("Cannot create the affinity group");
 +        }
 +
 +        return createAffinityGroupInternal(account, domainId, affinityGroupName, affinityGroupType, description);
 +    }
 +
 +    @DB
 +    @Override
-     public AffinityGroup createAffinityGroupInternal(String account, final Long domainId, final String affinityGroupName,
-             final String affinityGroupType, final String description) {
+     public AffinityGroup createAffinityGroupInternal(String account, 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)) {
 +
 +        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);
+                 throw new InvalidParameterValueException("Unable to create affinity group, invalid affinity group type" + affinityGroupType);
 -            }
 -        } else {
 +            }
 +        } else {
-             throw new InvalidParameterValueException(
-                     "Unable to create affinity group, no Affinity Group Types configured");
+             throw new InvalidParameterValueException("Unable to create affinity group, no Affinity Group Types configured");
 -        }
 -
 -        final AffinityGroupProcessor processor = typeProcessorMap.get(affinityGroupType);
 -
 -        if (processor.isAdminControlledGroup() && !_accountMgr.isRootAdmin(caller.getType())) {
 -            throw new PermissionDeniedException("Cannot create the affinity group");
 -        }
 -
 -        ControlledEntity.ACLType aclType = null;
 -        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.getType())) {
 -                // non root admin need to pass both account and domain
 +        }
 +
 +        final AffinityGroupProcessor processor = typeProcessorMap.get(affinityGroupType);
 +
 +        if (processor.isAdminControlledGroup() && !_accountMgr.isRootAdmin(caller.getId())) {
 +            throw new PermissionDeniedException("Cannot create the affinity group");
 +        }
 +
 +        ControlledEntity.ACLType aclType = null;
 +        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");
+                 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");
 -            }
 -            _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;
 -            aclType = ControlledEntity.ACLType.Account;
 -        }
 -
 -        if (_affinityGroupDao.isNameInUse(owner.getAccountId(), owner.getDomainId(), affinityGroupName)) {
 +            } 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");
 +            }
 +            _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;
 +            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 exisits.");
+             throw new InvalidParameterValueException("Unable to create affinity group, a group with name " + affinityGroupName + " already exisits.");
 -        }
 -        if (domainLevel && _affinityGroupDao.findDomainLevelGroupByName(domainId, affinityGroupName) != null) {
 +        }
 +        if (domainLevel && _affinityGroupDao.findDomainLevelGroupByName(domainId, affinityGroupName) != null) {
-             throw new InvalidParameterValueException("Unable to create affinity group, a group with name "
-                     + affinityGroupName + " already exisits under the domain.");
+             throw new InvalidParameterValueException("Unable to create affinity group, a group with name " + affinityGroupName + " already exisits under the domain.");
 -        }
 -
 -        final Account ownerFinal = owner;
 -        final ControlledEntity.ACLType aclTypeFinal = aclType;
 -        AffinityGroupVO group = Transaction.execute(new TransactionCallback<AffinityGroupVO>() {
 -            @Override
 -            public AffinityGroupVO doInTransaction(TransactionStatus status) {
 +        }
 +
 +        final Account ownerFinal = owner;
 +        final ControlledEntity.ACLType aclTypeFinal = aclType;
 +        AffinityGroupVO group = Transaction.execute(new TransactionCallback<AffinityGroupVO>() {
 +            @Override
 +            public AffinityGroupVO doInTransaction(TransactionStatus status) {
-                 AffinityGroupVO group = new AffinityGroupVO(affinityGroupName, affinityGroupType, description, ownerFinal.getDomainId(),
-                         ownerFinal.getId(), aclTypeFinal);
+                 AffinityGroupVO group =
+                     new AffinityGroupVO(affinityGroupName, affinityGroupType, description, ownerFinal.getDomainId(), ownerFinal.getId(), aclTypeFinal);
 -                _affinityGroupDao.persist(group);
 -
 -                if (domainId != null && aclTypeFinal == ACLType.Domain) {
 -                    boolean subDomainAccess = false;
 -                    subDomainAccess = processor.subDomainAccess();
 -                    AffinityGroupDomainMapVO domainMap = new AffinityGroupDomainMapVO(group.getId(), domainId, subDomainAccess);
 -                    _affinityGroupDomainMapDao.persist(domainMap);
 -                }
 -
 -                return group;
 -            }
 -        });
 -
 -        if (s_logger.isDebugEnabled()) {
 -            s_logger.debug("Created affinity group =" + affinityGroupName);
 -        }
 -
 -        return group;
 -    }
 -
 -    @DB
 -    @Override
 -    @ActionEvent(eventType = EventTypes.EVENT_AFFINITY_GROUP_DELETE, eventDescription = "Deleting affinity group")
 -    public boolean deleteAffinityGroup(Long affinityGroupId, String account, Long domainId, String affinityGroupName) {
 -
 -        Account caller = CallContext.current().getCallingAccount();
 -        Account owner = _accountMgr.finalizeOwner(caller, account, domainId, null);
 -
 -        AffinityGroupVO group = null;
 -        if (affinityGroupId != null) {
 -            group = _affinityGroupDao.findById(affinityGroupId);
 -            if (group == null) {
 +        _affinityGroupDao.persist(group);
 +
 +                if (domainId != null && aclTypeFinal == ACLType.Domain) {
 +            boolean subDomainAccess = false;
 +            subDomainAccess = processor.subDomainAccess();
 +            AffinityGroupDomainMapVO domainMap = new AffinityGroupDomainMapVO(group.getId(), domainId, subDomainAccess);
 +            _affinityGroupDomainMapDao.persist(domainMap);
 +        }
 +
 +                return group;
 +            }
 +        });
-         
 +
 +        if (s_logger.isDebugEnabled()) {
 +            s_logger.debug("Created affinity group =" + affinityGroupName);
 +        }
 +
 +        return group;
 +    }
 +
- 
 +    @DB
 +    @Override
 +    @ActionEvent(eventType = EventTypes.EVENT_AFFINITY_GROUP_DELETE, eventDescription = "Deleting affinity group")
 +    public boolean deleteAffinityGroup(Long affinityGroupId, String account, Long domainId, String affinityGroupName) {
 +
 +        Account caller = CallContext.current().getCallingAccount();
 +        Account owner = _accountMgr.finalizeOwner(caller, account, domainId, null);
 +
 +        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.");
+                 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) {
 +            }
 +        } 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.");
+                 throw new InvalidParameterValueException("Unable to find affinity group: " + affinityGroupName + "; failed to delete group.");
 -            }
 -        } else {
 +            }
 +        } else {
-             throw new InvalidParameterValueException(
-                     "Either the affinity group Id or group name must be specified to delete the group");
+             throw new InvalidParameterValueException("Either the affinity group Id or group name must be specified to delete the group");
 -        }
 -        if (affinityGroupId == null) {
 -            affinityGroupId = group.getId();
 -        }
 -        // check permissions
 -        _accountMgr.checkAccess(caller, AccessType.ModifyEntry, true, group);
 -
 -        final Long affinityGroupIdFinal = affinityGroupId;
 -        Transaction.execute(new TransactionCallbackNoReturn() {
 -            @Override
 -            public void doInTransactionWithoutResult(TransactionStatus status) {
 -
 -                AffinityGroupVO group = _affinityGroupDao.lockRow(affinityGroupIdFinal, true);
 -                if (group == null) {
 -                    throw new InvalidParameterValueException("Unable to find affinity group by id " + affinityGroupIdFinal);
 -                }
 -
 -                List<AffinityGroupVMMapVO> affinityGroupVmMap = _affinityGroupVMMapDao.listByAffinityGroup(affinityGroupIdFinal);
 -                if (!affinityGroupVmMap.isEmpty()) {
 -                    SearchBuilder<AffinityGroupVMMapVO> listByAffinityGroup = _affinityGroupVMMapDao.createSearchBuilder();
 +        }
 +        if (affinityGroupId == null) {
 +            affinityGroupId = group.getId();
 +        }
 +        // check permissions
 +        _accountMgr.checkAccess(caller, AccessType.ModifyEntry, true, group);
 +
 +        final Long affinityGroupIdFinal = affinityGroupId;
 +        Transaction.execute(new TransactionCallbackNoReturn() {
 +            @Override
 +            public void doInTransactionWithoutResult(TransactionStatus status) {
 +
 +                AffinityGroupVO group = _affinityGroupDao.lockRow(affinityGroupIdFinal, true);
 +        if (group == null) {
 +                    throw new InvalidParameterValueException("Unable to find affinity group by id " + affinityGroupIdFinal);
 +        }
 +
 +                List<AffinityGroupVMMapVO> affinityGroupVmMap = _affinityGroupVMMapDao.listByAffinityGroup(affinityGroupIdFinal);
 +        if (!affinityGroupVmMap.isEmpty()) {
 +            SearchBuilder<AffinityGroupVMMapVO> listByAffinityGroup = _affinityGroupVMMapDao.createSearchBuilder();
-             listByAffinityGroup.and("affinityGroupId", listByAffinityGroup.entity().getAffinityGroupId(),
-                     SearchCriteria.Op.EQ);
+                     listByAffinityGroup.and("affinityGroupId", listByAffinityGroup.entity().getAffinityGroupId(), SearchCriteria.Op.EQ);
 -                    listByAffinityGroup.done();
 -                    SearchCriteria<AffinityGroupVMMapVO> sc = listByAffinityGroup.create();
 -                    sc.setParameters("affinityGroupId", affinityGroupIdFinal);
 -
 -                    _affinityGroupVMMapDao.lockRows(sc, null, true);
 -                    _affinityGroupVMMapDao.remove(sc);
 -                }
 -
 -                // call processor to handle the group delete
 -                AffinityGroupProcessor processor = getAffinityGroupProcessorForType(group.getType());
 -                if (processor != null) {
 -                    processor.handleDeleteGroup(group);
 -                }
 -
 -                _affinityGroupDao.expunge(affinityGroupIdFinal);
 -            }
 -        });
 -
 -        if (s_logger.isDebugEnabled()) {
 -            s_logger.debug("Deleted affinity group id=" + affinityGroupId);
 -        }
 -        return true;
 -    }
 -
 -    @Override
 +            listByAffinityGroup.done();
 +            SearchCriteria<AffinityGroupVMMapVO> sc = listByAffinityGroup.create();
 +                    sc.setParameters("affinityGroupId", affinityGroupIdFinal);
 +
 +            _affinityGroupVMMapDao.lockRows(sc, null, true);
 +            _affinityGroupVMMapDao.remove(sc);
 +        }
 +
 +        // call processor to handle the group delete
 +        AffinityGroupProcessor processor = getAffinityGroupProcessorForType(group.getType());
 +        if (processor != null) {
 +            processor.handleDeleteGroup(group);
 +        }
 +
 +                _affinityGroupDao.expunge(affinityGroupIdFinal);
 +            }
 +        });
 +
 +        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) {
+     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) {
 +        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.");
+                 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
 +            }
 +            _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);
+             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
 -    public List<String> listAffinityGroupTypes() {
 -        List<String> types = new ArrayList<String>();
 -
 +            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
 +    public List<String> listAffinityGroupTypes() {
-         Account caller = CallContext.current().getCallingAccount();
- 
 +        List<String> types = new ArrayList<String>();
-         Map<String, AffinityGroupProcessor> componentMap = ComponentContext.getComponentsOfType(AffinityGroupProcessor.class);
 +
-         if (componentMap.size() > 0) {
-             for (Entry<String, AffinityGroupProcessor> entry : componentMap.entrySet()) {
-                 AffinityGroupProcessor processor = entry.getValue();
+         for (AffinityGroupProcessor processor : _affinityProcessors) {
 -            if (processor.isAdminControlledGroup()) {
 -                continue; // we dont list the type if this group can be
 -                          // created only as an admin/system operation.
 -            }
 -            types.add(processor.getType());
 -        }
 -
 -        return types;
 -    }
 -
 -    protected Map<String, AffinityGroupProcessor> getAffinityTypeToProcessorMap() {
 -        Map<String, AffinityGroupProcessor> typeProcessorMap = new HashMap<String, AffinityGroupProcessor>();
 -
 +                if (processor.isAdminControlledGroup()) {
 +                    continue; // we dont list the type if this group can be
 +                              // created only as an admin/system operation.
 +                }
 +                types.add(processor.getType());
 +            }
 +
-         }
 +        return types;
 +    }
 +
 +    protected Map<String, AffinityGroupProcessor> getAffinityTypeToProcessorMap() {
 +        Map<String, AffinityGroupProcessor> typeProcessorMap = new HashMap<String, AffinityGroupProcessor>();
-         Map<String, AffinityGroupProcessor> componentMap = ComponentContext
-                 .getComponentsOfType(AffinityGroupProcessor.class);
 +
-         if (componentMap.size() > 0) {
-             for (Entry<String, AffinityGroupProcessor> entry : componentMap.entrySet()) {
-                 typeProcessorMap.put(entry.getValue().getType(), entry.getValue());
-             }
+         for (AffinityGroupProcessor processor : _affinityProcessors) {
+             typeProcessorMap.put(processor.getType(), processor);
 -        }
 -
 -        return typeProcessorMap;
 -    }
 -
 -    @Override
 -    public boolean isAdminControlledGroup(AffinityGroup group) {
 -
 -        if (group != null) {
 -            String affinityGroupType = group.getType();
 -            Map<String, AffinityGroupProcessor> typeProcessorMap = getAffinityTypeToProcessorMap();
 -            if (typeProcessorMap != null && !typeProcessorMap.isEmpty()) {
 -                AffinityGroupProcessor processor = typeProcessorMap.get(affinityGroupType);
 -                if (processor != null) {
 -                    return processor.isAdminControlledGroup();
 -                }
 -            }
 -        }
 -        return false;
 -
 -    }
 -
 -    @Override
 -    public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
 -        _name = name;
 -        VirtualMachine.State.getStateMachine().registerListener(this);
 -        return true;
 -    }
 -
 -    @Override
 -    public boolean start() {
 -        return true;
 -    }
 -
 -    @Override
 -    public boolean stop() {
 -        return true;
 -    }
 -
 -    @Override
 -    public String getName() {
 -        return _name;
 -    }
 -
 -    @Override
 -    public AffinityGroup getAffinityGroup(Long groupId) {
 -        return _affinityGroupDao.findById(groupId);
 -    }
 -
 -    @Override
 +        }
++
 +        return typeProcessorMap;
 +    }
 +
 +    @Override
 +    public boolean isAdminControlledGroup(AffinityGroup group) {
 +
 +        if (group != null) {
 +            String affinityGroupType = group.getType();
 +            Map<String, AffinityGroupProcessor> typeProcessorMap = getAffinityTypeToProcessorMap();
 +            if (typeProcessorMap != null && !typeProcessorMap.isEmpty()) {
 +                AffinityGroupProcessor processor = typeProcessorMap.get(affinityGroupType);
 +                if (processor != null) {
 +                    return processor.isAdminControlledGroup();
 +                }
 +            }
 +        }
 +        return false;
 +
 +    }
 +
 +    @Override
 +    public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
 +        _name = name;
 +        VirtualMachine.State.getStateMachine().registerListener(this);
 +        return true;
 +    }
 +
 +    @Override
 +    public boolean start() {
 +        return true;
 +    }
 +
 +    @Override
 +    public boolean stop() {
 +        return true;
 +    }
 +
 +    @Override
 +    public String getName() {
 +        return _name;
 +    }
 +
 +    @Override
 +    public AffinityGroup getAffinityGroup(Long groupId) {
 +        return _affinityGroupDao.findById(groupId);
 +    }
 +
 +    @Override
-     public boolean preStateTransitionEvent(State oldState, Event event, State newState, VirtualMachine vo,
-             boolean status, Object opaque) {
+     public boolean preStateTransitionEvent(State oldState, Event event, State newState, VirtualMachine vo, boolean status, Object opaque) {
 -        return true;
 -    }
 -
 -    @Override
 +        return true;
 +    }
 +
 +    @Override
-     public boolean postStateTransitionEvent(State oldState, Event event, State newState, VirtualMachine vo,
-             boolean status, Object opaque) {
+     public boolean postStateTransitionEvent(State oldState, Event event, State newState, VirtualMachine vo, boolean status, Object opaque) {
 -        if (!status) {
 -            return false;
 -        }
 -        if ((newState == State.Expunging) || (newState == State.Error)) {
 -            // cleanup all affinity groups associations of the Expunged VM
 -            SearchCriteria<AffinityGroupVMMapVO> sc = _affinityGroupVMMapDao.createSearchCriteria();
 -            sc.addAnd("instanceId", SearchCriteria.Op.EQ, vo.getId());
 -            _affinityGroupVMMapDao.expunge(sc);
 -        }
 -        return true;
 -    }
 -
 -    @Override
 -    public UserVm updateVMAffinityGroups(Long vmId, List<Long> affinityGroupIds) {
 -        // Verify input parameters
 -        UserVmVO vmInstance = _userVmDao.findById(vmId);
 -        if (vmInstance == null) {
 -            throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
 -        }
 -
 -        // Check that the VM is stopped
 -        if (!vmInstance.getState().equals(State.Stopped)) {
 +        if (!status) {
 +            return false;
 +        }
 +        if ((newState == State.Expunging) || (newState == State.Error)) {
 +            // cleanup all affinity groups associations of the Expunged VM
 +            SearchCriteria<AffinityGroupVMMapVO> sc = _affinityGroupVMMapDao.createSearchCriteria();
 +            sc.addAnd("instanceId", SearchCriteria.Op.EQ, vo.getId());
 +            _affinityGroupVMMapDao.expunge(sc);
 +        }
 +        return true;
 +    }
 +
 +    @Override
 +    public UserVm updateVMAffinityGroups(Long vmId, List<Long> affinityGroupIds) {
 +        // Verify input parameters
 +        UserVmVO vmInstance = _userVmDao.findById(vmId);
 +        if (vmInstance == null) {
 +            throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
 +        }
 +
 +        // Check that the VM is stopped
 +        if (!vmInstance.getState().equals(State.Stopped)) {
-             s_logger.warn("Unable to update affinity groups of the virtual machine " + vmInstance.toString()
-                     + " in state " + vmInstance.getState());
-             throw new InvalidParameterValueException("Unable update affinity groups of the virtual machine "
-                     + vmInstance.toString() + " " + "in state " + vmInstance.getState()
-                     + "; make sure the virtual machine is stopped and not in an error state before updating.");
+             s_logger.warn("Unable to update affinity groups of the virtual machine " + vmInstance.toString() + " in state " + vmInstance.getState());
+             throw new InvalidParameterValueException("Unable update affinity groups of the virtual machine " + vmInstance.toString() + " " + "in state " +
+                 vmInstance.getState() + "; make sure the virtual machine is stopped and not in an error state before updating.");
 -        }
 -
 -        Account caller = CallContext.current().getCallingAccount();
 -        Account owner = _accountMgr.getAccount(vmInstance.getAccountId());
 -
 -        // check that the affinity groups exist
 -        for (Long affinityGroupId : affinityGroupIds) {
 -            AffinityGroupVO ag = _affinityGroupDao.findById(affinityGroupId);
 -            if (ag == null) {
 -                throw new InvalidParameterValueException("Unable to find affinity group by id " + affinityGroupId);
 -            } else {
 -                // verify permissions
 -                _accountMgr.checkAccess(caller, null, true, owner, ag);
 -                // Root admin has access to both VM and AG by default, but make sure the
 -                // owner of these entities is same
 -                if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getType())) {
 -                    if (ag.getAccountId() != owner.getAccountId()) {
 +        }
 +
 +        Account caller = CallContext.current().getCallingAccount();
 +        Account owner = _accountMgr.getAccount(vmInstance.getAccountId());
 +
 +        // check that the affinity groups exist
 +        for (Long affinityGroupId : affinityGroupIds) {
 +            AffinityGroupVO ag = _affinityGroupDao.findById(affinityGroupId);
 +            if (ag == null) {
 +                throw new InvalidParameterValueException("Unable to find affinity group by id " + affinityGroupId);
 +            } else {
 +                // verify permissions
 +                _accountMgr.checkAccess(caller, null, true, owner, ag);
 +                // Root admin has access to both VM and AG by default, but make sure the
 +                // owner of these entities is same
 +                if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) {
 +                    if (ag.getAccountId() != owner.getAccountId()) {
-                         throw new PermissionDeniedException("Affinity Group " + ag
-                                 + " does not belong to the VM's account");
+                         throw new PermissionDeniedException("Affinity Group " + ag + " does not belong to the VM's account");
 -                    }
 -                }
 -            }
 -        }
 -        _affinityGroupVMMapDao.updateMap(vmId, affinityGroupIds);
 -        if (s_logger.isDebugEnabled()) {
 -            s_logger.debug("Updated VM :" + vmId + " affinity groups to =" + affinityGroupIds);
 -        }
 -        // APIResponseHelper will pull out the updated affinitygroups.
 -        return vmInstance;
 -
 -    }
 -
 -    @Override
 -    public boolean isAffinityGroupProcessorAvailable(String affinityGroupType) {
 -        for (AffinityGroupProcessor processor : _affinityProcessors) {
 -            if (affinityGroupType != null && affinityGroupType.equals(processor.getType())) {
 -                return true;
 -            }
 -        }
 -        return false;
 -    }
 -
 -    private AffinityGroupProcessor getAffinityGroupProcessorForType(String affinityGroupType) {
 -        for (AffinityGroupProcessor processor : _affinityProcessors) {
 -            if (affinityGroupType != null && affinityGroupType.equals(processor.getType())) {
 -                return processor;
 -            }
 -        }
 -        return null;
 -    }
 -
 -    @Override
 -    public boolean isAffinityGroupAvailableInDomain(long affinityGroupId, long domainId) {
 -        Long groupDomainId = null;
 -
 -        AffinityGroupDomainMapVO domainMap = _affinityGroupDomainMapDao.findByAffinityGroup(affinityGroupId);
 -        if (domainMap == null) {
 -            return false;
 -        } else {
 -            groupDomainId = domainMap.getDomainId();
 -        }
 -
 -        if (domainId == groupDomainId.longValue()) {
 -            return true;
 -        }
 -
 -        if (domainMap.subdomainAccess) {
 -            Set<Long> parentDomains = _domainMgr.getDomainParentIds(domainId);
 -            if (parentDomains.contains(groupDomainId)) {
 -                return true;
 -            }
 -        }
 -
 -        return false;
 -    }
 -
 -}
 +                    }
 +                }
 +            }
 +        }
 +        _affinityGroupVMMapDao.updateMap(vmId, affinityGroupIds);
 +        if (s_logger.isDebugEnabled()) {
 +            s_logger.debug("Updated VM :" + vmId + " affinity groups to =" + affinityGroupIds);
 +        }
 +        // APIResponseHelper will pull out the updated affinitygroups.
 +        return vmInstance;
 +
 +    }
 +
 +    @Override
 +    public boolean isAffinityGroupProcessorAvailable(String affinityGroupType) {
 +        for (AffinityGroupProcessor processor : _affinityProcessors) {
 +            if (affinityGroupType != null && affinityGroupType.equals(processor.getType())) {
 +                return true;
 +            }
 +        }
 +        return false;
 +    }
 +
 +    private AffinityGroupProcessor getAffinityGroupProcessorForType(String affinityGroupType) {
 +        for (AffinityGroupProcessor processor : _affinityProcessors) {
 +            if (affinityGroupType != null && affinityGroupType.equals(processor.getType())) {
 +                return processor;
 +            }
 +        }
 +        return null;
 +    }
 +
 +    @Override
 +    public boolean isAffinityGroupAvailableInDomain(long affinityGroupId, long domainId) {
 +        Long groupDomainId = null;
 +
 +        AffinityGroupDomainMapVO domainMap = _affinityGroupDomainMapDao.findByAffinityGroup(affinityGroupId);
 +        if (domainMap == null) {
 +            return false;
 +        } else {
 +            groupDomainId = domainMap.getDomainId();
 +        }
 +
 +        if (domainId == groupDomainId.longValue()) {
 +            return true;
 +        }
 +
 +        if (domainMap.subdomainAccess) {
 +            Set<Long> parentDomains = _domainMgr.getDomainParentIds(domainId);
 +            if (parentDomains.contains(groupDomainId)) {
 +                return true;
 +            }
 +        }
 +
 +        return false;
 +    }
 +
 +}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerManagerImpl.java
index 49187b3,9c93b46..f7523a9
--- a/server/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerManagerImpl.java
+++ b/server/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerManagerImpl.java
@@@ -250,9 -254,9 +254,9 @@@ public class ApplicationLoadBalancerMan
       * @throws InsufficientVirtualNetworkCapcityException
       */
      protected Ip getSourceIp(Scheme scheme, Network sourceIpNtwk, String requestedIp) throws InsufficientVirtualNetworkCapcityException {
-         
+ 
          if (requestedIp != null) {
 -            if (_lbDao.countBySourceIp(new Ip(requestedIp), sourceIpNtwk.getId()) > 0) {
 +            if (_lbDao.countBySourceIp(new Ip(requestedIp), sourceIpNtwk.getId()) > 0)  {
                  s_logger.debug("IP address " + requestedIp + " is already used by existing LB rule, returning it");
                  return new Ip(requestedIp);
              }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/test/com/cloud/user/MockAccountManagerImpl.java
----------------------------------------------------------------------
diff --cc server/test/com/cloud/user/MockAccountManagerImpl.java
index c3f081d,62e7fc8..f0986aa
--- a/server/test/com/cloud/user/MockAccountManagerImpl.java
+++ b/server/test/com/cloud/user/MockAccountManagerImpl.java
@@@ -260,38 -250,18 +256,33 @@@ public class MockAccountManagerImpl ext
          return false;
      }
  
 +
- 
 +    /* (non-Javadoc)
 +     * @see com.cloud.user.AccountService#getUserByApiKey(java.lang.String)
 +     */
      @Override
 -    public void buildACLSearchBuilder(SearchBuilder<? extends ControlledEntity> sb, Long domainId, boolean isRecursive, List<Long> permittedAccounts,
 -        ListProjectResourcesCriteria listProjectResourcesCriteria) {
 +    public UserAccount getUserByApiKey(String apiKey) {
          // TODO Auto-generated method stub
 +        return null;
 +    }
  
 +    @Override
-     public UserAccount createUserAccount(String userName, String password,
-             String firstName, String lastName, String email, String timezone,
-             String accountName, short accountType, Long domainId,
-             String networkDomain, Map<String, String> details, String accountUUID, String userUUID) {
++    public UserAccount createUserAccount(String userName, String password, String firstName, String lastName, String email, String timezone, String accountName,
++        short accountType, Long domainId, String networkDomain, Map<String, String> details, String accountUUID, String userUUID) {
 +        // TODO Auto-generated method stub
 +        return null;
      }
  
      @Override
-     public User createUser(String userName, String password, String firstName,
-             String lastName, String email, String timeZone, String accountName,
-             Long domainId, String userUUID) {
 -    public void buildACLSearchCriteria(SearchCriteria<? extends ControlledEntity> sc, Long domainId, boolean isRecursive, List<Long> permittedAccounts,
 -        ListProjectResourcesCriteria listProjectResourcesCriteria) {
++    public User createUser(String userName, String password, String firstName, String lastName, String email, String timeZone, String accountName, Long domainId,
++        String userUUID) {
          // TODO Auto-generated method stub
 +        return null;
 +    }
  
- 
 +    @Override
 +    public RoleType getRoleType(Account account) {
 +        return null;
      }
  
      @Override

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/test/com/cloud/vm/UserVmManagerTest.java
----------------------------------------------------------------------
diff --cc server/test/com/cloud/vm/UserVmManagerTest.java
index 8e5032f,83f7520..43010a3
--- a/server/test/com/cloud/vm/UserVmManagerTest.java
+++ b/server/test/com/cloud/vm/UserVmManagerTest.java
@@@ -304,9 -331,10 +331,10 @@@ public class UserVmManagerTest 
          verify(_vmMock, times(1)).setIsoId(14L);
  
      }
+ 
      // Test scaleVm on incompatible HV.
-     @Test(expected=InvalidParameterValueException.class)
+     @Test(expected = InvalidParameterValueException.class)
 -    public void testScaleVMF1() throws Exception {
 +    public void testScaleVMF1()  throws Exception {
  
          ScaleVMCmd cmd = new ScaleVMCmd();
          Class<?> _class = cmd.getClass();
@@@ -321,8 -349,8 +349,8 @@@
  
          when(_vmInstanceDao.findById(anyLong())).thenReturn(_vmInstance);
  
 -        // UserContext.current().setEventDetails("Vm Id: "+getId());
 +       // UserContext.current().setEventDetails("Vm Id: "+getId());
-         Account account = new AccountVO("testaccount", 1L, "networkdomain", (short) 0, "uuid");
+         Account account = new AccountVO("testaccount", 1L, "networkdomain", (short)0, "uuid");
          UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString());
          //AccountVO(String accountName, long domainId, String networkDomain, short type, int regionId)
          doReturn(VirtualMachine.State.Running).when(_vmInstance).getState();
@@@ -337,9 -365,8 +365,8 @@@
      }
  
      // Test scaleVm on equal service offerings.
-     @Test(expected=InvalidParameterValueException.class)
+     @Test(expected = InvalidParameterValueException.class)
 -    public void testScaleVMF2() throws Exception {
 +    public void testScaleVMF2()  throws Exception {
  
          ScaleVMCmd cmd = new ScaleVMCmd();
          Class<?> _class = cmd.getClass();
@@@ -360,14 -386,13 +386,13 @@@
  
          doNothing().when(_accountMgr).checkAccess(_account, null, true, _templateMock);
  
-         doNothing().when(_itMgr).checkIfCanUpgrade(_vmMock, cmd.getServiceOfferingId());
- 
+         doNothing().when(_itMgr).checkIfCanUpgrade(_vmMock, _offeringVo);
  
 -        ServiceOffering so1 = getSvcoffering(512);
 -        ServiceOffering so2 = getSvcoffering(256);
 +        ServiceOffering so1 =  getSvcoffering(512);
 +        ServiceOffering so2 =  getSvcoffering(256);
  
-         when(_entityMgr.findById(eq(ServiceOffering.class), anyLong())).thenReturn(so1);
-         when(_offeringDao.findByIdIncludingRemoved(anyLong())).thenReturn((ServiceOfferingVO) so1);
+         when(_offeringDao.findById(anyLong())).thenReturn((ServiceOfferingVO)so1);
+         when(_offeringDao.findByIdIncludingRemoved(anyLong(), anyLong())).thenReturn((ServiceOfferingVO)so1);
  
          Account account = new AccountVO("testaccount", 1L, "networkdomain", (short)0, UUID.randomUUID().toString());
          UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString());
@@@ -398,10 -423,8 +423,8 @@@
          when(_vmInstanceDao.findById(anyLong())).thenReturn(_vmInstance);
          doReturn(Hypervisor.HypervisorType.XenServer).when(_vmInstance).getHypervisorType();
  
- 
 -        ServiceOffering so1 = getSvcoffering(512);
 -        ServiceOffering so2 = getSvcoffering(256);
 +        ServiceOffering so1 =  getSvcoffering(512);
 +        ServiceOffering so2 =  getSvcoffering(256);
  
          when(_entityMgr.findById(eq(ServiceOffering.class), anyLong())).thenReturn(so2);
          when(_entityMgr.findById(ServiceOffering.class, 1L)).thenReturn(so1);
@@@ -474,9 -496,9 +496,9 @@@
  
      }
  
-     private ServiceOfferingVO getSvcoffering(int ramSize){
+     private ServiceOfferingVO getSvcoffering(int ramSize) {
  
 -        long id = 4L;
 +        long id  = 4L;
          String name = "name";
          String displayText = "displayText";
          int cpu = 1;
@@@ -491,8 -514,8 +514,8 @@@
      }
  
      // Test Move VM b/w accounts where caller is not ROOT/Domain admin
-     @Test(expected=InvalidParameterValueException.class)
+     @Test(expected = InvalidParameterValueException.class)
 -    public void testMoveVmToUser1() throws Exception {
 +    public void testMoveVmToUser1()  throws Exception {
          AssignVMCmd cmd = new AssignVMCmd();
          Class<?> _class = cmd.getClass();
  
@@@ -522,10 -544,9 +544,9 @@@
          }
      }
  
- 
      // Test Move VM b/w accounts where caller doesn't have access to the old or new account
-     @Test(expected=PermissionDeniedException.class)
+     @Test(expected = PermissionDeniedException.class)
 -    public void testMoveVmToUser2() throws Exception {
 +    public void testMoveVmToUser2()  throws Exception {
          AssignVMCmd cmd = new AssignVMCmd();
          Class<?> _class = cmd.getClass();
  
@@@ -560,13 -577,10 +577,13 @@@
  
          when(_accountService.getActiveAccountByName(anyString(), anyLong())).thenReturn(newAccount);
  
-         doThrow(new PermissionDeniedException("Access check failed")).when(_accountMgr).checkAccess(any(Account.class), any(AccessType.class),
-                 any(Boolean.class), any(ControlledEntity.class));
+         doThrow(new PermissionDeniedException("Access check failed")).when(_accountMgr).checkAccess(any(Account.class), any(AccessType.class), any(Boolean.class),
+             any(ControlledEntity.class));
  
          CallContext.register(user, caller);
 +
 +        when(_accountMgr.isRootAdmin(anyLong())).thenReturn(true);
 +
          try {
              _userVmMgr.moveVMToUser(cmd);
          } finally {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/test/com/cloud/vpc/MockResourceLimitManagerImpl.java
----------------------------------------------------------------------
diff --cc server/test/com/cloud/vpc/MockResourceLimitManagerImpl.java
index 172d6b3,be49abd..db0ee6c
--- a/server/test/com/cloud/vpc/MockResourceLimitManagerImpl.java
+++ b/server/test/com/cloud/vpc/MockResourceLimitManagerImpl.java
@@@ -73,9 -73,8 +73,8 @@@ public class MockResourceLimitManagerIm
          return 0;
      }
  
- 
      @Override
 -    public long findCorrectResourceLimitForAccount(short accountType, Long limit, ResourceType type) {
 +    public long findCorrectResourceLimitForAccount(long accountId, Long limit, ResourceType type) {
          // TODO Auto-generated method stub
          return 0;
      }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/services/iam/plugin/pom.xml
----------------------------------------------------------------------
diff --cc services/iam/plugin/pom.xml
index 92dcd8c,0000000..0650e43
mode 100644,000000..100644
--- a/services/iam/plugin/pom.xml
+++ b/services/iam/plugin/pom.xml
@@@ -1,58 -1,0 +1,58 @@@
 +<!--
 +  Licensed to the Apache Software Foundation (ASF) under one
 +  or more contributor license agreements. See the NOTICE file
 +  distributed with this work for additional information
 +  regarding copyright ownership. The ASF licenses this file
 +  to you under the Apache License, Version 2.0 (the
 +  "License"); you may not use this file except in compliance
 +  with the License. You may obtain a copy of the License at
 +
 +  http://www.apache.org/licenses/LICENSE-2.0
 +
 +  Unless required by applicable law or agreed to in writing,
 +  software distributed under the License is distributed on an
 +  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 +  KIND, either express or implied. See the License for the
 +  specific language governing permissions and limitations
 +  under the License.
 +-->
 +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 +  <modelVersion>4.0.0</modelVersion>
 +  <artifactId>cloud-plugin-iam</artifactId>
 +  <name>Apache CloudStack IAM - Plugin</name>
 +  <parent>
 +    <groupId>org.apache.cloudstack</groupId>
 +    <artifactId>cloudstack-service-iam</artifactId>
-     <version>4.3.0-SNAPSHOT</version>
++    <version>4.4.0-SNAPSHOT</version>
 +    <relativePath>../pom.xml</relativePath>
 +  </parent>
 +  <dependencies>
 +    <dependency>
 +      <groupId>org.apache.cloudstack</groupId>
 +      <artifactId>cloud-api</artifactId>
 +      <version>${project.version}</version>    
 +    </dependency> 
 +    <dependency>
 +      <groupId>org.apache.cloudstack</groupId>
 +      <artifactId>cloud-engine-schema</artifactId>
 +      <version>${project.version}</version>    
 +    </dependency> 
 +    <dependency>
 +      <groupId>org.apache.cloudstack</groupId>
 +      <artifactId>cloud-server</artifactId>
 +      <version>${project.version}</version>    
 +    </dependency>  
 +    <dependency>
 +      <groupId>org.apache.cloudstack</groupId>
 +      <artifactId>cloud-iam</artifactId>
 +      <version>${project.version}</version>    
 +    </dependency>  
 +    <dependency>
 +      <groupId>org.apache.cloudstack</groupId>
 +      <artifactId>cloud-api</artifactId>
 +      <version>${project.version}</version>
 +      <type>test-jar</type>
 +      <scope>test</scope>
 +    </dependency>              
 +  </dependencies> 
 +</project>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/services/iam/plugin/src/org/apache/cloudstack/acl/RoleBasedAPIAccessChecker.java
----------------------------------------------------------------------
diff --cc services/iam/plugin/src/org/apache/cloudstack/acl/RoleBasedAPIAccessChecker.java
index dd49eb1,0000000..c81c31a
mode 100644,000000..100644
--- a/services/iam/plugin/src/org/apache/cloudstack/acl/RoleBasedAPIAccessChecker.java
+++ b/services/iam/plugin/src/org/apache/cloudstack/acl/RoleBasedAPIAccessChecker.java
@@@ -1,216 -1,0 +1,216 @@@
 +// Licensed to the Apache Software Foundation (ASF) under one
 +// or more contributor license agreements.  See the NOTICE file
 +// distributed with this work for additional information
 +// regarding copyright ownership.  The ASF licenses this file
 +// to you under the Apache License, Version 2.0 (the
 +// "License"); you may not use this file except in compliance
 +// with the License.  You may obtain a copy of the License at
 +//
 +//   http://www.apache.org/licenses/LICENSE-2.0
 +//
 +// Unless required by applicable law or agreed to in writing,
 +// software distributed under the License is distributed on an
 +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 +// KIND, either express or implied.  See the License for the
 +// specific language governing permissions and limitations
 +// under the License.
 +package org.apache.cloudstack.acl;
 +
 +import java.util.HashMap;
 +import java.util.HashSet;
 +import java.util.List;
 +import java.util.Map;
 +import java.util.Set;
 +
 +import javax.ejb.Local;
 +import javax.inject.Inject;
 +import javax.naming.ConfigurationException;
 +
 +import org.apache.log4j.Logger;
 +
 +import org.apache.cloudstack.acl.SecurityChecker.AccessType;
 +import org.apache.cloudstack.api.APICommand;
 +import org.apache.cloudstack.api.BaseCmd;
 +import org.apache.cloudstack.api.BaseListCmd;
 +import org.apache.cloudstack.iam.api.AclPolicy;
 +import org.apache.cloudstack.iam.api.AclPolicyPermission.Permission;
 +import org.apache.cloudstack.iam.api.IAMService;
 +
 +import com.cloud.api.ApiServerService;
 +import com.cloud.exception.PermissionDeniedException;
 +import com.cloud.user.Account;
 +import com.cloud.user.AccountService;
 +import com.cloud.user.User;
 +import com.cloud.utils.PropertiesUtil;
 +import com.cloud.utils.component.AdapterBase;
 +import com.cloud.utils.component.PluggableService;
 +import com.cloud.utils.exception.CloudRuntimeException;
 +
 +//This is the Role Based API access checker that grab's the  account's roles
 +//based on the set of roles, access is granted if any of the role has access to the api
 +@Local(value=APIChecker.class)
 +public class RoleBasedAPIAccessChecker extends AdapterBase implements APIChecker {
 +
 +    protected static final Logger s_logger = Logger.getLogger(RoleBasedAPIAccessChecker.class);
 +
 +    @Inject
 +    AccountService _accountService;
 +    @Inject
 +    ApiServerService _apiServer;
 +    @Inject
 +    IAMService _iamSrv;
 +
 +    Set<String> commandsPropertiesOverrides = new HashSet<String>();
 +    Map<RoleType, Set<String>> commandsPropertiesRoleBasedApisMap = new HashMap<RoleType, Set<String>>();
 +
 +    List<PluggableService> _services;
 +
 +    protected RoleBasedAPIAccessChecker() {
 +        super();
 +        for (RoleType roleType : RoleType.values()) {
 +            commandsPropertiesRoleBasedApisMap.put(roleType, new HashSet<String>());
 +        }
 +     }
 +
 +    @Override
 +    public boolean checkAccess(User user, String commandName) throws PermissionDeniedException {
 +        Account account = _accountService.getAccount(user.getAccountId());
 +        if (account == null) {
 +            throw new PermissionDeniedException("The account id=" + user.getAccountId() + "for user id=" + user.getId()
 +                    + "is null");
 +        }
 +
 +        List<AclPolicy> policies = _iamSrv.listAclPolicies(account.getAccountId());
 +
 +        boolean isAllowed = _iamSrv.isActionAllowedForPolicies(commandName, policies);
 +        if (!isAllowed) {
 +            throw new PermissionDeniedException("The API does not exist or is blacklisted. api: " + commandName);
 +        }
 +        return isAllowed;
 +     }
 +
 +    @Override
 +    public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
 +        super.configure(name, params);
 +
 +        processMapping(PropertiesUtil.processConfigFile(new String[] { "commands.properties" }));
 +        return true;
 +     }
 +
 +    @Override
 +    public boolean start() {
 +
 +        // drop all default policy api permissions - we reload them every time
 +        // to include any changes done to the @APICommand or
 +        // commands.properties.
 +
 +        for (RoleType role : RoleType.values()) {
 +            _iamSrv.resetAclPolicy(role.ordinal() + 1);
 +         }
 +
 +        for (PluggableService service : _services) {
 +            for (Class<?> cmdClass : service.getCommands()) {
 +                APICommand command = cmdClass.getAnnotation(APICommand.class);
 +                if (!commandsPropertiesOverrides.contains(command.name())) {
 +                    for (RoleType role : command.authorized()) {
 +                        addDefaultAclPolicyPermission(command.name(), cmdClass, role);
 +                    }
 +                 }
 +             }
 +         }
 +
 +        // read commands.properties and load api acl permissions -
 +        // commands.properties overrides any @APICommand authorization
 +
 +        for (String apiName : commandsPropertiesOverrides) {
 +            Class<?> cmdClass = _apiServer.getCmdClass(apiName);
 +            for (RoleType role : RoleType.values()) {
 +                if (commandsPropertiesRoleBasedApisMap.get(role).contains(apiName)) {
 +                    // insert permission for this role for this api
 +                    addDefaultAclPolicyPermission(apiName, cmdClass, role);
 +                }
 +             }
 +         }
 +
 +        return super.start();
 +     }
 +
 +    private void processMapping(Map<String, String> configMap) {
 +        for (Map.Entry<String, String> entry : configMap.entrySet()) {
 +            String apiName = entry.getKey();
 +            String roleMask = entry.getValue();
 +            commandsPropertiesOverrides.add(apiName);
 +            try {
 +                short cmdPermissions = Short.parseShort(roleMask);
 +                for (RoleType roleType : RoleType.values()) {
 +                    if ((cmdPermissions & roleType.getValue()) != 0)
 +                        commandsPropertiesRoleBasedApisMap.get(roleType).add(apiName);
 +                }
 +            } catch (NumberFormatException nfe) {
 +                s_logger.info("Malformed key=value pair for entry: " + entry.toString());
 +             }
 +         }
 +     }
 +
 +    public List<PluggableService> getServices() {
 +        return _services;
 +     }
 +
 +    @Inject
-     public void setServices(List<PluggableService> _services) {
-         this._services = _services;
++    public void setServices(List<PluggableService> services) {
++        _services = services;
 +     }
 +
 +    private void addDefaultAclPolicyPermission(String apiName, Class<?> cmdClass, RoleType role) {
 +
 +        AccessType accessType = null;
 +        AclEntityType[] entityTypes = null;
 +        if (cmdClass != null) {
 +            BaseCmd cmdObj;
 +            try {
 +                cmdObj = (BaseCmd) cmdClass.newInstance();
 +                if (cmdObj instanceof BaseListCmd) {
 +                    accessType = AccessType.ListEntry;
 +                }
 +            } catch (Exception e) {
 +                throw new CloudRuntimeException(String.format(
 +                        "%s is claimed as an API command, but it cannot be instantiated", cmdClass.getName()));
 +             }
 +
 +            APICommand at = cmdClass.getAnnotation(APICommand.class);
 +            entityTypes = at.entityType();
 +        }
 +
 +        PermissionScope permissionScope = PermissionScope.ACCOUNT;
 +        switch (role) {
 +        case User:
 +            permissionScope = PermissionScope.ACCOUNT;
 +            break;
 +
 +        case Admin:
 +            permissionScope = PermissionScope.ALL;
 +            break;
 +
 +        case DomainAdmin:
 +            permissionScope = PermissionScope.DOMAIN;
 +            break;
 +
 +        case ResourceAdmin:
 +            permissionScope = PermissionScope.DOMAIN;
 +            break;
 +         }
 +
-        
++
 +        if (entityTypes == null || entityTypes.length == 0) {
 +            _iamSrv.addAclPermissionToAclPolicy(new Long(role.ordinal()) + 1, null, permissionScope.toString(), new Long(-1),
 +                    apiName, (accessType == null) ? null : accessType.toString(), Permission.Allow);
 +        } else {
 +            for (AclEntityType entityType : entityTypes) {
 +                _iamSrv.addAclPermissionToAclPolicy(new Long(role.ordinal()) + 1, entityType.toString(), permissionScope.toString(), new Long(-1),
 +                        apiName, (accessType == null) ? null : accessType.toString(), Permission.Allow);
 +            }
 +         }
 +
 +     }
 +
 +}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/services/iam/plugin/src/org/apache/cloudstack/acl/RoleBasedEntityAccessChecker.java
----------------------------------------------------------------------
diff --cc services/iam/plugin/src/org/apache/cloudstack/acl/RoleBasedEntityAccessChecker.java
index 85e7278,0000000..e2b149b
mode 100644,000000..100644
--- a/services/iam/plugin/src/org/apache/cloudstack/acl/RoleBasedEntityAccessChecker.java
+++ b/services/iam/plugin/src/org/apache/cloudstack/acl/RoleBasedEntityAccessChecker.java
@@@ -1,145 -1,0 +1,145 @@@
 +// Licensed to the Apache Software Foundation (ASF) under one
 +// or more contributor license agreements.  See the NOTICE file
 +// distributed with this work for additional information
 +// regarding copyright ownership.  The ASF licenses this file
 +// to you under the Apache License, Version 2.0 (the
 +// "License"); you may not use this file except in compliance
 +// with the License.  You may obtain a copy of the License at
 +//
 +//   http://www.apache.org/licenses/LICENSE-2.0
 +//
 +// Unless required by applicable law or agreed to in writing,
 +// software distributed under the License is distributed on an
 +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 +// KIND, either express or implied.  See the License for the
 +// specific language governing permissions and limitations
 +// under the License.
 +package org.apache.cloudstack.acl;
 +
 +import java.util.ArrayList;
 +import java.util.HashMap;
 +import java.util.List;
 +
 +import javax.inject.Inject;
 +
 +import org.apache.log4j.Logger;
 +
 +import org.apache.cloudstack.iam.api.AclPolicy;
 +import org.apache.cloudstack.iam.api.AclPolicyPermission;
 +import org.apache.cloudstack.iam.api.IAMService;
 +
 +import com.cloud.acl.DomainChecker;
 +import com.cloud.domain.dao.DomainDao;
 +import com.cloud.exception.PermissionDeniedException;
 +import com.cloud.user.Account;
 +import com.cloud.user.AccountService;
 +
 +public class RoleBasedEntityAccessChecker extends DomainChecker implements SecurityChecker {
 +
 +    private static final Logger s_logger = Logger.getLogger(RoleBasedEntityAccessChecker.class.getName());
 +
 +    @Inject
 +    AccountService _accountService;
-     
++
 +    @Inject DomainDao _domainDao;
 +
 +    @Inject
 +    IAMService _iamSrv;
 +
 +
 +    @Override
 +    public boolean checkAccess(Account caller, ControlledEntity entity, AccessType accessType)
 +            throws PermissionDeniedException {
 +        return checkAccess(caller, entity, accessType, null);
 +    }
 +
 +    @Override
 +    public boolean checkAccess(Account caller, ControlledEntity entity, AccessType accessType, String action)
 +            throws PermissionDeniedException {
 +
 +        if (entity == null && action != null) {
 +            // check if caller can do this action
 +            List<AclPolicy> policies = _iamSrv.listAclPolicies(caller.getAccountId());
 +
 +            boolean isAllowed = _iamSrv.isActionAllowedForPolicies(action, policies);
 +            if (!isAllowed) {
 +                throw new PermissionDeniedException("The action '" + action + "' not allowed for account " + caller);
 +            }
 +            return true;
 +        }
 +
 +        String entityType = entity.getEntityType().toString();
 +
 +        if (accessType == null) {
 +            accessType = AccessType.ListEntry;
 +        }
 +
 +        // get all Policies of this caller w.r.t the entity
 +        List<AclPolicy> policies = getEffectivePolicies(caller, entity);
 +        HashMap<AclPolicy, Boolean> policyPermissionMap = new HashMap<AclPolicy, Boolean>();
 +
 +        for (AclPolicy policy : policies) {
 +            List<AclPolicyPermission> permissions = new ArrayList<AclPolicyPermission>();
 +
 +            if (action != null) {
 +                permissions = _iamSrv.listPolicyPermissionByEntityType(policy.getId(), action, entityType);
 +            } else {
 +                permissions = _iamSrv.listPolicyPermissionByAccessType(policy.getId(), accessType.toString(),
 +                        entityType, action);
 +            }
 +            for (AclPolicyPermission permission : permissions) {
 +                if (checkPermissionScope(caller, permission.getScope(), entity)) {
 +                    if (permission.getEntityType().equals(entityType)) {
 +                        policyPermissionMap.put(policy, permission.getPermission().isGranted());
 +                        break;
 +                    } else if (permission.getEntityType().equals("*")) {
 +                        policyPermissionMap.put(policy, permission.getPermission().isGranted());
 +                    }
 +                }
 +            }
 +            if (policyPermissionMap.containsKey(policy) && policyPermissionMap.get(policy)) {
 +                return true;
 +            }
 +        }
 +
 +        if (!policies.isEmpty()) { // Since we reach this point, none of the
 +                                   // roles granted access
 +            if (s_logger.isDebugEnabled()) {
 +                s_logger.debug("Account " + caller + " does not have permission to access resource " + entity
 +                        + " for access type: " + accessType);
 +            }
 +            throw new PermissionDeniedException(caller + " does not have permission to access resource " + entity);
 +        }
 +
 +        return false;
 +    }
 +
 +    private boolean checkPermissionScope(Account caller, String scope, ControlledEntity entity) {
-         
++
 +        if (scope.equals(PermissionScope.ACCOUNT.name())) {
 +            if(caller.getAccountId() == entity.getAccountId()){
 +                return true;
 +            }
 +        } else if (scope.equals(PermissionScope.DOMAIN.name())) {
 +            if (_domainDao.isChildDomain(caller.getDomainId(), entity.getDomainId())) {
 +                return true;
 +            }
 +        }
-         
++
 +        return false;
 +    }
 +
 +    private List<AclPolicy> getEffectivePolicies(Account caller, ControlledEntity entity) {
 +
 +        // Get the static Policies of the Caller
 +        List<AclPolicy> policies = _iamSrv.listAclPolicies(caller.getId());
 +
 +        // add any dynamic policies w.r.t the entity
 +        if (caller.getId() == entity.getAccountId()) {
 +            // The caller owns the entity
 +            policies.add(_iamSrv.getResourceOwnerPolicy());
 +        }
 +
 +        return policies;
 +    }
 +}