cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ahu...@apache.org
Subject [03/12] UserContext switched to CallContext. Added generic storage mechanism for other code to carry information throughout a call. Made the calling User and Account a must have. Added an interface to carry entities in error. Fixed up the code. Part
Date Tue, 16 Jul 2013 18:24:26 GMT
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/11e1e585/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 283e832..4b06e78 100755
--- a/server/src/com/cloud/user/AccountManagerImpl.java
+++ b/server/src/com/cloud/user/AccountManagerImpl.java
@@ -37,6 +37,9 @@ import javax.ejb.Local;
 import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
+import org.apache.commons.codec.binary.Base64;
+import org.apache.log4j.Logger;
+
 import org.apache.cloudstack.acl.ControlledEntity;
 import org.apache.cloudstack.acl.RoleType;
 import org.apache.cloudstack.acl.SecurityChecker;
@@ -46,9 +49,9 @@ import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd;
 import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd;
 import org.apache.cloudstack.api.command.admin.user.RegisterCmd;
 import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd;
+import org.apache.cloudstack.context.CallContext;
+import org.apache.cloudstack.context.ServerContexts;
 import org.apache.cloudstack.region.gslb.GlobalLoadBalancerRuleDao;
-import org.apache.commons.codec.binary.Base64;
-import org.apache.log4j.Logger;
 
 import com.cloud.api.ApiDBUtils;
 import com.cloud.api.query.vo.ControlledViewEntity;
@@ -104,7 +107,6 @@ import com.cloud.projects.ProjectManager;
 import com.cloud.projects.ProjectVO;
 import com.cloud.projects.dao.ProjectAccountDao;
 import com.cloud.projects.dao.ProjectDao;
-import com.cloud.region.ha.GlobalLoadBalancingRulesService;
 import com.cloud.server.auth.UserAuthenticator;
 import com.cloud.storage.VMTemplateVO;
 import com.cloud.storage.Volume;
@@ -277,7 +279,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
 	}
 
 	public void setSecurityCheckers(List<SecurityChecker> securityCheckers) {
-		this._securityCheckers = securityCheckers;
+		_securityCheckers = securityCheckers;
 	}
     
     @Override
@@ -621,7 +623,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
             for (VolumeVO volume : volumes) {
                 if (!volume.getState().equals(Volume.State.Destroy)) {
                     try {
-                        this.volumeMgr.deleteVolume(volume.getId(), caller);
+                        volumeMgr.deleteVolume(volume.getId(), caller);
                     } catch (Exception ex) {
                         s_logger.warn("Failed to cleanup volumes as a part of account id=" + accountId + " cleanup due to Exception: ", ex);
                         accountCleanupNeeded = true;
@@ -875,7 +877,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
         }
 
         // Check permissions
-        checkAccess(UserContext.current().getCaller(), domain);
+        checkAccess(CallContext.current().getCallingAccount(), domain);
 
         if (!_userAccountDao.validateUsernameInDomain(userName, domainId)) {
             throw new InvalidParameterValueException("The user " + userName + " already exists in domain " + domainId);
@@ -910,7 +912,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
         }
         txn.commit();
 
-        UserContext.current().setEntityDetails(Account.class, account.getUuid());
+        CallContext.current().putContextParameter(Account.class, account.getUuid());
 
         //check success
         return _userAccountDao.findById(user.getId());
@@ -931,7 +933,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
             throw new CloudRuntimeException("The user cannot be created as domain " + domain.getName() + " is being deleted");
         }
 
-        checkAccess(UserContext.current().getCaller(), domain);
+        checkAccess(CallContext.current().getCallingAccount(), domain);
 
         Account account = _accountDao.findEnabledAccount(accountName, domainId);
         if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
@@ -987,7 +989,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
             throw new PermissionDeniedException("user id : " + id + " is system account, update is not allowed");
         }
 
-        checkAccess(UserContext.current().getCaller(), null, true, account);
+        checkAccess(CallContext.current().getCallingAccount(), null, true, account);
 
         if (firstName != null) {
             if (firstName.isEmpty()) {
@@ -1073,7 +1075,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
             throw new CloudRuntimeException("Unable to update user " + id);
         }
 
-        UserContext.current().setEntityDetails(User.class, user.getUuid());
+        CallContext.current().putContextParameter(User.class, user.getUuid());
 
         return _userAccountDao.findById(id);
     }
@@ -1081,7 +1083,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
     @Override
     @ActionEvent(eventType = EventTypes.EVENT_USER_DISABLE, eventDescription = "disabling User", async = true)
     public UserAccount disableUser(long userId) {
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
 
         // Check if user exists in the system
         User user = _userDao.findById(userId);
@@ -1106,7 +1108,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
         boolean success = doSetUserStatus(userId, State.disabled);
         if (success) {
 
-            UserContext.current().setEntityDetails(User.class, user.getUuid());
+            CallContext.current().putContextParameter(User.class, user.getUuid());
 
             // user successfully disabled
             return _userAccountDao.findById(userId);
@@ -1120,7 +1122,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
     @ActionEvent(eventType = EventTypes.EVENT_USER_ENABLE, eventDescription = "enabling User")
     public UserAccount enableUser(long userId) {
 
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
 
         // Check if user exists in the system
         User user = _userDao.findById(userId);
@@ -1155,7 +1157,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
             // whenever the user is successfully enabled, reset the login attempts to zero
             updateLoginAttempts(userId, 0, false);
 
-            UserContext.current().setEntityDetails(User.class, user.getUuid());
+            CallContext.current().putContextParameter(User.class, user.getUuid());
 
             return _userAccountDao.findById(userId);
         } else {
@@ -1166,7 +1168,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
     @Override
     @ActionEvent(eventType = EventTypes.EVENT_USER_LOCK, eventDescription = "locking User")
     public UserAccount lockUser(long userId) {
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
 
         // Check if user with id exists in the system
         User user = _userDao.findById(userId);
@@ -1219,7 +1221,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
 
         if (success) {
 
-            UserContext.current().setEntityDetails(User.class, user.getUuid());
+            CallContext.current().putContextParameter(User.class, user.getUuid());
 
             return _userAccountDao.findById(userId);
         } else {
@@ -1232,9 +1234,9 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
     // This method deletes the account
     public boolean deleteUserAccount(long accountId) {
 
-        UserContext ctx = UserContext.current();
-        long callerUserId = ctx.getCallerUserId();
-        Account caller = ctx.getCaller();
+        CallContext ctx = CallContext.current();
+        long callerUserId = ctx.getCallingUserId();
+        Account caller = ctx.getCallingAccount();
 
         // If the user is a System user, return an error. We do not allow this
         AccountVO account = _accountDao.findById(accountId);
@@ -1267,7 +1269,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
             throw new InvalidParameterValueException("The account id=" + accountId + " manages project(s) with ids " + projectIds + "and can't be removed");
         }
 
-        UserContext.current().setEntityDetails(Account.class, account.getUuid());
+        CallContext.current().putContextParameter(Account.class, account.getUuid());
 
         return deleteAccount(account, callerUserId, caller);
     }
@@ -1293,13 +1295,13 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
         }
 
         // Check if user performing the action is allowed to modify this account
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
         checkAccess(caller, null, true, account);
 
         boolean success = enableAccount(account.getId());
         if (success) {
 
-            UserContext.current().setEntityDetails(Account.class, account.getUuid());
+            CallContext.current().putContextParameter(Account.class, account.getUuid());
 
             return _accountDao.findById(account.getId());
         } else {
@@ -1310,7 +1312,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
     @Override
     @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_DISABLE, eventDescription = "locking account", async = true)
     public AccountVO lockAccount(String accountName, Long domainId, Long accountId) {
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
 
         Account account = null;
         if (accountId != null) {
@@ -1330,7 +1332,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
         checkAccess(caller, null, true, account);
 
         if (lockAccount(account.getId())) {
-            UserContext.current().setEntityDetails(Account.class, account.getUuid());
+            CallContext.current().putContextParameter(Account.class, account.getUuid());
             return _accountDao.findById(account.getId());
         } else {
             throw new CloudRuntimeException("Unable to lock account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId);
@@ -1340,7 +1342,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
     @Override
     @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_DISABLE, eventDescription = "disabling account", async = true)
     public AccountVO disableAccount(String accountName, Long domainId, Long accountId) throws ConcurrentOperationException, ResourceUnavailableException {
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
 
         Account account = null;
         if (accountId != null) {
@@ -1360,7 +1362,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
         checkAccess(caller, null, true, account);
 
         if (disableAccount(account.getId())) {
-            UserContext.current().setEntityDetails(Account.class, account.getUuid());
+            CallContext.current().putContextParameter(Account.class, account.getUuid());
             return _accountDao.findById(account.getId());
         } else {
             throw new CloudRuntimeException("Unable to update account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId);
@@ -1398,7 +1400,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
         }
 
         // Check if user performing the action is allowed to modify this account
-        checkAccess(UserContext.current().getCaller(), _domainMgr.getDomain(account.getDomainId()));
+        checkAccess(CallContext.current().getCallingAccount(), _domainMgr.getDomain(account.getDomainId()));
 
         // check if the given account name is unique in this domain for updating
         Account duplicateAcccount = _accountDao.findActiveAccount(newAccountName, domainId);
@@ -1443,7 +1445,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
         txn.commit();
 
         if (success) {
-            UserContext.current().setEntityDetails(Account.class, account.getUuid());
+            CallContext.current().putContextParameter(Account.class, account.getUuid());
             return _accountDao.findById(account.getId());
         } else {
             throw new CloudRuntimeException("Unable to update account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId);
@@ -1473,8 +1475,8 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
             throw new InvalidParameterValueException("The user is default and can't be removed");
         }
 
-        checkAccess(UserContext.current().getCaller(), null, true, account);
-        UserContext.current().setEntityDetails(User.class, user.getUuid());
+        checkAccess(CallContext.current().getCallingAccount(), null, true, account);
+        CallContext.current().putContextParameter(User.class, user.getUuid());
         return _userDao.remove(id);
     }
 
@@ -1489,6 +1491,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
         @Override
         public void run() {
             try {
+                ServerContexts.registerSystemContext();
                 GlobalLock lock = GlobalLock.getInternLock("AccountCleanup");
                 if (lock == null) {
                     s_logger.debug("Couldn't get the global lock");
@@ -1500,10 +1503,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
                     return;
                 }
 
-                Transaction txn = null;
                 try {
-                    txn = Transaction.open(Transaction.CLOUD_DB);
-
                     // Cleanup removed accounts
                     List<AccountVO> removedAccounts = _accountDao.findCleanupsForRemovedAccounts(null);
                     s_logger.info("Found " + removedAccounts.size() + " removed accounts to cleanup");
@@ -1560,7 +1560,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
                             Account projectAccount = getAccount(project.getProjectAccountId());
                             if (projectAccount == null) {
                                 s_logger.debug("Removing inactive project id=" + project.getId());
-                                _projectMgr.deleteProject(UserContext.current().getCaller(), UserContext.current().getCallerUserId(), project);
+                                _projectMgr.deleteProject(CallContext.current().getCallingAccount(), CallContext.current().getCallingUserId(), project);
                             } else {
                                 s_logger.debug("Can't remove disabled project " + project + " as it has non removed account id=" + project.getId());
                             }
@@ -1572,11 +1572,8 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
                 } catch (Exception e) {
                     s_logger.error("Exception ", e);
                 } finally {
-                    if (txn != null) {
-                        txn.close();
-                    }
-
                     lock.unlock();
+                    ServerContexts.unregisterSystemContext();
                 }
             } catch (Exception e) {
                 s_logger.error("Exception ", e);
@@ -1793,7 +1790,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
             userUUID =  UUID.randomUUID().toString();
         }
         UserVO user = _userDao.persist(new UserVO(accountId, userName, encodedPassword, firstName, lastName, email, timezone, userUUID));
-        UserContext.current().setEntityDetails(User.class, user.getUuid());
+        CallContext.current().putContextParameter(User.class, user.getUuid());
         return user;
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/11e1e585/server/src/com/cloud/user/DomainManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/user/DomainManagerImpl.java b/server/src/com/cloud/user/DomainManagerImpl.java
index aad5787..c862061 100644
--- a/server/src/com/cloud/user/DomainManagerImpl.java
+++ b/server/src/com/cloud/user/DomainManagerImpl.java
@@ -24,12 +24,14 @@ import java.util.UUID;
 import javax.ejb.Local;
 import javax.inject.Inject;
 
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
 import org.apache.cloudstack.api.command.admin.domain.ListDomainChildrenCmd;
 import org.apache.cloudstack.api.command.admin.domain.ListDomainsCmd;
 import org.apache.cloudstack.api.command.admin.domain.UpdateDomainCmd;
+import org.apache.cloudstack.context.CallContext;
 import org.apache.cloudstack.region.RegionManager;
-import org.apache.log4j.Logger;
-import org.springframework.stereotype.Component;
 
 import com.cloud.configuration.Resource.ResourceOwnerType;
 import com.cloud.configuration.ResourceLimit;
@@ -133,7 +135,7 @@ public class DomainManagerImpl extends ManagerBase implements DomainManager, Dom
     @Override
     @ActionEvent(eventType = EventTypes.EVENT_DOMAIN_CREATE, eventDescription = "creating Domain")
     public Domain createDomain(String name, Long parentId, String networkDomain, String domainUUID) {
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
 
         if (parentId == null) {
             parentId = Long.valueOf(DomainVO.ROOT_DOMAIN);
@@ -184,7 +186,7 @@ public class DomainManagerImpl extends ManagerBase implements DomainManager, Dom
         DomainVO domain = _domainDao.create(new DomainVO(name, ownerId, parentId, networkDomain, domainUUID));
         _resourceCountDao.createResourceCounts(domain.getId(), ResourceLimit.ResourceOwnerType.Domain);
         txn.commit();
-        UserContext.current().setEntityDetails(Domain.class, domain.getUuid());
+        CallContext.current().putContextParameter(Domain.class, domain.getUuid());
         return domain;
     }
 
@@ -211,7 +213,7 @@ public class DomainManagerImpl extends ManagerBase implements DomainManager, Dom
     @Override
     @ActionEvent(eventType = EventTypes.EVENT_DOMAIN_DELETE, eventDescription = "deleting Domain", async = true)
     public boolean deleteDomain(long domainId, Boolean cleanup) {
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
 
         DomainVO domain = _domainDao.findById(domainId);
 
@@ -281,7 +283,7 @@ public class DomainManagerImpl extends ManagerBase implements DomainManager, Dom
             }
 
             cleanupDomainOfferings(domain.getId());
-            UserContext.current().setEntityDetails(Domain.class, domain.getUuid());
+            CallContext.current().putContextParameter(Domain.class, domain.getUuid());
             return true;
         } catch (Exception ex) {
             s_logger.error("Exception deleting domain with id " + domain.getId(), ex);
@@ -350,15 +352,15 @@ public class DomainManagerImpl extends ManagerBase implements DomainManager, Dom
         for (AccountVO account : accounts) {
             if (account.getType() != Account.ACCOUNT_TYPE_PROJECT) {
                 s_logger.debug("Deleting account " + account + " as a part of domain id=" + domainId + " cleanup");
-                boolean deleteAccount = _accountMgr.deleteAccount(account, UserContext.current().getCallerUserId(), UserContext.current().getCaller());
+                boolean deleteAccount = _accountMgr.deleteAccount(account, CallContext.current().getCallingUserId(), CallContext.current().getCallingAccount());
                 if (!deleteAccount) {
                     s_logger.warn("Failed to cleanup account id=" + account.getId() + " as a part of domain cleanup");
                 }
-                success = (success && deleteAccount);    
+                success = (success && deleteAccount);
             } else {
                 ProjectVO project = _projectDao.findByProjectAccountId(account.getId());
                 s_logger.debug("Deleting project " + project + " as a part of domain id=" + domainId + " cleanup");
-                boolean deleteProject = _projectMgr.deleteProject(UserContext.current().getCaller(), UserContext.current().getCallerUserId(), project);
+                boolean deleteProject = _projectMgr.deleteProject(CallContext.current().getCallingAccount(), CallContext.current().getCallingUserId(), project);
                 if (!deleteProject) {
                     s_logger.warn("Failed to cleanup project " + project + " as a part of domain cleanup");
                 }
@@ -370,8 +372,8 @@ public class DomainManagerImpl extends ManagerBase implements DomainManager, Dom
         boolean networksDeleted = true;
         s_logger.debug("Deleting networks for domain id=" + domainId);
         List<Long> networkIds = _networkDomainDao.listNetworkIdsByDomain(domainId);
-        UserContext ctx = UserContext.current();
-        ReservationContext context = new ReservationContextImpl(null, null, _accountMgr.getActiveUser(ctx.getCallerUserId()), ctx.getCaller());
+        CallContext ctx = CallContext.current();
+        ReservationContext context = new ReservationContextImpl(null, null, _accountMgr.getActiveUser(ctx.getCallingUserId()), ctx.getCallingAccount());
         for (Long networkId : networkIds) {
             s_logger.debug("Deleting network id=" + networkId + " as a part of domain id=" + domainId + " cleanup");
             
@@ -419,7 +421,7 @@ public class DomainManagerImpl extends ManagerBase implements DomainManager, Dom
 
     @Override
     public Pair<List<? extends Domain>, Integer> searchForDomains(ListDomainsCmd cmd) {
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
         Long domainId = cmd.getId();
         boolean listAll = cmd.listAll();
         boolean isRecursive = false;
@@ -491,7 +493,7 @@ public class DomainManagerImpl extends ManagerBase implements DomainManager, Dom
         boolean listAll = cmd.listAll();
         String path = null;
 
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
         if (domainId != null) {
             _accountMgr.checkAccess(caller, getDomain(domainId));
         } else {
@@ -560,7 +562,7 @@ public class DomainManagerImpl extends ManagerBase implements DomainManager, Dom
         }
 
         // check permissions
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
         _accountMgr.checkAccess(caller, domain);
 
         // domain name is unique in the cloud
@@ -606,7 +608,7 @@ public class DomainManagerImpl extends ManagerBase implements DomainManager, Dom
             }
         }
         _domainDao.update(domainId, domain);
-        UserContext.current().setEntityDetails(Domain.class, domain.getUuid());
+        CallContext.current().putContextParameter(Domain.class, domain.getUuid());
         txn.commit();
 
         return _domainDao.findById(domainId);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/11e1e585/server/src/com/cloud/vm/UserVmManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java
index ef9fcbc..bd7a791 100755
--- a/server/src/com/cloud/vm/UserVmManagerImpl.java
+++ b/server/src/com/cloud/vm/UserVmManagerImpl.java
@@ -58,6 +58,8 @@ import org.apache.cloudstack.api.command.user.vm.UpdateVMCmd;
 import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd;
 import org.apache.cloudstack.api.command.user.vmgroup.CreateVMGroupCmd;
 import org.apache.cloudstack.api.command.user.vmgroup.DeleteVMGroupCmd;
+import org.apache.cloudstack.context.CallContext;
+import org.apache.cloudstack.context.ServerContexts;
 import org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity;
 import org.apache.cloudstack.engine.service.api.OrchestrationService;
 import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory;
@@ -210,7 +212,6 @@ import com.cloud.user.ResourceLimitService;
 import com.cloud.user.SSHKeyPair;
 import com.cloud.user.SSHKeyPairVO;
 import com.cloud.user.User;
-import com.cloud.user.UserContext;
 import com.cloud.user.UserVO;
 import com.cloud.user.VmDiskStatisticsVO;
 import com.cloud.user.dao.AccountDao;
@@ -469,7 +470,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
     @ActionEvent(eventType = EventTypes.EVENT_VM_RESETPASSWORD, eventDescription = "resetting Vm password", async = true)
     public UserVm resetVMPassword(ResetVMPasswordCmd cmd, String password)
             throws ResourceUnavailableException, InsufficientCapacityException {
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
         Long vmId = cmd.getId();
         UserVmVO userVm = _vmDao.findById(cmd.getId());
         _vmDao.loadDetails(userVm);
@@ -515,7 +516,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
     private boolean resetVMPasswordInternal(Long vmId,
             String password) throws ResourceUnavailableException,
             InsufficientCapacityException {
-        Long userId = UserContext.current().getCallerUserId();
+        Long userId = CallContext.current().getCallingUserId();
         VMInstanceVO vmInstance = _vmDao.findById(vmId);
 
         if (password == null || password.equals("")) {
@@ -584,7 +585,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
     public UserVm resetVMSSHKey(ResetVMSSHKeyCmd cmd)
             throws ResourceUnavailableException, InsufficientCapacityException {
 
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
         Account owner = _accountMgr.finalizeOwner(caller, cmd.getAccountName(), cmd.getDomainId(), cmd.getProjectId());
         Long vmId = cmd.getId();
 
@@ -636,7 +637,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
     }
 
     private boolean resetVMSSHKeyInternal(Long vmId, String SSHPublicKey, String password) throws ResourceUnavailableException, InsufficientCapacityException {
-        Long userId = UserContext.current().getCallerUserId();
+        Long userId = CallContext.current().getCallingUserId();
         VMInstanceVO vmInstance = _vmDao.findById(vmId);
 
         VMTemplateVO template = _templateDao.findByIdIncludingRemoved(vmInstance.getTemplateId());
@@ -754,7 +755,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
 
 
     private UserVm upgradeStoppedVirtualMachine(Long vmId, Long svcOffId) throws ResourceAllocationException {
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
 
         // Verify input parameters
         UserVmVO vmInstance = _vmDao.findById(vmId);
@@ -827,7 +828,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
         Long vmId = cmd.getVmId();
         Long networkId = cmd.getNetworkId();
         String ipAddress = cmd.getIpAddress();
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
 
         UserVmVO vmInstance = _vmDao.findById(vmId);
         if(vmInstance == null) {
@@ -902,7 +903,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
     public UserVm removeNicFromVirtualMachine(RemoveNicFromVMCmd cmd) throws InvalidParameterValueException, PermissionDeniedException, CloudRuntimeException {
         Long vmId = cmd.getVmId();
         Long nicId = cmd.getNicId();
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
 
         UserVmVO vmInstance = _vmDao.findById(vmId);
         if(vmInstance == null) {
@@ -959,7 +960,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
     public UserVm updateDefaultNicForVirtualMachine(UpdateDefaultNicForVMCmd cmd) throws InvalidParameterValueException, CloudRuntimeException {
         Long vmId = cmd.getVmId();
         Long nicId = cmd.getNicId();
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
 
         UserVmVO vmInstance = _vmDao.findById(vmId);
         if (vmInstance == null){
@@ -1122,7 +1123,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
 
     @Override
     public boolean upgradeVirtualMachine(Long vmId, Long newServiceOfferingId) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException{
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
 
         // Verify input parameters
         VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId);
@@ -1285,7 +1286,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
             throws ResourceAllocationException, CloudRuntimeException {
 
         Long vmId = cmd.getId();
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
 
         // Verify input parameters
         UserVmVO vm = _vmDao.findById(vmId.longValue());
@@ -1496,9 +1497,6 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
 
     @Override
     public boolean expunge(UserVmVO vm, long callerUserId, Account caller) {
-        UserContext ctx = UserContext.current();
-        ctx.setAccountId(vm.getAccountId());
-
         try {
             // expunge the vm
             if (!_itMgr.advanceExpunge(vm, _accountMgr.getSystemUser(), caller)) {
@@ -1651,7 +1649,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
 
         @Override
         public void run() {
-            UserContext.registerContext(_accountMgr.getSystemUser().getId(), _accountMgr.getSystemAccount(), null, false);
+            ServerContexts.registerSystemContext();
             GlobalLock scanLock = GlobalLock.getInternLock("UserVMExpunge");
             try {
                 if (scanLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION)) {
@@ -1685,9 +1683,10 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
                 }
             } finally {
                 scanLock.releaseRef();
-                UserContext.unregisterContext();
+                ServerContexts.unregisterSystemContext();
             }
         }
+
     }
 
     private static boolean isAdmin(short accountType) {
@@ -1708,7 +1707,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
         Long osTypeId = cmd.getOsTypeId();
         String userData = cmd.getUserData();
         Boolean isDynamicallyScalable = cmd.isDynamicallyScalable();
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
 
         // Input validation
         UserVmVO vmInstance = null;
@@ -1728,7 +1727,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
                     "Can't enable ha for the vm as it's created from the Service offering having HA disabled");
         }
 
-        _accountMgr.checkAccess(UserContext.current().getCaller(), null, true,
+        _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true,
                 vmInstance);
 
         if (displayName == null) {
@@ -1863,7 +1862,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
     @ActionEvent(eventType = EventTypes.EVENT_VM_REBOOT, eventDescription = "rebooting Vm", async = true)
     public UserVm rebootVirtualMachine(RebootVMCmd cmd)
             throws InsufficientCapacityException, ResourceUnavailableException {
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
         Long vmId = cmd.getId();
 
         // Verify input parameters
@@ -1886,7 +1885,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
             throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId + " corresponding to the vm");
         }
 
-        return rebootVirtualMachine(UserContext.current().getCallerUserId(),
+        return rebootVirtualMachine(CallContext.current().getCallingUserId(),
                 vmId);
     }
 
@@ -1900,7 +1899,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
     @Override
     @DB
     public InstanceGroupVO createVmGroup(CreateVMGroupCmd cmd) {
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
         Long domainId = cmd.getDomainId();
         String accountName = cmd.getAccountName();
         String groupName = cmd.getGroupName();
@@ -1955,7 +1954,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
 
     @Override
     public boolean deleteVmGroup(DeleteVMGroupCmd cmd) {
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
         Long groupId = cmd.getId();
 
         // Verify input parameters
@@ -2108,7 +2107,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
 	    List<Long> affinityGroupIdList)
         throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException {
 
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
         List<NetworkVO> networkList = new ArrayList<NetworkVO>();
 
         // Verify that caller can perform actions in behalf of vm owner
@@ -2168,7 +2167,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
 	        List<Long> affinityGroupIdList) throws InsufficientCapacityException, ConcurrentOperationException,
 	        ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException {
 
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
         List<NetworkVO> networkList = new ArrayList<NetworkVO>();
         boolean isSecurityGroupEnabledNetworkUsed = false;
         boolean isVmWare = (template.getHypervisorType() == HypervisorType.VMware || (hypervisor != null && hypervisor == HypervisorType.VMware));
@@ -2283,7 +2282,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
 	    IpAddresses defaultIps, Boolean displayvm, String keyboard, List<Long> affinityGroupIdList)
         throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException {
 
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
         List<NetworkVO> networkList = new ArrayList<NetworkVO>();
 
         // Verify that caller can perform actions in behalf of vm owner
@@ -2779,7 +2778,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
         if (s_logger.isDebugEnabled()) {
             s_logger.debug("Successfully allocated DB entry for " + vm);
         }
-        UserContext.current().setEventDetails("Vm Id: " + vm.getId());
+        CallContext.current().setEventDetails("Vm Id: " + vm.getId());
 
         UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_CREATE, accountId, zone.getId(), vm.getId(),
                 vm.getHostName(), offering.getId(), template.getId(), hypervisorType.toString(),
@@ -3113,8 +3112,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
     public UserVm stopVirtualMachine(long vmId, boolean forced)
             throws ConcurrentOperationException {
         // Input validation
-        Account caller = UserContext.current().getCaller();
-        Long userId = UserContext.current().getCallerUserId();
+        Account caller = CallContext.current().getCallingAccount();
+        Long userId = CallContext.current().getCallingUserId();
 
         // if account is removed, return error
         if (caller != null && caller.getRemoved() != null) {
@@ -3155,13 +3154,13 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
         // release elastic IP here
         IPAddressVO ip = _ipAddressDao.findByAssociatedVmId(profile.getId());
         if (ip != null && ip.getSystem()) {
-            UserContext ctx = UserContext.current();
+            CallContext ctx = CallContext.current();
             try {
                 long networkId = ip.getAssociatedWithNetworkId();
                 Network guestNetwork = _networkDao.findById(networkId);
                 NetworkOffering offering = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId());
                 assert (offering.getAssociatePublicIP() == true) : "User VM should not have system owned public IP associated with it when offering configured not to associate public IP.";
-                _rulesMgr.disableStaticNat(ip.getId(), ctx.getCaller(), ctx.getCallerUserId(), true);
+                _rulesMgr.disableStaticNat(ip.getId(), ctx.getCallingAccount(), ctx.getCallingUserId(), true);
             } catch (Exception ex) {
                 s_logger.warn(
                         "Failed to disable static nat and release system ip "
@@ -3195,9 +3194,9 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
                     throws ConcurrentOperationException, ResourceUnavailableException,
                     InsufficientCapacityException {
         // Input validation
-        Account callerAccount = UserContext.current().getCaller();
-        UserVO callerUser = _userDao.findById(UserContext.current()
-                .getCallerUserId());
+        Account callerAccount = CallContext.current().getCallingAccount();
+        UserVO callerUser = _userDao.findById(CallContext.current()
+                .getCallingUserId());
 
         // if account is removed, return error
         if (callerAccount != null && callerAccount.getRemoved() != null) {
@@ -3227,7 +3226,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
 
         Host destinationHost = null;
         if (hostId != null) {
-            Account account = UserContext.current().getCaller();
+            Account account = CallContext.current().getCallingAccount();
             if (!_accountService.isRootAdmin(account.getType())) {
                 throw new PermissionDeniedException(
                         "Parameter hostid can only be specified by a Root Admin, permission denied");
@@ -3329,8 +3328,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
     @Override
     public UserVm destroyVm(long vmId) throws ResourceUnavailableException,
     ConcurrentOperationException {
-        Account caller = UserContext.current().getCaller();
-        Long userId = UserContext.current().getCallerUserId();
+        Account caller = CallContext.current().getCallingAccount();
+        Long userId = CallContext.current().getCallingUserId();
 
         // Verify input parameters
         UserVmVO vm = _vmDao.findById(vmId);
@@ -3395,7 +3394,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
     public void collectVmDiskStatistics (UserVmVO userVm) {
         // support KVM only util 2013.06.25
         if (!userVm.getHypervisorType().equals(HypervisorType.KVM))
-            return;        
+            return;
     	// Collect vm disk statistics from host before stopping Vm
     	long hostId = userVm.getHostId();
     	List<String> vmNames = new ArrayList<String>();
@@ -3721,7 +3720,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
     @Override
     public VirtualMachine vmStorageMigration(Long vmId, StoragePool destPool) {
         // access check - only root admin can migrate VM
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
         if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
             if (s_logger.isDebugEnabled()) {
                 s_logger.debug("Caller is not a root admin, permission denied to migrate the VM");
@@ -3794,7 +3793,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
             throws ResourceUnavailableException, ConcurrentOperationException,
             ManagementServerException, VirtualMachineMigrationException {
         // access check - only root admin can migrate VM
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
         if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
             if (s_logger.isDebugEnabled()) {
                 s_logger.debug("Caller is not a root admin, permission denied to migrate the VM");
@@ -3920,7 +3919,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
             Map<String, String> volumeToPool) throws ResourceUnavailableException, ConcurrentOperationException,
             ManagementServerException, VirtualMachineMigrationException {
         // Access check - only root administrator can migrate VM.
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
         if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
             if (s_logger.isDebugEnabled()) {
                 s_logger.debug("Caller is not a root admin, permission denied to migrate the VM");
@@ -4044,7 +4043,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
         // VERIFICATIONS and VALIDATIONS
 
         // VV 1: verify the two users
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
         if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN
                 && caller.getType() != Account.ACCOUNT_TYPE_DOMAIN_ADMIN) { // only
             // root
@@ -4383,7 +4382,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
                             // if the network offering has persistent set to true, implement the network
                             if (requiredOfferings.get(0).getIsPersistent()) {
                                 DeployDestination dest = new DeployDestination(zone, null, null, null);
-                                UserVO callerUser = _userDao.findById(UserContext.current().getCallerUserId());
+                                UserVO callerUser = _userDao.findById(CallContext.current().getCallingUserId());
                                 Journal journal = new Journal.LogJournal("Implementing " + newNetwork, s_logger);
                                 ReservationContext context = new ReservationContextImpl(UUID.randomUUID().toString(),
                                         journal, callerUser, caller);
@@ -4453,7 +4452,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
     @Override
     public UserVm restoreVM(RestoreVMCmd cmd) throws InsufficientCapacityException, ResourceUnavailableException {
         // Input validation
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
 
         long vmId = cmd.getVmId();
         Long newTemplateId = cmd.getTemplateId();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/11e1e585/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java b/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java
index 8687163..686c688 100644
--- a/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java
+++ b/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java
@@ -28,9 +28,11 @@ import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
 import org.apache.cloudstack.api.command.user.vmsnapshot.ListVMSnapshotCmd;
+import org.apache.cloudstack.context.CallContext;
 import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
 import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
 import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
+
 import org.apache.log4j.Logger;
 import org.springframework.stereotype.Component;
 
@@ -72,7 +74,6 @@ import com.cloud.storage.dao.SnapshotDao;
 import com.cloud.storage.dao.VolumeDao;
 import com.cloud.user.Account;
 import com.cloud.user.AccountManager;
-import com.cloud.user.UserContext;
 import com.cloud.user.UserVO;
 import com.cloud.user.dao.AccountDao;
 import com.cloud.user.dao.UserDao;
@@ -232,7 +233,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana
     }
 
     protected Account getCaller(){
-        return UserContext.current().getCaller();
+        return CallContext.current().getCallingAccount();
     }
     
     @Override
@@ -663,7 +664,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana
                     "VM Snapshot reverting failed due to vm snapshot is not in the state of Created.");
         }
 
-        UserVO callerUser = _userDao.findById(UserContext.current().getCallerUserId());
+        UserVO callerUser = _userDao.findById(CallContext.current().getCallingUserId());
         
         UserVmVO vm = null;
         Long hostId = null;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/11e1e585/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 5211279..287e622 100644
--- a/server/src/org/apache/cloudstack/affinity/AffinityGroupServiceImpl.java
+++ b/server/src/org/apache/cloudstack/affinity/AffinityGroupServiceImpl.java
@@ -28,10 +28,13 @@ import javax.naming.ConfigurationException;
 
 import org.apache.cloudstack.affinity.dao.AffinityGroupDao;
 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.event.ActionEvent;
 import com.cloud.event.EventTypes;
@@ -41,7 +44,6 @@ import com.cloud.exception.ResourceInUseException;
 import com.cloud.network.security.SecurityGroup;
 import com.cloud.user.Account;
 import com.cloud.user.AccountManager;
-import com.cloud.user.UserContext;
 import com.cloud.uservm.UserVm;
 import com.cloud.utils.Pair;
 import com.cloud.utils.component.ComponentContext;
@@ -85,7 +87,7 @@ public class AffinityGroupServiceImpl extends ManagerBase implements AffinityGro
     public AffinityGroup createAffinityGroup(String account, Long domainId, String affinityGroupName,
             String affinityGroupType, String description) {
 
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
         Account owner = _accountMgr.finalizeOwner(caller, account, domainId, null);
 
         if (_affinityGroupDao.isNameInUse(owner.getAccountId(), owner.getDomainId(), affinityGroupName)) {
@@ -127,7 +129,7 @@ public class AffinityGroupServiceImpl extends ManagerBase implements AffinityGro
     @ActionEvent(eventType = EventTypes.EVENT_AFFINITY_GROUP_DELETE, eventDescription = "Deleting affinity group")
     public boolean deleteAffinityGroup(Long affinityGroupId, String account, Long domainId, String affinityGroupName) {
 
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
         Account owner = _accountMgr.finalizeOwner(caller, account, domainId, null);
 
         AffinityGroupVO group = null;
@@ -187,7 +189,7 @@ public class AffinityGroupServiceImpl extends ManagerBase implements AffinityGro
     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 = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
 
         Long accountId = caller.getAccountId();
         Long domainId = caller.getDomainId();
@@ -329,7 +331,7 @@ public class AffinityGroupServiceImpl extends ManagerBase implements AffinityGro
                     + "; make sure the virtual machine is stopped and not in an error state before updating.");
         }
 
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
         Account owner = _accountMgr.getAccount(vmInstance.getAccountId());
 
         // check that the affinity groups exist

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/11e1e585/server/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerManagerImpl.java b/server/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerManagerImpl.java
index ac3b8f5..560768c 100644
--- a/server/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerManagerImpl.java
+++ b/server/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerManagerImpl.java
@@ -26,8 +26,10 @@ import javax.inject.Inject;
 
 import org.apache.cloudstack.acl.SecurityChecker.AccessType;
 import org.apache.cloudstack.api.command.user.loadbalancer.ListApplicationLoadBalancersCmd;
+import org.apache.cloudstack.context.CallContext;
 import org.apache.cloudstack.lb.ApplicationLoadBalancerRuleVO;
 import org.apache.cloudstack.lb.dao.ApplicationLoadBalancerRuleDao;
+
 import org.apache.log4j.Logger;
 import org.springframework.stereotype.Component;
 
@@ -59,7 +61,6 @@ import com.cloud.tags.ResourceTagVO;
 import com.cloud.tags.dao.ResourceTagDao;
 import com.cloud.user.Account;
 import com.cloud.user.AccountManager;
-import com.cloud.user.UserContext;
 import com.cloud.utils.Pair;
 import com.cloud.utils.Ternary;
 import com.cloud.utils.component.ManagerBase;
@@ -99,7 +100,7 @@ public class ApplicationLoadBalancerManagerImpl extends ManagerBase implements A
             throw new InvalidParameterValueException("Can't find guest network by id");
         }
         
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
         _accountMgr.checkAccess(caller, AccessType.UseNetwork, false, guestNtwk);
         
         Network sourceIpNtwk = _networkModel.getNetwork(sourceIpNetworkId);
@@ -166,7 +167,7 @@ public class ApplicationLoadBalancerManagerImpl extends ManagerBase implements A
             }
             s_logger.debug("Load balancer " + newRule.getId() + " for Ip address " + newRule.getSourceIp().addr() + ", source port "
                     + newRule.getSourcePortStart() + ", instance port " + newRule.getDefaultPortStart() + " is added successfully.");
-            UserContext.current().setEventDetails("Load balancer Id: " + newRule.getId());
+            CallContext.current().setEventDetails("Load balancer Id: " + newRule.getId());
             Network ntwk = _networkModel.getNetwork(newRule.getNetworkId());
             UsageEventUtils.publishUsageEvent(EventTypes.EVENT_LOAD_BALANCER_CREATE, newRule.getAccountId(),
                     ntwk.getDataCenterId(), newRule.getId(), null, LoadBalancingRule.class.getName(),
@@ -373,7 +374,7 @@ public class ApplicationLoadBalancerManagerImpl extends ManagerBase implements A
         
         Map<String, String> tags = cmd.getTags();
 
-        Account caller = UserContext.current().getCaller();
+        Account caller = CallContext.current().getCallingAccount();
         List<Long> permittedAccounts = new ArrayList<Long>();
 
         Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/11e1e585/server/src/org/apache/cloudstack/region/gslb/GlobalLoadBalancingRulesServiceImpl.java
----------------------------------------------------------------------
diff --git a/server/src/org/apache/cloudstack/region/gslb/GlobalLoadBalancingRulesServiceImpl.java b/server/src/org/apache/cloudstack/region/gslb/GlobalLoadBalancingRulesServiceImpl.java
index ad36fae..38ba37c 100644
--- a/server/src/org/apache/cloudstack/region/gslb/GlobalLoadBalancingRulesServiceImpl.java
+++ b/server/src/org/apache/cloudstack/region/gslb/GlobalLoadBalancingRulesServiceImpl.java
@@ -34,20 +34,23 @@ import com.cloud.region.ha.GlobalLoadBalancerRule;
 import com.cloud.region.ha.GlobalLoadBalancingRulesService;
 import com.cloud.user.Account;
 import com.cloud.user.AccountManager;
-import com.cloud.user.UserContext;
 import com.cloud.utils.Pair;
 import com.cloud.utils.db.DB;
 import com.cloud.utils.db.Transaction;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.utils.net.NetUtils;
+
 import org.apache.cloudstack.acl.SecurityChecker;
 import org.apache.cloudstack.api.command.user.region.ha.gslb.*;
+import org.apache.cloudstack.context.CallContext;
 import org.apache.cloudstack.region.Region;
 import org.apache.cloudstack.region.dao.RegionDao;
+
 import org.apache.log4j.Logger;
 
 import javax.ejb.Local;
 import javax.inject.Inject;
+
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
@@ -150,8 +153,8 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR
             "Assigning a load balancer rule to global load balancer rule", async=true)
     public boolean assignToGlobalLoadBalancerRule(AssignToGlobalLoadBalancerRuleCmd assignToGslbCmd) {
 
-        UserContext ctx = UserContext.current();
-        Account caller = ctx.getCaller();
+        CallContext ctx = CallContext.current();
+        Account caller = ctx.getCallingAccount();
 
         long gslbRuleId =  assignToGslbCmd.getGlobalLoadBalancerRuleId();
         GlobalLoadBalancerRuleVO gslbRule = _gslbRuleDao.findById(gslbRuleId);
@@ -292,8 +295,8 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR
             "Removing a load balancer rule to be part of global load balancer rule")
     public boolean removeFromGlobalLoadBalancerRule(RemoveFromGlobalLoadBalancerRuleCmd removeFromGslbCmd) {
 
-        UserContext ctx = UserContext.current();
-        Account caller = ctx.getCaller();
+        CallContext ctx = CallContext.current();
+        Account caller = ctx.getCallingAccount();
 
         long gslbRuleId =  removeFromGslbCmd.getGlobalLoadBalancerRuleId();
         GlobalLoadBalancerRuleVO gslbRule = _gslbRuleDao.findById(gslbRuleId);
@@ -405,8 +408,8 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR
             "Delete global load balancer rule")
     public boolean deleteGlobalLoadBalancerRule(DeleteGlobalLoadBalancerRuleCmd deleteGslbCmd) {
 
-        UserContext ctx = UserContext.current();
-        Account caller = ctx.getCaller();
+        CallContext ctx = CallContext.current();
+        Account caller = ctx.getCallingAccount();
         long gslbRuleId =  deleteGslbCmd.getGlobalLoadBalancerId();
 
         try {
@@ -493,8 +496,8 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR
             throw new InvalidParameterValueException("Invalid global load balancer rule id: " + gslbRuleId);
         }
 
-        UserContext ctx = UserContext.current();
-        Account caller = ctx.getCaller();
+        CallContext ctx = CallContext.current();
+        Account caller = ctx.getCallingAccount();
 
         _accountMgr.checkAccess(caller, SecurityChecker.AccessType.ModifyEntry, true, gslbRule);
 
@@ -541,8 +544,8 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR
     @Override
     public List<GlobalLoadBalancerRule> listGlobalLoadBalancerRule(ListGlobalLoadBalancerRuleCmd listGslbCmd) {
 
-        UserContext ctx = UserContext.current();
-        Account caller = ctx.getCaller();
+        CallContext ctx = CallContext.current();
+        Account caller = ctx.getCallingAccount();
 
         Integer regionId =  listGslbCmd.getRegionId();
         Long ruleId = listGslbCmd.getId();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/11e1e585/server/test/com/cloud/configuration/ConfigurationManagerTest.java
----------------------------------------------------------------------
diff --git a/server/test/com/cloud/configuration/ConfigurationManagerTest.java b/server/test/com/cloud/configuration/ConfigurationManagerTest.java
index 5c1cabf..eb362b7 100755
--- a/server/test/com/cloud/configuration/ConfigurationManagerTest.java
+++ b/server/test/com/cloud/configuration/ConfigurationManagerTest.java
@@ -17,25 +17,38 @@
 
 package com.cloud.configuration;
 
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyBoolean;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.anyLong;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.when;
+
+import java.lang.reflect.Field;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.UUID;
-import java.lang.reflect.Field;
 
-import org.apache.cloudstack.api.command.admin.vlan.DedicatePublicIpRangeCmd;
-import org.apache.cloudstack.api.command.admin.vlan.ReleasePublicIpRangeCmd;
+import junit.framework.Assert;
+
 import org.apache.log4j.Logger;
+import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
+import org.apache.cloudstack.api.command.admin.vlan.DedicatePublicIpRangeCmd;
+import org.apache.cloudstack.api.command.admin.vlan.ReleasePublicIpRangeCmd;
+import org.apache.cloudstack.context.CallContext;
+
 import com.cloud.configuration.Resource.ResourceType;
 import com.cloud.dc.AccountVlanMapVO;
+import com.cloud.dc.DataCenter.NetworkType;
 import com.cloud.dc.DataCenterVO;
 import com.cloud.dc.Vlan;
 import com.cloud.dc.VlanVO;
-import com.cloud.dc.DataCenter.NetworkType;
 import com.cloud.dc.dao.AccountVlanMapDao;
 import com.cloud.dc.dao.DataCenterDao;
 import com.cloud.dc.dao.VlanDao;
@@ -48,17 +61,11 @@ import com.cloud.user.Account;
 import com.cloud.user.AccountManager;
 import com.cloud.user.AccountVO;
 import com.cloud.user.ResourceLimitService;
-import com.cloud.user.UserContext;
+import com.cloud.user.UserVO;
 import com.cloud.user.dao.AccountDao;
 import com.cloud.utils.db.Transaction;
 import com.cloud.utils.net.Ip;
 
-import junit.framework.Assert;
-
-import static org.mockito.Matchers.*;
-import static org.mockito.Mockito.when;
-import static org.mockito.Mockito.doNothing;
-
 public class ConfigurationManagerTest {
 
     private static final Logger s_logger = Logger.getLogger(ConfigurationManagerTest.class);
@@ -98,11 +105,14 @@ public class ConfigurationManagerTest {
         configurationMgr._zoneDao = _zoneDao;
         configurationMgr._firewallDao = _firewallDao;
 
-        Account account = (Account) new AccountVO("testaccount", 1, "networkdomain", (short) 0, UUID.randomUUID().toString());
+        Account account = new AccountVO("testaccount", 1, "networkdomain", (short) 0, UUID.randomUUID().toString());
         when(configurationMgr._accountMgr.getAccount(anyLong())).thenReturn(account);
         when(configurationMgr._accountDao.findActiveAccount(anyString(), anyLong())).thenReturn(account);
         when(configurationMgr._accountMgr.getActiveAccountById(anyLong())).thenReturn(account);
 
+        UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString());
+        CallContext.register(user, account);
+
         when(configurationMgr._publicIpAddressDao.countIPs(anyLong(), anyLong(), anyBoolean())).thenReturn(1);
 
         doNothing().when(configurationMgr._resourceLimitMgr).checkResourceLimit(any(Account.class),
@@ -112,8 +122,6 @@ public class ConfigurationManagerTest {
 
         when(configurationMgr._vlanDao.acquireInLockTable(anyLong(), anyInt())).thenReturn(vlan);
 
-        UserContext.registerContext(1, account, null, true);
-
         Field dedicateIdField = _dedicatePublicIpRangeClass.getDeclaredField("id");
         dedicateIdField.setAccessible(true);
         dedicateIdField.set(dedicatePublicIpRangesCmd, 1L);
@@ -135,6 +143,11 @@ public class ConfigurationManagerTest {
         releaseIdField.set(releasePublicIpRangesCmd, 1L);
     }
 
+    @After
+    public void tearDown() {
+        CallContext.unregister();
+    }
+
     @Test
     public void testDedicatePublicIpRange() throws Exception {
 
@@ -400,12 +413,14 @@ public class ConfigurationManagerTest {
 
 
     public class DedicatePublicIpRangeCmdExtn extends DedicatePublicIpRangeCmd {
+        @Override
         public long getEntityOwnerId() {
             return 1;
         }
     }
 
     public class ReleasePublicIpRangeCmdExtn extends ReleasePublicIpRangeCmd {
+        @Override
         public long getEntityOwnerId() {
             return 1;
         }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/11e1e585/server/test/com/cloud/network/DedicateGuestVlanRangesTest.java
----------------------------------------------------------------------
diff --git a/server/test/com/cloud/network/DedicateGuestVlanRangesTest.java b/server/test/com/cloud/network/DedicateGuestVlanRangesTest.java
index e5d3329..d6ee630 100644
--- a/server/test/com/cloud/network/DedicateGuestVlanRangesTest.java
+++ b/server/test/com/cloud/network/DedicateGuestVlanRangesTest.java
@@ -17,21 +17,32 @@
 
 package com.cloud.network;
 
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.anyLong;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.when;
+
+import java.lang.reflect.Field;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.UUID;
-import java.lang.reflect.Field;
 
-import org.apache.cloudstack.api.command.admin.network.DedicateGuestVlanRangeCmd;
-import org.apache.cloudstack.api.command.admin.network.ListDedicatedGuestVlanRangesCmd;
-import org.apache.cloudstack.api.command.admin.network.ReleaseDedicatedGuestVlanRangeCmd;
+import junit.framework.Assert;
 
 import org.apache.log4j.Logger;
+import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
+import org.apache.cloudstack.api.command.admin.network.DedicateGuestVlanRangeCmd;
+import org.apache.cloudstack.api.command.admin.network.ListDedicatedGuestVlanRangesCmd;
+import org.apache.cloudstack.api.command.admin.network.ReleaseDedicatedGuestVlanRangeCmd;
+import org.apache.cloudstack.context.CallContext;
+
 import com.cloud.dc.DataCenterVnetVO;
 import com.cloud.dc.dao.DataCenterVnetDao;
 import com.cloud.network.dao.AccountGuestVlanMapDao;
@@ -40,18 +51,12 @@ import com.cloud.network.dao.PhysicalNetworkDao;
 import com.cloud.network.dao.PhysicalNetworkVO;
 import com.cloud.projects.ProjectManager;
 import com.cloud.user.Account;
-import com.cloud.user.dao.AccountDao;
 import com.cloud.user.AccountManager;
 import com.cloud.user.AccountVO;
-import com.cloud.user.UserContext;
+import com.cloud.user.UserVO;
+import com.cloud.user.dao.AccountDao;
 import com.cloud.utils.db.Transaction;
 
-import junit.framework.Assert;
-
-import static org.mockito.Matchers.*;
-import static org.mockito.Mockito.when;
-import static org.mockito.Mockito.doNothing;
-
 public class DedicateGuestVlanRangesTest {
 
     private static final Logger s_logger = Logger.getLogger(DedicateGuestVlanRangesTest.class);
@@ -86,11 +91,13 @@ public class DedicateGuestVlanRangesTest {
         networkService._datacneter_vnet = _dataCenterVnetDao;
         networkService._accountGuestVlanMapDao = _accountGuestVlanMapDao;
 
-        Account account = (Account) new AccountVO("testaccount", 1, "networkdomain", (short) 0, UUID.randomUUID().toString());
+        Account account = new AccountVO("testaccount", 1, "networkdomain", (short) 0, UUID.randomUUID().toString());
         when(networkService._accountMgr.getAccount(anyLong())).thenReturn(account);
         when(networkService._accountDao.findActiveAccount(anyString(), anyLong())).thenReturn(account);
+        
+        UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString());
 
-        UserContext.registerContext(1, account, null, true);
+        CallContext.register(user, account);
 
         Field accountNameField = _dedicateGuestVlanRangeClass.getDeclaredField("accountName");
         accountNameField.setAccessible(true);
@@ -113,6 +120,11 @@ public class DedicateGuestVlanRangesTest {
         releaseIdField.set(releaseDedicatedGuestVlanRangesCmd, 1L);
     }
 
+    @After
+    public void tearDown() {
+        CallContext.unregister();
+    }
+
     @Test
     public void testDedicateGuestVlanRange() throws Exception {
         s_logger.info("Running tests for DedicateGuestVlanRange API");
@@ -359,18 +371,21 @@ public class DedicateGuestVlanRangesTest {
     }
     
     public class DedicateGuestVlanRangeCmdExtn extends DedicateGuestVlanRangeCmd {
+        @Override
         public long getEntityOwnerId() {
             return 1;
         }
     }
 
     public class ReleaseDedicatedGuestVlanRangeCmdExtn extends ReleaseDedicatedGuestVlanRangeCmd {
+        @Override
         public long getEntityOwnerId() {
             return 1;
         }
     }
 
     public class ListDedicatedGuestVlanRangesCmdExtn extends ListDedicatedGuestVlanRangesCmd {
+        @Override
         public long getEntityOwnerId() {
             return 1;
         }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/11e1e585/server/test/com/cloud/vm/UserVmManagerTest.java
----------------------------------------------------------------------
diff --git a/server/test/com/cloud/vm/UserVmManagerTest.java b/server/test/com/cloud/vm/UserVmManagerTest.java
index 5eedfa5..0eb9a08 100755
--- a/server/test/com/cloud/vm/UserVmManagerTest.java
+++ b/server/test/com/cloud/vm/UserVmManagerTest.java
@@ -24,24 +24,30 @@ import static org.mockito.Matchers.anyInt;
 import static org.mockito.Matchers.anyLong;
 import static org.mockito.Matchers.anyString;
 import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.*;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.doThrow;
 import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
 
 import java.lang.reflect.Field;
 import java.util.List;
 import java.util.UUID;
 
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
+
 import org.apache.cloudstack.acl.ControlledEntity;
 import org.apache.cloudstack.acl.SecurityChecker.AccessType;
 import org.apache.cloudstack.api.ServerApiException;
 import org.apache.cloudstack.api.command.admin.vm.AssignVMCmd;
 import org.apache.cloudstack.api.command.user.vm.RestoreVMCmd;
 import org.apache.cloudstack.api.command.user.vm.ScaleVMCmd;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.mockito.Spy;
+import org.apache.cloudstack.context.CallContext;
 
 import com.cloud.capacity.CapacityManager;
 import com.cloud.configuration.ConfigurationManager;
@@ -56,18 +62,17 @@ import com.cloud.hypervisor.Hypervisor;
 import com.cloud.hypervisor.Hypervisor.HypervisorType;
 import com.cloud.offering.ServiceOffering;
 import com.cloud.service.ServiceOfferingVO;
+import com.cloud.storage.Storage.ImageFormat;
 import com.cloud.storage.VMTemplateVO;
 import com.cloud.storage.Volume;
 import com.cloud.storage.VolumeManager;
 import com.cloud.storage.VolumeVO;
 import com.cloud.storage.dao.VMTemplateDao;
 import com.cloud.storage.dao.VolumeDao;
-import com.cloud.storage.Storage.ImageFormat;
 import com.cloud.user.Account;
 import com.cloud.user.AccountManager;
 import com.cloud.user.AccountService;
 import com.cloud.user.AccountVO;
-import com.cloud.user.UserContext;
 import com.cloud.user.UserVO;
 import com.cloud.user.dao.AccountDao;
 import com.cloud.user.dao.UserDao;
@@ -138,7 +143,15 @@ public class UserVmManagerTest {
         when(_vmDao.findById(anyLong())).thenReturn(_vmMock);
         when(_templateDao.findById(anyLong())).thenReturn(_templateMock);
         doReturn(VirtualMachine.State.Error).when(_vmMock).getState();
-        _userVmMgr.restoreVMInternal(_account, _vmMock, null);
+        Account account = new AccountVO("testaccount", 1L, "networkdomain", (short)0, "uuid");
+        UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString());
+
+        CallContext.register(user, account);
+        try {
+            _userVmMgr.restoreVMInternal(_account, _vmMock, null);
+        } finally {
+            CallContext.unregister();
+        }
     }
 
     // Test restoreVm when VM is in stopped state
@@ -160,7 +173,15 @@ public class UserVmManagerTest {
       
         when(_templateMock.getUuid()).thenReturn("e0552266-7060-11e2-bbaa-d55f5db67735");
 
-        _userVmMgr.restoreVMInternal(_account, _vmMock, null);
+        Account account = new AccountVO("testaccount", 1L, "networkdomain", (short)0, "uuid");
+        UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString());
+
+        CallContext.register(user, account);
+        try {
+            _userVmMgr.restoreVMInternal(_account, _vmMock, null);
+        } finally {
+            CallContext.unregister();
+        }
 
     }
 
@@ -185,7 +206,15 @@ public class UserVmManagerTest {
      
         when(_templateMock.getUuid()).thenReturn("e0552266-7060-11e2-bbaa-d55f5db67735");
 
-        _userVmMgr.restoreVMInternal(_account, _vmMock, null);
+        Account account = new AccountVO("testaccount", 1L, "networkdomain", (short)0, "uuid");
+        UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString());
+
+        CallContext.register(user, account);
+        try {
+            _userVmMgr.restoreVMInternal(_account, _vmMock, null);
+        } finally {
+            CallContext.unregister();
+        }
 
     }
 
@@ -216,7 +245,15 @@ public class UserVmManagerTest {
       
         when(_templateMock.getUuid()).thenReturn("b1a3626e-72e0-4697-8c7c-a110940cc55d");
 
-        _userVmMgr.restoreVMInternal(_account, _vmMock, 14L);
+        Account account = new AccountVO("testaccount", 1L, "networkdomain", (short)0, "uuid");
+        UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString());
+
+        CallContext.register(user, account);
+        try {
+            _userVmMgr.restoreVMInternal(_account, _vmMock, 14L);
+        } finally {
+            CallContext.unregister();
+        }
 
     }
 
@@ -249,7 +286,15 @@ public class UserVmManagerTest {
 
         when(_templateMock.getUuid()).thenReturn("b1a3626e-72e0-4697-8c7c-a110940cc55d");
 
-        _userVmMgr.restoreVMInternal(_account, _vmMock, 14L);
+        Account account = new AccountVO("testaccount", 1L, "networkdomain", (short)0, "uuid");
+        UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString());
+
+        CallContext.register(user, account);
+        try {
+            _userVmMgr.restoreVMInternal(_account, _vmMock, 14L);
+        } finally {
+            CallContext.unregister();
+        }
 
         verify(_vmMock, times(1)).setIsoId(14L);
 
@@ -269,14 +314,19 @@ public class UserVmManagerTest {
         serviceOfferingIdField.setAccessible(true);
         serviceOfferingIdField.set(cmd, 1L);
 
+        when(_vmInstanceDao.findById(anyLong())).thenReturn(_vmInstance);
+
        // UserContext.current().setEventDetails("Vm Id: "+getId());
-        Account account = (Account) new AccountVO("testaccount", 1L, "networkdomain", (short) 0, "uuid");
-        //AccountVO(String accountName, long domainId, String networkDomain, short type, int regionId)
-       UserContext.registerContext(1, account, null, true);
+        Account account = new AccountVO("testaccount", 1L, "networkdomain", (short) 0, "uuid");
+        UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString());
 
-        when(_vmInstanceDao.findById(anyLong())).thenReturn(_vmInstance);
+        CallContext.register(user, account);
+        try {
+            _userVmMgr.upgradeVirtualMachine(cmd);
+        } finally {
+            CallContext.unregister();
+        }
 
-        _userVmMgr.upgradeVirtualMachine(cmd);
 
     }
 
@@ -306,13 +356,20 @@ public class UserVmManagerTest {
         doNothing().when(_itMgr).checkIfCanUpgrade(_vmMock, cmd.getServiceOfferingId());
 
 
-        ServiceOffering so1 =  (ServiceOffering) getSvcoffering(512);
-        ServiceOffering so2 =  (ServiceOffering) getSvcoffering(256);
+        ServiceOffering so1 =  getSvcoffering(512);
+        ServiceOffering so2 =  getSvcoffering(256);
 
         when(_configMgr.getServiceOffering(anyLong())).thenReturn(so1);
         when(_configMgr.getServiceOffering(1L)).thenReturn(so1);
 
-        _userVmMgr.upgradeVirtualMachine(cmd);
+        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());
+        CallContext.register(user, account);
+        try {
+            _userVmMgr.upgradeVirtualMachine(cmd);
+        } finally {
+            CallContext.unregister();
+        }
 
     }
 
@@ -331,17 +388,13 @@ public class UserVmManagerTest {
         serviceOfferingIdField.setAccessible(true);
         serviceOfferingIdField.set(cmd, 1L);
 
-        //UserContext.current().setEventDetails("Vm Id: "+getId());
-        //Account account = (Account) new AccountVO("testaccount", 1L, "networkdomain", (short) 0, 1);
-        //AccountVO(String accountName, long domainId, String networkDomain, short type, int regionId)
-        //UserContext.registerContext(1, account, null, true);
 
         when(_vmInstanceDao.findById(anyLong())).thenReturn(_vmInstance);
         doReturn(Hypervisor.HypervisorType.XenServer).when(_vmInstance).getHypervisorType();
 
 
-        ServiceOffering so1 =  (ServiceOffering) getSvcoffering(512);
-        ServiceOffering so2 =  (ServiceOffering) getSvcoffering(256);
+        ServiceOffering so1 =  getSvcoffering(512);
+        ServiceOffering so2 =  getSvcoffering(256);
 
         when(_configMgr.getServiceOffering(anyLong())).thenReturn(so2);
         when(_configMgr.getServiceOffering(1L)).thenReturn(so1);
@@ -354,7 +407,14 @@ public class UserVmManagerTest {
 
         //when(_vmDao.findById(anyLong())).thenReturn(_vmMock);
 
-        _userVmMgr.upgradeVirtualMachine(cmd);
+        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());
+        CallContext.register(user, account);
+        try {
+            _userVmMgr.upgradeVirtualMachine(cmd);
+        } finally {
+            CallContext.unregister();
+        }
 
     }
 
@@ -380,8 +440,8 @@ public class UserVmManagerTest {
         when(_vmInstanceDao.findById(anyLong())).thenReturn(_vmInstance);
         doReturn(Hypervisor.HypervisorType.XenServer).when(_vmInstance).getHypervisorType();
 
-        ServiceOffering so1 =  (ServiceOffering) getSvcoffering(512);
-        ServiceOffering so2 =  (ServiceOffering) getSvcoffering(256);
+        ServiceOffering so1 =  getSvcoffering(512);
+        ServiceOffering so2 =  getSvcoffering(256);
 
         when(_configMgr.getServiceOffering(anyLong())).thenReturn(so2);
         when(_configMgr.getServiceOffering(1L)).thenReturn(so1);
@@ -396,7 +456,14 @@ public class UserVmManagerTest {
 
         when(_vmDao.findById(anyLong())).thenReturn(_vmMock);
 
-        _userVmMgr.upgradeVirtualMachine(cmd);
+        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());
+        CallContext.register(user, account);
+        try {
+            _userVmMgr.upgradeVirtualMachine(cmd);
+        } finally {
+            CallContext.unregister();
+        }
 
     }
 
@@ -435,11 +502,17 @@ public class UserVmManagerTest {
         domainIdField.set(cmd, 1L);
 
         // caller is of type 0
-        Account caller = (Account) new AccountVO("testaccount", 1, "networkdomain", (short) 0,
+        Account caller = new AccountVO("testaccount", 1, "networkdomain", (short) 0,
                 UUID.randomUUID().toString());
-        UserContext.registerContext(1, caller, null, true);
+        UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString());
+
+        CallContext.register(user, caller);
+        try {
 
         _userVmMgr.moveVMToUser(cmd);
+        } finally {
+            CallContext.unregister();
+        }
     }
 
 
@@ -462,13 +535,13 @@ public class UserVmManagerTest {
         domainIdField.set(cmd, 1L);
 
         // caller is of type 0
-        Account caller = (Account) new AccountVO("testaccount", 1, "networkdomain", (short) 1,
-                UUID.randomUUID().toString());
-        UserContext.registerContext(1, caller, null, true);
+        Account caller = new AccountVO("testaccount", 1, "networkdomain", (short)1, UUID.randomUUID().toString());
+        UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString());
+
 
-        Account oldAccount = (Account) new AccountVO("testaccount", 1, "networkdomain", (short) 0,
+        Account oldAccount = new AccountVO("testaccount", 1, "networkdomain", (short) 0,
                 UUID.randomUUID().toString());
-        Account newAccount = (Account) new AccountVO("testaccount", 1, "networkdomain", (short) 1,
+        Account newAccount = new AccountVO("testaccount", 1, "networkdomain", (short) 1,
                 UUID.randomUUID().toString());
 
         UserVmVO vm = new UserVmVO(10L, "test", "test", 1L, HypervisorType.Any, 1L, false, false, 1L, 1L,
@@ -483,7 +556,12 @@ public class UserVmManagerTest {
         doThrow(new PermissionDeniedException("Access check failed")).when(_accountMgr).checkAccess(any(Account.class), any(AccessType.class),
                 any(Boolean.class), any(ControlledEntity.class));
 
-        _userVmMgr.moveVMToUser(cmd);
+        CallContext.register(user, caller);
+        try {
+            _userVmMgr.moveVMToUser(cmd);
+        } finally {
+            CallContext.unregister();
+        }
     }
 
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/11e1e585/server/test/com/cloud/vpc/NetworkACLManagerTest.java
----------------------------------------------------------------------
diff --git a/server/test/com/cloud/vpc/NetworkACLManagerTest.java b/server/test/com/cloud/vpc/NetworkACLManagerTest.java
index ddcfe7f..446e4e1 100644
--- a/server/test/com/cloud/vpc/NetworkACLManagerTest.java
+++ b/server/test/com/cloud/vpc/NetworkACLManagerTest.java
@@ -15,6 +15,35 @@
 
 package com.cloud.vpc;
 
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+
+import javax.inject.Inject;
+
+import junit.framework.TestCase;
+
+import org.apache.log4j.Logger;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mockito;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.FilterType;
+import org.springframework.core.type.classreading.MetadataReader;
+import org.springframework.core.type.classreading.MetadataReaderFactory;
+import org.springframework.core.type.filter.TypeFilter;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.support.AnnotationConfigContextLoader;
+
+import org.apache.cloudstack.context.CallContext;
+import org.apache.cloudstack.test.utils.SpringUtils;
+
 import com.cloud.configuration.ConfigurationManager;
 import com.cloud.network.Network;
 import com.cloud.network.NetworkManager;
@@ -35,32 +64,9 @@ import com.cloud.tags.dao.ResourceTagDao;
 import com.cloud.user.Account;
 import com.cloud.user.AccountManager;
 import com.cloud.user.AccountVO;
-import com.cloud.user.UserContext;
+import com.cloud.user.UserVO;
 import com.cloud.utils.component.ComponentContext;
 import com.cloud.utils.exception.CloudRuntimeException;
-import junit.framework.TestCase;
-import org.apache.cloudstack.test.utils.SpringUtils;
-import org.apache.log4j.Logger;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mockito;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.ComponentScan;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.FilterType;
-import org.springframework.core.type.classreading.MetadataReader;
-import org.springframework.core.type.classreading.MetadataReaderFactory;
-import org.springframework.core.type.filter.TypeFilter;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.test.context.support.AnnotationConfigContextLoader;
-
-import javax.inject.Inject;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.UUID;
 
 @RunWith(SpringJUnit4ClassRunner.class)
 @ContextConfiguration(loader = AnnotationConfigContextLoader.class)
@@ -90,15 +96,24 @@ public class NetworkACLManagerTest extends TestCase{
 
     private static final Logger s_logger = Logger.getLogger( NetworkACLManagerTest.class);
 
+    @Override
     @Before
     public void setUp() {
         ComponentContext.initComponentsLifeCycle();
         Account account = new AccountVO("testaccount", 1, "testdomain", (short) 0, UUID.randomUUID().toString());
-        UserContext.registerContext(1, account, null, true);
+        UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString());
+
+        CallContext.register(user, account);
         acl = Mockito.mock(NetworkACLVO.class);
         aclItem = Mockito.mock(NetworkACLItemVO.class);
     }
 
+    @Override
+    @After
+    public void tearDown() {
+        CallContext.unregister();
+    }
+
     @Test
     public void testCreateACL() throws Exception {
         Mockito.when(_networkACLDao.persist(Mockito.any(NetworkACLVO.class))).thenReturn(acl);


Mime
View raw message