You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by bh...@apache.org on 2012/12/08 02:05:21 UTC

[2/3] api: Refactoring ListEventsCmd and EventResponse, and create Event db view.

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/30941c2d/server/src/com/cloud/server/ManagementServerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java
index fba6ac9..41727b6 100755
--- a/server/src/com/cloud/server/ManagementServerImpl.java
+++ b/server/src/com/cloud/server/ManagementServerImpl.java
@@ -5,7 +5,7 @@
 // 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,
@@ -99,6 +99,7 @@ import org.apache.cloudstack.api.admin.systemvm.command.UpgradeSystemVMCmd;
 import org.apache.cloudstack.api.admin.resource.command.UploadCustomCertificateCmd;
 import com.cloud.api.response.ExtractResponse;
 import com.cloud.api.view.vo.DomainRouterJoinVO;
+import com.cloud.api.view.vo.EventJoinVO;
 import com.cloud.async.AsyncJob;
 import com.cloud.async.AsyncJobExecutor;
 import com.cloud.async.AsyncJobManager;
@@ -141,6 +142,7 @@ import com.cloud.event.EventTypes;
 import com.cloud.event.EventUtils;
 import com.cloud.event.EventVO;
 import com.cloud.event.dao.EventDao;
+import com.cloud.event.dao.EventJoinDao;
 import com.cloud.exception.CloudAuthenticationException;
 import com.cloud.exception.ConcurrentOperationException;
 import com.cloud.exception.InvalidParameterValueException;
@@ -281,6 +283,7 @@ public class ManagementServerImpl implements ManagementServer {
     private final ClusterDao _clusterDao;
     private final SecondaryStorageVmDao _secStorageVmDao;
     private final EventDao _eventDao;
+    private final EventJoinDao _eventJoinDao;
     private final DataCenterDao _dcDao;
     private final VlanDao _vlanDao;
     private final AccountVlanMapDao _accountVlanMapDao;
@@ -322,7 +325,7 @@ public class ManagementServerImpl implements ManagementServer {
     private final Adapters<HostAllocator> _hostAllocators;
     private final ConfigurationManager _configMgr;
     private final ResourceTagDao _resourceTagDao;
-    
+
     @Inject
     ProjectManager _projectMgr;
     private final ResourceManager _resourceMgr;
@@ -342,7 +345,7 @@ public class ManagementServerImpl implements ManagementServer {
     private final StatsCollector _statsCollector;
 
     private final Map<String, Boolean> _availableIdsMap;
-    
+
     private Adapters<UserAuthenticator> _userAuthenticators;
 
     private String _hashKey = null;
@@ -353,6 +356,7 @@ public class ManagementServerImpl implements ManagementServer {
         _routerDao = locator.getDao(DomainRouterDao.class);
         _routerJoinDao = locator.getDao(DomainRouterJoinDao.class);
         _eventDao = locator.getDao(EventDao.class);
+        _eventJoinDao = locator.getDao(EventJoinDao.class);
         _dcDao = locator.getDao(DataCenterDao.class);
         _vlanDao = locator.getDao(VlanDao.class);
         _accountVlanMapDao = locator.getDao(AccountVlanMapDao.class);
@@ -424,7 +428,7 @@ public class ManagementServerImpl implements ManagementServer {
         for (String id : availableIds) {
             _availableIdsMap.put(id, true);
         }
-        
+
         _userAuthenticators = locator.getAdapters(UserAuthenticator.class);
         if (_userAuthenticators == null || !_userAuthenticators.isSet()) {
             s_logger.error("Unable to find an user authenticator.");
@@ -450,8 +454,10 @@ public class ManagementServerImpl implements ManagementServer {
         String keyword = cmd.getKeyword();
         if (domainId != null) {
             // for domainId != null
-            // right now, we made the decision to only list zones associated with this domain
-            dcs = _dcDao.findZonesByDomainId(domainId, keyword); // private zones
+            // right now, we made the decision to only list zones associated
+            // with this domain
+            dcs = _dcDao.findZonesByDomainId(domainId, keyword); // private
+                                                                 // zones
         } else if ((account == null || account.getType() == Account.ACCOUNT_TYPE_ADMIN)) {
             if (keyword != null) {
                 dcs = _dcDao.findByKeyword(keyword);
@@ -459,7 +465,8 @@ public class ManagementServerImpl implements ManagementServer {
                 dcs = _dcDao.listAll(); // all zones
             }
         } else if (account.getType() == Account.ACCOUNT_TYPE_NORMAL) {
-            // it was decided to return all zones for the user's domain, and everything above till root
+            // it was decided to return all zones for the user's domain, and
+            // everything above till root
             // list all zones belonging to this domain, and all of its parents
             // check the parent, if not null, add zones for that parent to list
             dcs = new ArrayList<DataCenterVO>();
@@ -478,7 +485,8 @@ public class ManagementServerImpl implements ManagementServer {
             dcs.addAll(_dcDao.listPublicZones(keyword));
             removeDisabledZones = true;
         } else if (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
-            // it was decided to return all zones for the domain admin, and everything above till root
+            // it was decided to return all zones for the domain admin, and
+            // everything above till root
             dcs = new ArrayList<DataCenterVO>();
             DomainVO domainRecord = _domainDao.findById(account.getDomainId());
             // this covers path till root
@@ -495,7 +503,8 @@ public class ManagementServerImpl implements ManagementServer {
             }
             // this covers till leaf
             if (domainRecord != null) {
-                // find all children for this domain based on a like search by path
+                // find all children for this domain based on a like search by
+                // path
                 List<DomainVO> allChildDomains = _domainDao.findAllChildren(domainRecord.getPath(), domainRecord.getId());
                 List<Long> allChildDomainIds = new ArrayList<Long>();
                 // create list of domainIds for search
@@ -568,11 +577,14 @@ public class ManagementServerImpl implements ManagementServer {
             throw new InvalidParameterValueException("privatePort is an invalid value");
         }
 
-        // s_logger.debug("Checking if " + privateIp + " is a valid private IP address. Guest IP address is: " +
+        // s_logger.debug("Checking if " + privateIp +
+        // " is a valid private IP address. Guest IP address is: " +
         // _configs.get("guest.ip.network"));
         //
-        // if (!NetUtils.isValidPrivateIp(privateIp, _configs.get("guest.ip.network"))) {
-        // throw new InvalidParameterValueException("Invalid private ip address");
+        // if (!NetUtils.isValidPrivateIp(privateIp,
+        // _configs.get("guest.ip.network"))) {
+        // throw new
+        // InvalidParameterValueException("Invalid private ip address");
         // }
         if (!NetUtils.isValidProto(proto)) {
             throw new InvalidParameterValueException("Invalid protocol");
@@ -621,7 +633,8 @@ public class ManagementServerImpl implements ManagementServer {
         return cal.getTime();
     }
 
-    // This method is used for permissions check for both disk and service offerings
+    // This method is used for permissions check for both disk and service
+    // offerings
     private boolean isPermissible(Long accountDomainId, Long offeringDomainId) {
 
         if (accountDomainId == offeringDomainId) {
@@ -652,11 +665,13 @@ public class ManagementServerImpl implements ManagementServer {
     public List<ServiceOfferingVO> searchForServiceOfferings(ListServiceOfferingsCmd cmd) {
 
         // Note
-        // The list method for offerings is being modified in accordance with discussion with Will/Kevin
+        // The list method for offerings is being modified in accordance with
+        // discussion with Will/Kevin
         // For now, we will be listing the following based on the usertype
         // 1. For root, we will list all offerings
-        // 2. For domainAdmin and regular users, we will list everything in their domains+parent domains ... all the way
-// till
+        // 2. For domainAdmin and regular users, we will list everything in
+        // their domains+parent domains ... all the way
+        // till
         // root
         Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm"));
         isAscending = (isAscending == null ? true : isAscending);
@@ -677,16 +692,20 @@ public class ManagementServerImpl implements ManagementServer {
         }
 
         // Keeping this logic consistent with domain specific zones
-        // if a domainId is provided, we just return the so associated with this domain
+        // if a domainId is provided, we just return the so associated with this
+        // domain
         if (domainId != null && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
-            // check if the user's domain == so's domain || user's domain is a child of so's domain
+            // check if the user's domain == so's domain || user's domain is a
+            // child of so's domain
             if (!isPermissible(caller.getDomainId(), domainId)) {
-                throw new PermissionDeniedException("The account:" + caller.getAccountName() + " does not fall in the same domain hierarchy as the service offering");
+                throw new PermissionDeniedException("The account:" + caller.getAccountName()
+                        + " does not fall in the same domain hierarchy as the service offering");
             }
         }
 
         // For non-root users
-        if ((caller.getType() == Account.ACCOUNT_TYPE_NORMAL || caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
+        if ((caller.getType() == Account.ACCOUNT_TYPE_NORMAL || caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)
+                || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
             if (isSystem) {
                 throw new InvalidParameterValueException("Only root admins can access system's offering");
             }
@@ -707,8 +726,8 @@ public class ManagementServerImpl implements ManagementServer {
         } else if (vmId != null) {
             UserVmVO vmInstance = _userVmDao.findById(vmId);
             if ((vmInstance == null) || (vmInstance.getRemoved() != null)) {
-            	InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with specified id");
-            	ex.addProxyObject(vmInstance, vmId, "vmId");
+                InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with specified id");
+                ex.addProxyObject(vmInstance, vmId, "vmId");
                 throw ex;
             }
 
@@ -717,8 +736,10 @@ public class ManagementServerImpl implements ManagementServer {
             ServiceOfferingVO offering = _offeringsDao.findByIdIncludingRemoved(vmInstance.getServiceOfferingId());
             sc.addAnd("id", SearchCriteria.Op.NEQ, offering.getId());
 
-            // Only return offerings with the same Guest IP type and storage pool preference
-            // sc.addAnd("guestIpType", SearchCriteria.Op.EQ, offering.getGuestIpType());
+            // Only return offerings with the same Guest IP type and storage
+            // pool preference
+            // sc.addAnd("guestIpType", SearchCriteria.Op.EQ,
+            // offering.getGuestIpType());
             sc.addAnd("useLocalStorage", SearchCriteria.Op.EQ, offering.getUseLocalStorage());
         }
         if (id != null) {
@@ -747,10 +768,12 @@ public class ManagementServerImpl implements ManagementServer {
 
     }
 
-    private List<ServiceOfferingVO> searchServiceOfferingsInternal(Account caller, Object name, Object id, Long vmId, Object keyword, Filter searchFilter) {
+    private List<ServiceOfferingVO> searchServiceOfferingsInternal(Account caller, Object name, Object id, Long vmId, Object keyword,
+            Filter searchFilter) {
 
-        // it was decided to return all offerings for the user's domain, and everything above till root (for normal user
-// or
+        // it was decided to return all offerings for the user's domain, and
+        // everything above till root (for normal user
+        // or
         // domain admin)
         // list all offerings belonging to this domain, and all of its parents
         // check the parent, if not null, add offerings for that parent to list
@@ -779,11 +802,11 @@ public class ManagementServerImpl implements ManagementServer {
                 } else if (vmId != null) {
                     UserVmVO vmInstance = _userVmDao.findById(vmId);
                     if ((vmInstance == null) || (vmInstance.getRemoved() != null)) {
-                    	InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
-                    	ex.addProxyObject(vmInstance, vmId, "vmId");
+                        InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
+                        ex.addProxyObject(vmInstance, vmId, "vmId");
                         throw ex;
                     }
-                    
+
                     _accountMgr.checkAccess(caller, null, false, vmInstance);
 
                     ServiceOfferingVO offering = _offeringsDao.findById(vmInstance.getServiceOfferingId());
@@ -826,20 +849,20 @@ public class ManagementServerImpl implements ManagementServer {
 
         return sol;
     }
-    
+
     @Override
     public List<? extends Cluster> searchForClusters(long zoneId, Long startIndex, Long pageSizeVal, String hypervisorType) {
-    	Filter searchFilter = new Filter(ClusterVO.class, "id", true, startIndex, pageSizeVal);
-    	SearchCriteria<ClusterVO> sc = _clusterDao.createSearchCriteria();
-    	
-    	zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), zoneId);
+        Filter searchFilter = new Filter(ClusterVO.class, "id", true, startIndex, pageSizeVal);
+        SearchCriteria<ClusterVO> sc = _clusterDao.createSearchCriteria();
+
+        zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), zoneId);
 
-    	sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId);
-    	sc.addAnd("hypervisorType", SearchCriteria.Op.EQ, hypervisorType);
-    	
-    	return _clusterDao.search(sc, searchFilter);
+        sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId);
+        sc.addAnd("hypervisorType", SearchCriteria.Op.EQ, hypervisorType);
+
+        return _clusterDao.search(sc, searchFilter);
     }
-    
+
     @Override
     public Pair<List<? extends Cluster>, Integer> searchForClusters(ListClustersCmd cmd) {
         Filter searchFilter = new Filter(ClusterVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
@@ -909,7 +932,8 @@ public class ManagementServerImpl implements ManagementServer {
         Object resourceState = cmd.getResourceState();
         Object haHosts = cmd.getHaHost();
 
-        return searchForServers(cmd.getStartIndex(), cmd.getPageSizeVal(), name, type, state, zoneId, pod, cluster, id, keyword, resourceState, haHosts);
+        return searchForServers(cmd.getStartIndex(), cmd.getPageSizeVal(), name, type, state, zoneId, pod, cluster, id, keyword, resourceState,
+                haHosts);
     }
 
     @Override
@@ -925,8 +949,8 @@ public class ManagementServerImpl implements ManagementServer {
 
         VMInstanceVO vm = _vmInstanceDao.findById(vmId);
         if (vm == null) {
-        	InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find the VM with specified id");
-        	ex.addProxyObject(vm, vmId, "vmId");
+            InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find the VM with specified id");
+            ex.addProxyObject(vm, vmId, "vmId");
             throw ex;
         }
         // business logic
@@ -939,8 +963,8 @@ public class ManagementServerImpl implements ManagementServer {
             throw ex;
         }
 
-        if (!vm.getHypervisorType().equals(HypervisorType.XenServer) && !vm.getHypervisorType().equals(HypervisorType.VMware) && !vm.getHypervisorType().equals(HypervisorType.KVM)
-                && !vm.getHypervisorType().equals(HypervisorType.Ovm)) {
+        if (!vm.getHypervisorType().equals(HypervisorType.XenServer) && !vm.getHypervisorType().equals(HypervisorType.VMware)
+                && !vm.getHypervisorType().equals(HypervisorType.KVM) && !vm.getHypervisorType().equals(HypervisorType.Ovm)) {
             if (s_logger.isDebugEnabled()) {
                 s_logger.debug(vm + " is not XenServer/VMware/KVM/OVM, cannot migrate this VM.");
             }
@@ -960,8 +984,9 @@ public class ManagementServerImpl implements ManagementServer {
             if (s_logger.isDebugEnabled()) {
                 s_logger.debug("Unable to find the host with id: " + srcHostId + " of this VM:" + vm);
             }
-            InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find the host (with specified id) of VM with specified id");
-            ex.addProxyObject(srcHost, srcHostId, "hostId");            
+            InvalidParameterValueException ex = new InvalidParameterValueException(
+                    "Unable to find the host (with specified id) of VM with specified id");
+            ex.addProxyObject(srcHost, srcHostId, "hostId");
             ex.addProxyObject(vm, vmId, "vmId");
             throw ex;
         }
@@ -971,7 +996,8 @@ public class ManagementServerImpl implements ManagementServer {
             s_logger.debug("Searching for all hosts in cluster: " + cluster + " for migrating VM " + vm);
         }
 
-        List<? extends Host> allHostsInCluster = searchForServers(startIndex, pageSize, null, hostType, null, null, null, cluster, null, null, null, null);
+        List<? extends Host> allHostsInCluster = searchForServers(startIndex, pageSize, null, hostType, null, null, null, cluster, null, null, null,
+                null);
         // filter out the current host
         allHostsInCluster.remove(srcHost);
 
@@ -1010,10 +1036,10 @@ public class ManagementServerImpl implements ManagementServer {
         return new Pair<List<? extends Host>, List<? extends Host>>(allHostsInCluster, suitableHosts);
     }
 
-    private List<HostVO> searchForServers(Long startIndex, Long pageSize, Object name, Object type, Object state, Object zone, Object pod, Object cluster, Object id, Object keyword,
-            Object resourceState, Object haHosts) {
+    private List<HostVO> searchForServers(Long startIndex, Long pageSize, Object name, Object type, Object state, Object zone, Object pod,
+            Object cluster, Object id, Object keyword, Object resourceState, Object haHosts) {
         Filter searchFilter = new Filter(HostVO.class, "id", Boolean.TRUE, startIndex, pageSize);
-        
+
         SearchBuilder<HostVO> sb = _hostDao.createSearchBuilder();
         sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
         sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE);
@@ -1023,12 +1049,12 @@ public class ManagementServerImpl implements ManagementServer {
         sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ);
         sb.and("clusterId", sb.entity().getClusterId(), SearchCriteria.Op.EQ);
         sb.and("resourceState", sb.entity().getResourceState(), SearchCriteria.Op.EQ);
-        
+
         String haTag = _haMgr.getHaTag();
         SearchBuilder<HostTagVO> hostTagSearch = null;
         if (haHosts != null && haTag != null && !haTag.isEmpty()) {
             hostTagSearch = _hostTagsDao.createSearchBuilder();
-            if ((Boolean)haHosts) {
+            if ((Boolean) haHosts) {
                 hostTagSearch.and().op("tag", hostTagSearch.entity().getTag(), SearchCriteria.Op.EQ);
             } else {
                 hostTagSearch.and().op("tag", hostTagSearch.entity().getTag(), SearchCriteria.Op.NEQ);
@@ -1036,9 +1062,9 @@ public class ManagementServerImpl implements ManagementServer {
             }
 
             hostTagSearch.cp();
-            sb.join("hostTagSearch", hostTagSearch, sb.entity().getId(), hostTagSearch.entity().getHostId(), JoinBuilder.JoinType.LEFTOUTER); 
+            sb.join("hostTagSearch", hostTagSearch, sb.entity().getId(), hostTagSearch.entity().getHostId(), JoinBuilder.JoinType.LEFTOUTER);
         }
-        
+
         SearchCriteria<HostVO> sc = sb.create();
 
         if (keyword != null) {
@@ -1076,7 +1102,7 @@ public class ManagementServerImpl implements ManagementServer {
         if (resourceState != null) {
             sc.setParameters("resourceState", resourceState);
         }
-        
+
         if (haHosts != null && haTag != null && !haTag.isEmpty()) {
             sc.setJoinParameters("hostTagSearch", "tag", haTag);
         }
@@ -1121,7 +1147,7 @@ public class ManagementServerImpl implements ManagementServer {
             sc.addAnd("allocationState", SearchCriteria.Op.EQ, allocationState);
         }
 
-        Pair<List<HostPodVO>, Integer> result =  _hostPodDao.searchAndCount(sc, searchFilter);
+        Pair<List<HostPodVO>, Integer> result = _hostPodDao.searchAndCount(sc, searchFilter);
         return new Pair<List<? extends Pod>, Integer>(result.first(), result.second());
     }
 
@@ -1143,8 +1169,10 @@ public class ManagementServerImpl implements ManagementServer {
             }
             Account account = _accountDao.findActiveAccount(accountName, domainId);
             if (account == null) {
-            	InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find account " + accountName + " in specified domain");            	
-                // Since we don't have a DomainVO object here, we directly set tablename to "domain".
+                InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find account " + accountName
+                        + " in specified domain");
+                // Since we don't have a DomainVO object here, we directly set
+                // tablename to "domain".
                 String tablename = "domain";
                 ex.addProxyObject(tablename, domainId, "domainId");
                 throw ex;
@@ -1165,8 +1193,8 @@ public class ManagementServerImpl implements ManagementServer {
         if (projectId != null) {
             Project project = _projectMgr.getProject(projectId);
             if (project == null) {
-            	InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project by id " + projectId);
-            	ex.addProxyObject(project, projectId, "projectId");
+                InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project by id " + projectId);
+                ex.addProxyObject(project, projectId, "projectId");
                 throw ex;
             }
             accountId = project.getProjectAccountId();
@@ -1192,7 +1220,8 @@ public class ManagementServerImpl implements ManagementServer {
         if (accountId != null) {
             SearchBuilder<AccountVlanMapVO> accountVlanMapSearch = _accountVlanMapDao.createSearchBuilder();
             accountVlanMapSearch.and("accountId", accountVlanMapSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
-            sb.join("accountVlanMapSearch", accountVlanMapSearch, sb.entity().getId(), accountVlanMapSearch.entity().getVlanDbId(), JoinBuilder.JoinType.INNER);
+            sb.join("accountVlanMapSearch", accountVlanMapSearch, sb.entity().getId(), accountVlanMapSearch.entity().getVlanDbId(),
+                    JoinBuilder.JoinType.INNER);
         }
 
         if (podId != null) {
@@ -1294,8 +1323,10 @@ public class ManagementServerImpl implements ManagementServer {
             listAll = true;
         }
         List<Long> permittedAccountIds = new ArrayList<Long>();
-        Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(cmd.getDomainId(), cmd.isRecursive(), null);
-        _accountMgr.buildACLSearchParameters(caller, cmd.getId(), cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds, domainIdRecursiveListProject, listAll, false);
+        Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
+                cmd.getDomainId(), cmd.isRecursive(), null);
+        _accountMgr.buildACLSearchParameters(caller, cmd.getId(), cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds,
+                domainIdRecursiveListProject, listAll, false);
         ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
 
         List<Account> permittedAccounts = new ArrayList<Account>();
@@ -1304,8 +1335,9 @@ public class ManagementServerImpl implements ManagementServer {
         }
 
         HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor());
-        return listTemplates(cmd.getId(), cmd.getIsoName(), cmd.getKeyword(), isoFilter, true, cmd.isBootable(), cmd.getPageSizeVal(), cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, true,
-                cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags);
+        return listTemplates(cmd.getId(), cmd.getIsoName(), cmd.getKeyword(), isoFilter, true, cmd.isBootable(), cmd.getPageSizeVal(),
+                cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, true, cmd.listInReadyState(), permittedAccounts, caller,
+                listProjectResourcesCriteria, tags);
     }
 
     @Override
@@ -1314,7 +1346,7 @@ public class ManagementServerImpl implements ManagementServer {
         Long id = cmd.getId();
         Map<String, String> tags = cmd.getTags();
         Account caller = UserContext.current().getCaller();
-        
+
         boolean listAll = false;
         if (templateFilter != null && templateFilter == TemplateFilter.all) {
             if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
@@ -1322,10 +1354,12 @@ public class ManagementServerImpl implements ManagementServer {
             }
             listAll = true;
         }
-        
+
         List<Long> permittedAccountIds = new ArrayList<Long>();
-        Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(cmd.getDomainId(), cmd.isRecursive(), null);
-        _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds, domainIdRecursiveListProject, listAll, false);
+        Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
+                cmd.getDomainId(), cmd.isRecursive(), null);
+        _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds, domainIdRecursiveListProject,
+                listAll, false);
         ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
         List<Account> permittedAccounts = new ArrayList<Account>();
         for (Long accountId : permittedAccountIds) {
@@ -1335,15 +1369,13 @@ public class ManagementServerImpl implements ManagementServer {
         boolean showDomr = ((templateFilter != TemplateFilter.selfexecutable) && (templateFilter != TemplateFilter.featured));
         HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor());
 
-        return listTemplates(id, cmd.getTemplateName(), cmd.getKeyword(), templateFilter, false, null, 
-                cmd.getPageSizeVal(), cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, showDomr,
-                cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags);
+        return listTemplates(id, cmd.getTemplateName(), cmd.getKeyword(), templateFilter, false, null, cmd.getPageSizeVal(), cmd.getStartIndex(),
+                cmd.getZoneId(), hypervisorType, showDomr, cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags);
     }
 
-    private Set<Pair<Long, Long>> listTemplates(Long templateId, String name, String keyword, TemplateFilter templateFilter,
-            boolean isIso, Boolean bootable, Long pageSize, Long startIndex, Long zoneId, HypervisorType hyperType,
-            boolean showDomr, boolean onlyReady, List<Account> permittedAccounts, Account caller,
-            ListProjectResourcesCriteria listProjectResourcesCriteria, Map<String, String> tags) {
+    private Set<Pair<Long, Long>> listTemplates(Long templateId, String name, String keyword, TemplateFilter templateFilter, boolean isIso,
+            Boolean bootable, Long pageSize, Long startIndex, Long zoneId, HypervisorType hyperType, boolean showDomr, boolean onlyReady,
+            List<Account> permittedAccounts, Account caller, ListProjectResourcesCriteria listProjectResourcesCriteria, Map<String, String> tags) {
 
         VMTemplateVO template = null;
         if (templateId != null) {
@@ -1359,7 +1391,8 @@ public class ManagementServerImpl implements ManagementServer {
             }// If ISO not requested then it shouldn't be an ISO.
             if (!isIso && template.getFormat() == ImageFormat.ISO) {
                 s_logger.error("Incorrect format of the template id " + templateId);
-                InvalidParameterValueException ex = new InvalidParameterValueException("Incorrect format " + template.getFormat() + " of the specified template id");
+                InvalidParameterValueException ex = new InvalidParameterValueException("Incorrect format " + template.getFormat()
+                        + " of the specified template id");
                 ex.addProxyObject(template, templateId, "templateId");
                 throw ex;
             }
@@ -1379,14 +1412,12 @@ public class ManagementServerImpl implements ManagementServer {
         Set<Pair<Long, Long>> templateZonePairSet = new HashSet<Pair<Long, Long>>();
         if (_swiftMgr.isSwiftEnabled()) {
             if (template == null) {
-                templateZonePairSet = _templateDao.searchSwiftTemplates(name, keyword, templateFilter, isIso, 
-                        hypers, bootable, domain, pageSize, startIndex, zoneId, hyperType, onlyReady, showDomr,
-                        permittedAccounts, caller, tags);
+                templateZonePairSet = _templateDao.searchSwiftTemplates(name, keyword, templateFilter, isIso, hypers, bootable, domain, pageSize,
+                        startIndex, zoneId, hyperType, onlyReady, showDomr, permittedAccounts, caller, tags);
                 Set<Pair<Long, Long>> templateZonePairSet2 = new HashSet<Pair<Long, Long>>();
-                templateZonePairSet2 = _templateDao.searchTemplates(name, keyword, templateFilter, isIso, hypers, 
-                        bootable, domain, pageSize, startIndex, zoneId, hyperType, onlyReady, showDomr,
-                        permittedAccounts, caller, listProjectResourcesCriteria, tags);
-                
+                templateZonePairSet2 = _templateDao.searchTemplates(name, keyword, templateFilter, isIso, hypers, bootable, domain, pageSize,
+                        startIndex, zoneId, hyperType, onlyReady, showDomr, permittedAccounts, caller, listProjectResourcesCriteria, tags);
+
                 for (Pair<Long, Long> tmpltPair : templateZonePairSet2) {
                     if (!templateZonePairSet.contains(new Pair<Long, Long>(tmpltPair.first(), -1L))) {
                         templateZonePairSet.add(tmpltPair);
@@ -1403,9 +1434,8 @@ public class ManagementServerImpl implements ManagementServer {
             }
         } else {
             if (template == null) {
-                templateZonePairSet = _templateDao.searchTemplates(name, keyword, templateFilter, isIso, hypers, 
-                        bootable, domain, pageSize, startIndex, zoneId, hyperType, onlyReady, showDomr,
-                        permittedAccounts, caller, listProjectResourcesCriteria, tags);
+                templateZonePairSet = _templateDao.searchTemplates(name, keyword, templateFilter, isIso, hypers, bootable, domain, pageSize,
+                        startIndex, zoneId, hyperType, onlyReady, showDomr, permittedAccounts, caller, listProjectResourcesCriteria, tags);
             } else {
                 // if template is not public, perform permission check here
                 if (!template.isPublicTemplate() && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
@@ -1443,22 +1473,23 @@ public class ManagementServerImpl implements ManagementServer {
         // verify that template exists
         VMTemplateVO template = _templateDao.findById(id);
         if (template == null || template.getRemoved() != null) {
-        	InvalidParameterValueException ex = new InvalidParameterValueException("unable to find template/iso with specified id");
-        	ex.addProxyObject(template, id, "templateId");
+            InvalidParameterValueException ex = new InvalidParameterValueException("unable to find template/iso with specified id");
+            ex.addProxyObject(template, id, "templateId");
             throw ex;
         }
 
         // Don't allow to modify system template
         if (id == Long.valueOf(1)) {
-        	InvalidParameterValueException ex = new InvalidParameterValueException("Unable to update template/iso of specified id");
-        	ex.addProxyObject(template, id, "templateId");
+            InvalidParameterValueException ex = new InvalidParameterValueException("Unable to update template/iso of specified id");
+            ex.addProxyObject(template, id, "templateId");
             throw ex;
         }
 
         // do a permission check
         _accountMgr.checkAccess(account, AccessType.ModifyEntry, true, template);
 
-        boolean updateNeeded = !(name == null && displayText == null && format == null && guestOSId == null && passwordEnabled == null && bootable == null && sortKey == null);
+        boolean updateNeeded = !(name == null && displayText == null && format == null && guestOSId == null && passwordEnabled == null
+                && bootable == null && sortKey == null);
         if (!updateNeeded) {
             return template;
         }
@@ -1482,7 +1513,8 @@ public class ManagementServerImpl implements ManagementServer {
             try {
                 imageFormat = ImageFormat.valueOf(format.toUpperCase());
             } catch (IllegalArgumentException e) {
-                throw new InvalidParameterValueException("Image format: " + format + " is incorrect. Supported formats are " + EnumUtils.listValues(ImageFormat.values()));
+                throw new InvalidParameterValueException("Image format: " + format + " is incorrect. Supported formats are "
+                        + EnumUtils.listValues(ImageFormat.values()));
             }
 
             template.setFormat(imageFormat);
@@ -1512,7 +1544,7 @@ public class ManagementServerImpl implements ManagementServer {
     }
 
     @Override
-    public List<EventVO> searchForEvents(ListEventsCmd cmd) {
+    public Pair<List<EventJoinVO>, Integer> searchForEvents(ListEventsCmd cmd) {
         Account caller = UserContext.current().getCaller();
         List<Long> permittedAccounts = new ArrayList<Long>();
 
@@ -1525,34 +1557,17 @@ public class ManagementServerImpl implements ManagementServer {
         Integer entryTime = cmd.getEntryTime();
         Integer duration = cmd.getDuration();
 
-        Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(cmd.getDomainId(), cmd.isRecursive(), null);
-        _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
+        Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
+                cmd.getDomainId(), cmd.isRecursive(), null);
+        _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject,
+                cmd.listAll(), false);
         Long domainId = domainIdRecursiveListProject.first();
         Boolean isRecursive = domainIdRecursiveListProject.second();
         ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
 
-        Filter searchFilter = new Filter(EventVO.class, "createDate", false, cmd.getStartIndex(), cmd.getPageSizeVal());
-        SearchBuilder<EventVO> sb = _eventDao.createSearchBuilder();
-
-        sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN);
-        sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ);
-        if (((permittedAccounts.isEmpty()) && (domainId != null) && isRecursive)) {
-            // if accountId isn't specified, we can do a domain match for the admin case if isRecursive is true
-            SearchBuilder<DomainVO> domainSearch = _domainDao.createSearchBuilder();
-            domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE);
-            sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER);
-        }
-
-        if (listProjectResourcesCriteria != null) {
-            SearchBuilder<AccountVO> accountSearch = _accountDao.createSearchBuilder();
-            if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) {
-                accountSearch.and("accountType", accountSearch.entity().getType(), SearchCriteria.Op.EQ);
-                sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER);
-            } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) {
-                accountSearch.and("accountType", accountSearch.entity().getType(), SearchCriteria.Op.NEQ);
-                sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER);
-            }
-        }
+        Filter searchFilter = new Filter(EventJoinVO.class, "createDate", false, cmd.getStartIndex(), cmd.getPageSizeVal());
+        SearchBuilder<EventJoinVO> sb = _eventJoinDao.createSearchBuilder();
+        _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
 
         sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
         sb.and("levelL", sb.entity().getLevel(), SearchCriteria.Op.LIKE);
@@ -1565,28 +1580,16 @@ public class ManagementServerImpl implements ManagementServer {
         sb.and("startId", sb.entity().getStartId(), SearchCriteria.Op.EQ);
         sb.and("createDate", sb.entity().getCreateDate(), SearchCriteria.Op.BETWEEN);
 
-        SearchCriteria<EventVO> sc = sb.create();
-        if (listProjectResourcesCriteria != null) {
-            sc.setJoinParameters("accountSearch", "accountType", Account.ACCOUNT_TYPE_PROJECT);
-        }
-
-        if (!permittedAccounts.isEmpty()) {
-            sc.setParameters("accountIdIN", permittedAccounts.toArray());
-        } else if (domainId != null) {
-            DomainVO domain = _domainDao.findById(domainId);
-            if (isRecursive) {
-                sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%");
-            } else {
-                sc.setParameters("domainId", domainId);
-            }
-        }
+        SearchCriteria<EventJoinVO> sc = sb.create();
+        // building ACL condition
+        _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
 
         if (id != null) {
             sc.setParameters("id", id);
         }
 
         if (keyword != null) {
-            SearchCriteria<EventVO> ssc = _eventDao.createSearchCriteria();
+            SearchCriteria<EventJoinVO> ssc = _eventJoinDao.createSearchCriteria();
             ssc.addOr("type", SearchCriteria.Op.LIKE, "%" + keyword + "%");
             ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%");
             ssc.addOr("level", SearchCriteria.Op.LIKE, "%" + keyword + "%");
@@ -1609,32 +1612,34 @@ public class ManagementServerImpl implements ManagementServer {
             sc.setParameters("createDateL", endDate);
         }
 
+        Pair<List<EventJoinVO>, Integer> eventPair = null;
+        // event_view will not have duplicate rows for each event, so searchAndCount should be good enough.
         if ((entryTime != null) && (duration != null)) {
-            if (entryTime <= duration) {
-                throw new InvalidParameterValueException("Entry time must be greater than duration");
-            }
-            Calendar calMin = Calendar.getInstance();
-            Calendar calMax = Calendar.getInstance();
-            calMin.add(Calendar.SECOND, -entryTime);
-            calMax.add(Calendar.SECOND, -duration);
-            Date minTime = calMin.getTime();
-            Date maxTime = calMax.getTime();
-
-            sc.setParameters("state", com.cloud.event.Event.State.Completed);
-            sc.setParameters("startId", 0);
-            sc.setParameters("createDate", minTime, maxTime);
-            List<EventVO> startedEvents = _eventDao.searchAllEvents(sc, searchFilter);
-            List<EventVO> pendingEvents = new ArrayList<EventVO>();
-            for (EventVO event : startedEvents) {
-                EventVO completedEvent = _eventDao.findCompletedEvent(event.getId());
-                if (completedEvent == null) {
-                    pendingEvents.add(event);
-                }
-            }
-            return pendingEvents;
+            // TODO: waiting for response from dev list, logic is mystery to
+            // me!!
+            /*
+             * if (entryTime <= duration) { throw new
+             * InvalidParameterValueException
+             * ("Entry time must be greater than duration"); } Calendar calMin =
+             * Calendar.getInstance(); Calendar calMax = Calendar.getInstance();
+             * calMin.add(Calendar.SECOND, -entryTime);
+             * calMax.add(Calendar.SECOND, -duration); Date minTime =
+             * calMin.getTime(); Date maxTime = calMax.getTime();
+             *
+             * sc.setParameters("state", com.cloud.event.Event.State.Completed);
+             * sc.setParameters("startId", 0); sc.setParameters("createDate",
+             * minTime, maxTime); List<EventJoinVO> startedEvents =
+             * _eventJoinDao.searchAllEvents(sc, searchFilter);
+             * List<EventJoinVO> pendingEvents = new ArrayList<EventJoinVO>();
+             * for (EventVO event : startedEvents) { EventVO completedEvent =
+             * _eventDao.findCompletedEvent(event.getId()); if (completedEvent
+             * == null) { pendingEvents.add(event); } } return pendingEvents;
+             */
         } else {
-            return _eventDao.searchAllEvents(sc, searchFilter);
+            eventPair = _eventJoinDao.searchAndCount(sc, searchFilter);
         }
+        return eventPair;
+
     }
 
     @Override
@@ -1653,16 +1658,23 @@ public class ManagementServerImpl implements ManagementServer {
         Account caller = UserContext.current().getCaller();
         List<Long> permittedAccounts = new ArrayList<Long>();
 
-        Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(cmd.getDomainId(), cmd.isRecursive(), null);
-        _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
+        Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
+                cmd.getDomainId(), cmd.isRecursive(), null);
+        _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject,
+                cmd.listAll(), false);
         Long domainId = domainIdRecursiveListProject.first();
         Boolean isRecursive = domainIdRecursiveListProject.second();
         ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
         // no default orderBy
-        //Filter searchFilter = new Filter(DomainRouterJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
+        // Filter searchFilter = new Filter(DomainRouterJoinVO.class, "id",
+        // true, cmd.getStartIndex(), cmd.getPageSizeVal());
         Filter searchFilter = new Filter(DomainRouterJoinVO.class, null, true, cmd.getStartIndex(), cmd.getPageSizeVal());
         SearchBuilder<DomainRouterJoinVO> sb = _routerJoinDao.createSearchBuilder();
-        sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct ids to get number of records with pagination
+        sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
+                                                             // ids to get
+                                                             // number of
+                                                             // records with
+                                                             // pagination
         _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
 
         sb.and("name", sb.entity().getHostName(), SearchCriteria.Op.LIKE);
@@ -1673,12 +1685,12 @@ public class ManagementServerImpl implements ManagementServer {
         sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ);
         sb.and("hostId", sb.entity().getHostId(), SearchCriteria.Op.EQ);
         sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ);
-        
+
         if (forVpc != null) {
             if (forVpc) {
-                sb.and("forVpc", sb.entity().getVpcId(), SearchCriteria.Op.NNULL); 
+                sb.and("forVpc", sb.entity().getVpcId(), SearchCriteria.Op.NNULL);
             } else {
-                sb.and("forVpc", sb.entity().getVpcId(), SearchCriteria.Op.NULL); 
+                sb.and("forVpc", sb.entity().getVpcId(), SearchCriteria.Op.NULL);
             }
         }
 
@@ -1701,49 +1713,49 @@ public class ManagementServerImpl implements ManagementServer {
         if (name != null) {
             sc.setParameters("name", "%" + name + "%");
         }
-        
+
         if (id != null) {
             sc.setParameters("id", id);
         }
-        
+
         if (state != null) {
             sc.setParameters("state", state);
         }
-        
+
         if (zone != null) {
             sc.setParameters("dataCenterId", zone);
         }
-        
+
         if (pod != null) {
             sc.setParameters("podId", pod);
         }
-        
+
         if (hostId != null) {
             sc.setParameters("hostId", hostId);
         }
-        
+
         if (networkId != null) {
             sc.setJoinParameters("nicSearch", "networkId", networkId);
         }
-        
+
         if (vpcId != null) {
             sc.setParameters("vpcId", vpcId);
         }
 
         // search VR details by ids
-        Pair<List<DomainRouterJoinVO>, Integer> uniqueVrPair =  _routerJoinDao.searchAndCount(sc, searchFilter);
+        Pair<List<DomainRouterJoinVO>, Integer> uniqueVrPair = _routerJoinDao.searchAndCount(sc, searchFilter);
         Integer count = uniqueVrPair.second();
-        if ( count.intValue() == 0 ) {
+        if (count.intValue() == 0) {
             // empty result
             return uniqueVrPair;
         }
         List<DomainRouterJoinVO> uniqueVrs = uniqueVrPair.first();
         Long[] vrIds = new Long[uniqueVrs.size()];
         int i = 0;
-        for (DomainRouterJoinVO v : uniqueVrs ){
+        for (DomainRouterJoinVO v : uniqueVrs) {
             vrIds[i++] = v.getId();
         }
-        List<DomainRouterJoinVO> vrs =  _routerJoinDao.searchByIds(vrIds);
+        List<DomainRouterJoinVO> vrs = _routerJoinDao.searchByIds(vrIds);
         return new Pair<List<DomainRouterJoinVO>, Integer>(vrs, count);
     }
 
@@ -1763,7 +1775,6 @@ public class ManagementServerImpl implements ManagementServer {
         Long vpcId = cmd.getVpcId();
         Map<String, String> tags = cmd.getTags();
 
-
         Boolean isAllocated = cmd.isAllocatedOnly();
         if (isAllocated == null) {
             isAllocated = Boolean.TRUE;
@@ -1778,15 +1789,15 @@ public class ManagementServerImpl implements ManagementServer {
         if (isAllocated) {
             Account caller = UserContext.current().getCaller();
 
-            Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = 
-                    new Ternary<Long, Boolean, ListProjectResourcesCriteria>(cmd.getDomainId(), cmd.isRecursive(), null);
-            _accountMgr.buildACLSearchParameters(caller, cmd.getId(), cmd.getAccountName(), cmd.getProjectId(), 
-                    permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
+            Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
+                    cmd.getDomainId(), cmd.isRecursive(), null);
+            _accountMgr.buildACLSearchParameters(caller, cmd.getId(), cmd.getAccountName(), cmd.getProjectId(), permittedAccounts,
+                    domainIdRecursiveListProject, cmd.listAll(), false);
             domainId = domainIdRecursiveListProject.first();
             isRecursive = domainIdRecursiveListProject.second();
             listProjectResourcesCriteria = domainIdRecursiveListProject.third();
-        _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
-        }      
+            _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
+        }
 
         sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ);
         sb.and("address", sb.entity().getAddress(), SearchCriteria.Op.EQ);
@@ -1810,7 +1821,7 @@ public class ManagementServerImpl implements ManagementServer {
 
         if (tags != null && !tags.isEmpty()) {
             SearchBuilder<ResourceTagVO> tagSearch = _resourceTagDao.createSearchBuilder();
-            for (int count=0; count < tags.size(); count++) {
+            for (int count = 0; count < tags.size(); count++) {
                 tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ);
                 tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ);
                 tagSearch.cp();
@@ -1820,7 +1831,6 @@ public class ManagementServerImpl implements ManagementServer {
             sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER);
         }
 
-
         SearchBuilder<VlanVO> vlanSearch = _vlanDao.createSearchBuilder();
         vlanSearch.and("vlanType", vlanSearch.entity().getVlanType(), SearchCriteria.Op.EQ);
         sb.join("vlanSearch", vlanSearch, sb.entity().getVlanId(), vlanSearch.entity().getId(), JoinBuilder.JoinType.INNER);
@@ -1840,7 +1850,7 @@ public class ManagementServerImpl implements ManagementServer {
 
         SearchCriteria<IPAddressVO> sc = sb.create();
         if (isAllocated) {
-        _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
+            _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
         }
 
         sc.setJoinParameters("vlanSearch", "vlanType", vlanType);
@@ -1862,7 +1872,7 @@ public class ManagementServerImpl implements ManagementServer {
         if (vpcId != null) {
             sc.setParameters("vpcId", vpcId);
         }
-        
+
         if (ipId != null) {
             sc.setParameters("id", ipId);
         }
@@ -1916,11 +1926,11 @@ public class ManagementServerImpl implements ManagementServer {
         if (osCategoryId != null) {
             sc.addAnd("categoryId", SearchCriteria.Op.EQ, osCategoryId);
         }
-        
+
         if (description != null) {
             sc.addAnd("displayName", SearchCriteria.Op.LIKE, "%" + description + "%");
         }
-        
+
         if (keyword != null) {
             sc.addAnd("displayName", SearchCriteria.Op.LIKE, "%" + keyword + "%");
         }
@@ -1941,11 +1951,11 @@ public class ManagementServerImpl implements ManagementServer {
         if (id != null) {
             sc.addAnd("id", SearchCriteria.Op.EQ, id);
         }
-        
+
         if (name != null) {
             sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%");
         }
-        
+
         if (keyword != null) {
             sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
         }
@@ -1965,7 +1975,8 @@ public class ManagementServerImpl implements ManagementServer {
     }
 
     @ActionEvent(eventType = EventTypes.EVENT_PROXY_STOP, eventDescription = "stopping console proxy Vm", async = true)
-    private ConsoleProxyVO stopConsoleProxy(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException {
+    private ConsoleProxyVO stopConsoleProxy(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException, OperationTimedoutException,
+            ConcurrentOperationException {
 
         User caller = _userDao.findById(UserContext.current().getCallerUserId());
 
@@ -2033,11 +2044,12 @@ public class ManagementServerImpl implements ManagementServer {
         // check if domain exists in the system
         DomainVO domain = _domainDao.findById(domainId);
         if (domain == null) {
-        	InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find domain with specified domain id");
-        	ex.addProxyObject(domain, domainId, "domainId");            
+            InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find domain with specified domain id");
+            ex.addProxyObject(domain, domainId, "domainId");
             throw ex;
         } else if (domain.getParent() == null && domainName != null) {
-            // check if domain is ROOT domain - and deny to edit it with the new name
+            // check if domain is ROOT domain - and deny to edit it with the new
+            // name
             throw new InvalidParameterValueException("ROOT domain can not be edited with a new name");
         }
 
@@ -2054,9 +2066,10 @@ public class ManagementServerImpl implements ManagementServer {
             boolean sameDomain = (domains.size() == 1 && domains.get(0).getId() == domainId);
 
             if (!domains.isEmpty() && !sameDomain) {
-                InvalidParameterValueException ex = new InvalidParameterValueException("Failed to update specified domain id with name '" + domainName + "' since it already exists in the system");
-                ex.addProxyObject(domain, domainId, "domainId");                
-            	throw ex;
+                InvalidParameterValueException ex = new InvalidParameterValueException("Failed to update specified domain id with name '"
+                        + domainName + "' since it already exists in the system");
+                ex.addProxyObject(domain, domainId, "domainId");
+                throw ex;
             }
         }
 
@@ -2143,7 +2156,7 @@ public class ManagementServerImpl implements ManagementServer {
             sc.addAnd("type", SearchCriteria.Op.EQ, type);
         }
 
-        Pair<List<AlertVO>, Integer> result =_alertDao.searchAndCount(sc, searchFilter);
+        Pair<List<AlertVO>, Integer> result = _alertDao.searchAndCount(sc, searchFilter);
         return new Pair<List<? extends Alert>, Integer>(result.first(), result.second());
     }
 
@@ -2162,13 +2175,15 @@ public class ManagementServerImpl implements ManagementServer {
         List<SummedCapacity> summedCapacities = new ArrayList<SummedCapacity>();
 
         if (zoneId == null && podId == null) {// Group by Zone, capacity type
-            List<SummedCapacity> summedCapacitiesAtZone = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 1, cmd.getPageSizeVal());
+            List<SummedCapacity> summedCapacitiesAtZone = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 1,
+                    cmd.getPageSizeVal());
             if (summedCapacitiesAtZone != null) {
                 summedCapacities.addAll(summedCapacitiesAtZone);
             }
         }
         if (podId == null) {// Group by Pod, capacity type
-            List<SummedCapacity> summedCapacitiesAtPod = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 2, cmd.getPageSizeVal());
+            List<SummedCapacity> summedCapacitiesAtPod = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 2,
+                    cmd.getPageSizeVal());
             if (summedCapacitiesAtPod != null) {
                 summedCapacities.addAll(summedCapacitiesAtPod);
             }
@@ -2179,7 +2194,8 @@ public class ManagementServerImpl implements ManagementServer {
         }
 
         // Group by Cluster, capacity type
-        List<SummedCapacity> summedCapacitiesAtCluster = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 3, cmd.getPageSizeVal());
+        List<SummedCapacity> summedCapacitiesAtCluster = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 3,
+                cmd.getPageSizeVal());
         if (summedCapacitiesAtCluster != null) {
             summedCapacities.addAll(summedCapacitiesAtCluster);
         }
@@ -2231,20 +2247,22 @@ public class ManagementServerImpl implements ManagementServer {
                 } else {
                     capacity.setUsedPercentage(0);
                 }
-                SummedCapacity summedCapacity = new SummedCapacity(capacity.getUsedCapacity(), capacity.getTotalCapacity(), capacity.getUsedPercentage(), capacity.getCapacityType(), capacity.getDataCenterId(),
-                        capacity.getPodId(), capacity.getClusterId());
+                SummedCapacity summedCapacity = new SummedCapacity(capacity.getUsedCapacity(), capacity.getTotalCapacity(),
+                        capacity.getUsedPercentage(), capacity.getCapacityType(), capacity.getDataCenterId(), capacity.getPodId(),
+                        capacity.getClusterId());
                 list.add(summedCapacity);
             } else {
                 List<DataCenterVO> dcList = _dcDao.listEnabledZones();
                 for (DataCenterVO dc : dcList) {
                     CapacityVO capacity = _storageMgr.getSecondaryStorageUsedStats(null, dc.getId());
                     if (capacity.getTotalCapacity() != 0) {
-                        capacity.setUsedPercentage((float)capacity.getUsedCapacity() / capacity.getTotalCapacity());
+                        capacity.setUsedPercentage((float) capacity.getUsedCapacity() / capacity.getTotalCapacity());
                     } else {
                         capacity.setUsedPercentage(0);
                     }
-                    SummedCapacity summedCapacity = new SummedCapacity(capacity.getUsedCapacity(), capacity.getTotalCapacity(), capacity.getUsedPercentage(), capacity.getCapacityType(), capacity.getDataCenterId(),
-                            capacity.getPodId(), capacity.getClusterId());
+                    SummedCapacity summedCapacity = new SummedCapacity(capacity.getUsedCapacity(), capacity.getTotalCapacity(),
+                            capacity.getUsedPercentage(), capacity.getCapacityType(), capacity.getDataCenterId(), capacity.getPodId(),
+                            capacity.getClusterId());
                     list.add(summedCapacity);
                 }// End of for
             }
@@ -2271,9 +2289,8 @@ public class ManagementServerImpl implements ManagementServer {
         List<CapacityVO> capacities = new ArrayList<CapacityVO>();
 
         for (SummedCapacity summedCapacity : summedCapacities) {
-            CapacityVO capacity = new CapacityVO(null, summedCapacity.getDataCenterId(), podId, clusterId,
-                    summedCapacity.getUsedCapacity() + summedCapacity.getReservedCapacity(),
-                    summedCapacity.getTotalCapacity(), summedCapacity.getCapacityType());
+            CapacityVO capacity = new CapacityVO(null, summedCapacity.getDataCenterId(), podId, clusterId, summedCapacity.getUsedCapacity()
+                    + summedCapacity.getReservedCapacity(), summedCapacity.getTotalCapacity(), summedCapacity.getCapacityType());
 
             if (summedCapacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU) {
                 capacity.setTotalCapacity((long) (summedCapacity.getTotalCapacity() * ApiDBUtils.getCpuOverprovisioningFactor()));
@@ -2281,7 +2298,8 @@ public class ManagementServerImpl implements ManagementServer {
             capacities.add(capacity);
         }
 
-        // op_host_Capacity contains only allocated stats and the real time stats are stored "in memory".
+        // op_host_Capacity contains only allocated stats and the real time
+        // stats are stored "in memory".
         // Show Sec. Storage only when the api is invoked for the zone layer.
         List<DataCenterVO> dcList = new ArrayList<DataCenterVO>();
         if (zoneId == null && podId == null && clusterId == null) {
@@ -2289,11 +2307,11 @@ public class ManagementServerImpl implements ManagementServer {
         } else if (zoneId != null) {
             dcList.add(ApiDBUtils.findZoneById(zoneId));
         } else {
-        	if (clusterId != null){
-        		zoneId = ApiDBUtils.findClusterById(clusterId).getDataCenterId();
-        	}else{
-        		zoneId = ApiDBUtils.findPodById(podId).getDataCenterId();
-        	}
+            if (clusterId != null) {
+                zoneId = ApiDBUtils.findClusterById(clusterId).getDataCenterId();
+            } else {
+                zoneId = ApiDBUtils.findPodById(podId).getDataCenterId();
+            }
             if (capacityType == null || capacityType == Capacity.CAPACITY_TYPE_STORAGE) {
                 capacities.add(_storageMgr.getStoragePoolUsedStats(null, clusterId, podId, zoneId));
             }
@@ -2320,12 +2338,14 @@ public class ManagementServerImpl implements ManagementServer {
     }
 
     public static boolean isAdmin(short accountType) {
-        return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN));
+        return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN)
+                || (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN));
     }
 
     private List<DiskOfferingVO> searchDiskOfferingsInternal(Account account, Object name, Object id, Object keyword, Filter searchFilter) {
-        // it was decided to return all offerings for the user's domain, and everything above till root (for normal user
-// or
+        // it was decided to return all offerings for the user's domain, and
+        // everything above till root (for normal user
+        // or
         // domain admin)
         // list all offerings belonging to this domain, and all of its parents
         // check the parent, if not null, add offerings for that parent to list
@@ -2390,11 +2410,13 @@ public class ManagementServerImpl implements ManagementServer {
     @Override
     public List<DiskOfferingVO> searchForDiskOfferings(ListDiskOfferingsCmd cmd) {
         // Note
-        // The list method for offerings is being modified in accordance with discussion with Will/Kevin
+        // The list method for offerings is being modified in accordance with
+        // discussion with Will/Kevin
         // For now, we will be listing the following based on the usertype
         // 1. For root, we will list all offerings
-        // 2. For domainAdmin and regular users, we will list everything in their domains+parent domains ... all the way
-// till
+        // 2. For domainAdmin and regular users, we will list everything in
+        // their domains+parent domains ... all the way
+        // till
         // root
 
         Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm"));
@@ -2402,31 +2424,38 @@ public class ManagementServerImpl implements ManagementServer {
         Filter searchFilter = new Filter(DiskOfferingVO.class, "sortKey", isAscending, cmd.getStartIndex(), cmd.getPageSizeVal());
         SearchBuilder<DiskOfferingVO> sb = _diskOfferingDao.createSearchBuilder();
 
-        // SearchBuilder and SearchCriteria are now flexible so that the search builder can be built with all possible
-        // search terms and only those with criteria can be set. The proper SQL should be generated as a result.
+        // SearchBuilder and SearchCriteria are now flexible so that the search
+        // builder can be built with all possible
+        // search terms and only those with criteria can be set. The proper SQL
+        // should be generated as a result.
         Account account = UserContext.current().getCaller();
         Object name = cmd.getDiskOfferingName();
         Object id = cmd.getId();
         Object keyword = cmd.getKeyword();
         Long domainId = cmd.getDomainId();
         // Keeping this logic consistent with domain specific zones
-        // if a domainId is provided, we just return the disk offering associated with this domain
+        // if a domainId is provided, we just return the disk offering
+        // associated with this domain
         if (domainId != null) {
             if (account.getType() == Account.ACCOUNT_TYPE_ADMIN) {
-                return _diskOfferingDao.listByDomainId(domainId);// no perm check
+                return _diskOfferingDao.listByDomainId(domainId);// no perm
+                                                                 // check
             } else {
-                // check if the user's domain == do's domain || user's domain is a child of so's domain
+                // check if the user's domain == do's domain || user's domain is
+                // a child of so's domain
                 if (isPermissible(account.getDomainId(), domainId)) {
                     // perm check succeeded
                     return _diskOfferingDao.listByDomainId(domainId);
                 } else {
-                    throw new PermissionDeniedException("The account:" + account.getAccountName() + " does not fall in the same domain hierarchy as the disk offering");
+                    throw new PermissionDeniedException("The account:" + account.getAccountName()
+                            + " does not fall in the same domain hierarchy as the disk offering");
                 }
             }
         }
 
         // For non-root users
-        if ((account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
+        if ((account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)
+                || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
             return searchDiskOfferingsInternal(account, name, id, keyword, searchFilter);
         }
 
@@ -2435,12 +2464,16 @@ public class ManagementServerImpl implements ManagementServer {
         sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
         sb.and("removed", sb.entity().getRemoved(), SearchCriteria.Op.NULL);
 
-        // FIXME: disk offerings should search back up the hierarchy for available disk offerings...
+        // FIXME: disk offerings should search back up the hierarchy for
+        // available disk offerings...
         /*
-         * sb.addAnd("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); if (domainId != null) {
-         * SearchBuilder<DomainVO> domainSearch = _domainDao.createSearchBuilder(); domainSearch.addAnd("path",
-         * domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); sb.join("domainSearch", domainSearch,
-         * sb.entity().getDomainId(), domainSearch.entity().getId()); }
+         * sb.addAnd("domainId", sb.entity().getDomainId(),
+         * SearchCriteria.Op.EQ); if (domainId != null) {
+         * SearchBuilder<DomainVO> domainSearch =
+         * _domainDao.createSearchBuilder(); domainSearch.addAnd("path",
+         * domainSearch.entity().getPath(), SearchCriteria.Op.LIKE);
+         * sb.join("domainSearch", domainSearch, sb.entity().getDomainId(),
+         * domainSearch.entity().getId()); }
          */
 
         SearchCriteria<DiskOfferingVO> sc = sb.create();
@@ -2460,12 +2493,14 @@ public class ManagementServerImpl implements ManagementServer {
             sc.setParameters("id", id);
         }
 
-        // FIXME: disk offerings should search back up the hierarchy for available disk offerings...
+        // FIXME: disk offerings should search back up the hierarchy for
+        // available disk offerings...
         /*
-         * if (domainId != null) { sc.setParameters("domainId", domainId); // //DomainVO domain =
-         * _domainDao.findById((Long)domainId); // // I want to join on user_vm.domain_id = domain.id where domain.path
-         * like
-         * 'foo%' //sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); // }
+         * if (domainId != null) { sc.setParameters("domainId", domainId); //
+         * //DomainVO domain = _domainDao.findById((Long)domainId); // // I want
+         * to join on user_vm.domain_id = domain.id where domain.path like
+         * 'foo%' //sc.setJoinParameters("domainSearch", "path",
+         * domain.getPath() + "%"); // }
          */
 
         return _diskOfferingDao.search(sc, searchFilter);
@@ -2587,8 +2622,10 @@ public class ManagementServerImpl implements ManagementServer {
 
         List<Long> permittedAccounts = new ArrayList<Long>();
 
-        Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(cmd.getDomainId(), cmd.isRecursive(), null);
-        _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), null, permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
+        Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
+                cmd.getDomainId(), cmd.isRecursive(), null);
+        _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), null, permittedAccounts, domainIdRecursiveListProject,
+                cmd.listAll(), false);
         Long domainId = domainIdRecursiveListProject.first();
         Boolean isRecursive = domainIdRecursiveListProject.second();
         ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
@@ -2600,13 +2637,15 @@ public class ManagementServerImpl implements ManagementServer {
         boolean accountJoinIsDone = false;
         if (permittedAccounts.isEmpty() && domainId != null) {
             accountSearch = _accountDao.createSearchBuilder();
-            // if accountId isn't specified, we can do a domain match for the admin case if isRecursive is true
+            // if accountId isn't specified, we can do a domain match for the
+            // admin case if isRecursive is true
             SearchBuilder<DomainVO> domainSearch = _domainDao.createSearchBuilder();
             domainSearch.and("domainId", domainSearch.entity().getId(), SearchCriteria.Op.EQ);
             domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE);
             sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER);
             accountJoinIsDone = true;
-            accountSearch.join("domainSearch", domainSearch, accountSearch.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER);
+            accountSearch.join("domainSearch", domainSearch, accountSearch.entity().getDomainId(), domainSearch.entity().getId(),
+                    JoinBuilder.JoinType.INNER);
         }
 
         if (listProjectResourcesCriteria != null) {
@@ -2652,7 +2691,7 @@ public class ManagementServerImpl implements ManagementServer {
         }
 
         Pair<List<AsyncJobVO>, Integer> result = _jobDao.searchAndCount(sc, searchFilter);
-        return new Pair<List<? extends AsyncJob>, Integer> (result.first(), result.second());
+        return new Pair<List<? extends AsyncJob>, Integer>(result.first(), result.second());
     }
 
     @ActionEvent(eventType = EventTypes.EVENT_SSVM_START, eventDescription = "starting secondary storage Vm", async = true)
@@ -2661,7 +2700,8 @@ public class ManagementServerImpl implements ManagementServer {
     }
 
     @ActionEvent(eventType = EventTypes.EVENT_SSVM_STOP, eventDescription = "stopping secondary storage Vm", async = true)
-    private SecondaryStorageVmVO stopSecondaryStorageVm(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException {
+    private SecondaryStorageVmVO stopSecondaryStorageVm(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException,
+            OperationTimedoutException, ConcurrentOperationException {
 
         User caller = _userDao.findById(UserContext.current().getCallerUserId());
 
@@ -2709,7 +2749,7 @@ public class ManagementServerImpl implements ManagementServer {
         sb.and("hostId", sb.entity().getHostId(), SearchCriteria.Op.EQ);
         sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ);
         sb.and("nulltype", sb.entity().getType(), SearchCriteria.Op.IN);
-        
+
         if (storageId != null) {
             SearchBuilder<VolumeVO> volumeSearch = _volumeDao.createSearchBuilder();
             volumeSearch.and("poolId", volumeSearch.entity().getPoolId(), SearchCriteria.Op.EQ);
@@ -2722,9 +2762,9 @@ public class ManagementServerImpl implements ManagementServer {
             SearchCriteria<VMInstanceVO> ssc = _vmInstanceDao.createSearchCriteria();
             ssc.addOr("hostName", SearchCriteria.Op.LIKE, "%" + keyword + "%");
             ssc.addOr("state", SearchCriteria.Op.LIKE, "%" + keyword + "%");
-            
+
             sc.addAnd("hostName", SearchCriteria.Op.SC, ssc);
-        } 
+        }
 
         if (id != null) {
             sc.setParameters("id", id);
@@ -2751,7 +2791,7 @@ public class ManagementServerImpl implements ManagementServer {
         } else {
             sc.setParameters("nulltype", VirtualMachine.Type.SecondaryStorageVm, VirtualMachine.Type.ConsoleProxy);
         }
-        
+
         if (storageId != null) {
             sc.setJoinParameters("volumeSearch", "poolId", storageId);
         }
@@ -2764,8 +2804,8 @@ public class ManagementServerImpl implements ManagementServer {
     public VirtualMachine.Type findSystemVMTypeById(long instanceId) {
         VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(instanceId, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm);
         if (systemVm == null) {
-        	InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a system vm of specified instanceId");
-        	ex.addProxyObject(systemVm, instanceId, "instanceId");
+            InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a system vm of specified instanceId");
+            ex.addProxyObject(systemVm, instanceId, "instanceId");
             throw ex;
         }
         return systemVm.getType();
@@ -2776,8 +2816,8 @@ public class ManagementServerImpl implements ManagementServer {
 
         VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(vmId, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm);
         if (systemVm == null) {
-        	InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId");
-        	ex.addProxyObject(systemVm, vmId, "vmId");           
+            InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId");
+            ex.addProxyObject(systemVm, vmId, "vmId");
             throw ex;
         }
 
@@ -2786,8 +2826,8 @@ public class ManagementServerImpl implements ManagementServer {
         } else if (systemVm.getType() == VirtualMachine.Type.SecondaryStorageVm) {
             return startSecondaryStorageVm(vmId);
         } else {
-        	InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a system vm with specified vmId");
-        	ex.addProxyObject(systemVm, vmId, "vmId");            
+            InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a system vm with specified vmId");
+            ex.addProxyObject(systemVm, vmId, "vmId");
             throw ex;
         }
     }
@@ -2799,8 +2839,8 @@ public class ManagementServerImpl implements ManagementServer {
         // verify parameters
         VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(id, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm);
         if (systemVm == null) {
-        	InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId");
-        	ex.addProxyObject(systemVm, id, "vmId");
+            InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId");
+            ex.addProxyObject(systemVm, id, "vmId");
             throw ex;
         }
 
@@ -2821,8 +2861,8 @@ public class ManagementServerImpl implements ManagementServer {
         VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(cmd.getId(), VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm);
 
         if (systemVm == null) {
-        	InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId");
-        	ex.addProxyObject(systemVm, cmd.getId(), "vmId");
+            InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId");
+            ex.addProxyObject(systemVm, cmd.getId(), "vmId");
             throw ex;
         }
 
@@ -2838,8 +2878,8 @@ public class ManagementServerImpl implements ManagementServer {
         VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(cmd.getId(), VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm);
 
         if (systemVm == null) {
-        	InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId");
-        	ex.addProxyObject(systemVm, cmd.getId(), "vmId");
+            InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId");
+            ex.addProxyObject(systemVm, cmd.getId(), "vmId");
             throw ex;
         }
 
@@ -2876,8 +2916,8 @@ public class ManagementServerImpl implements ManagementServer {
         // verify that user exists
         User user = _accountMgr.getUserIncludingRemoved(userId);
         if ((user == null) || (user.getRemoved() != null)) {
-        	InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find active user of specified id");
-        	ex.addProxyObject(user, userId, "userId");
+            InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find active user of specified id");
+            ex.addProxyObject(user, userId, "userId");
             throw ex;
         }
 
@@ -2925,19 +2965,20 @@ public class ManagementServerImpl implements ManagementServer {
                     supportELB = networkType;
             }
         }
-        
+
         long diskOffMaxSize = Long.valueOf(_configDao.getValue(Config.CustomDiskOfferingMaxSize.key()));
 
         String userPublicTemplateEnabled = _configs.get(Config.AllowPublicUserTemplates.key());
 
         capabilities.put("securityGroupsEnabled", securityGroupsEnabled);
-        capabilities.put("userPublicTemplateEnabled", (userPublicTemplateEnabled == null || userPublicTemplateEnabled.equals("false") ? false : true));
+        capabilities
+                .put("userPublicTemplateEnabled", (userPublicTemplateEnabled == null || userPublicTemplateEnabled.equals("false") ? false : true));
         capabilities.put("cloudStackVersion", getVersion());
         capabilities.put("supportELB", supportELB);
         capabilities.put("projectInviteRequired", _projectMgr.projectInviteRequired());
         capabilities.put("allowusercreateprojects", _projectMgr.allowUserToCreateProject());
         capabilities.put("customDiskOffMaxSize", diskOffMaxSize);
-        
+
         return capabilities;
     }
 
@@ -2962,8 +3003,8 @@ public class ManagementServerImpl implements ManagementServer {
 
         VolumeVO volume = _volumeDao.findById(volumeId);
         if (volume == null) {
-        	InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find volume with specified volumeId");
-        	ex.addProxyObject(volume, volumeId, "volumeId");
+            InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find volume with specified volumeId");
+            ex.addProxyObject(volume, volumeId, "volumeId");
             throw ex;
         }
 
@@ -2976,23 +3017,31 @@ public class ManagementServerImpl implements ManagementServer {
         if (volume.getPoolId() == null) {
             throw new InvalidParameterValueException("The volume doesnt belong to a storage pool so cant extract it");
         }
-        // Extract activity only for detached volumes or for volumes whose instance is stopped
+        // Extract activity only for detached volumes or for volumes whose
+        // instance is stopped
         if (volume.getInstanceId() != null && ApiDBUtils.findVMInstanceById(volume.getInstanceId()).getState() != State.Stopped) {
-            s_logger.debug("Invalid state of the volume with ID: " + volumeId + ". It should be either detached or the VM should be in stopped state.");
-            PermissionDeniedException ex = new PermissionDeniedException("Invalid state of the volume with specified ID. It should be either detached or the VM should be in stopped state.");
+            s_logger.debug("Invalid state of the volume with ID: " + volumeId
+                    + ". It should be either detached or the VM should be in stopped state.");
+            PermissionDeniedException ex = new PermissionDeniedException(
+                    "Invalid state of the volume with specified ID. It should be either detached or the VM should be in stopped state.");
             ex.addProxyObject(volume, volumeId, "volumeId");
             throw ex;
         }
 
-        if (volume.getVolumeType() != Volume.Type.DATADISK) { // Datadisk dont have any template dependence.
+        if (volume.getVolumeType() != Volume.Type.DATADISK) { // Datadisk dont
+                                                              // have any
+                                                              // template
+                                                              // dependence.
 
             VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId());
-            if (template != null) { // For ISO based volumes template = null and we allow extraction of all ISO based volumes
+            if (template != null) { // For ISO based volumes template = null and
+                                    // we allow extraction of all ISO based
+                                    // volumes
                 boolean isExtractable = template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM;
                 if (!isExtractable && account != null && account.getType() != Account.ACCOUNT_TYPE_ADMIN) { // Global
-// admins are always allowed to extract
-                	PermissionDeniedException ex = new PermissionDeniedException("The volume with specified volumeId is not allowed to be extracted");
-                	ex.addProxyObject(volume, volumeId, "volumeId");                    
+                // admins are always allowed to extract
+                    PermissionDeniedException ex = new PermissionDeniedException("The volume with specified volumeId is not allowed to be extracted");
+                    ex.addProxyObject(volume, volumeId, "volumeId");
                     throw ex;
                 }
             }
@@ -3005,7 +3054,8 @@ public class ManagementServerImpl implements ManagementServer {
             extractMode = mode.equals(Upload.Mode.FTP_UPLOAD.toString()) ? Upload.Mode.FTP_UPLOAD : Upload.Mode.HTTP_DOWNLOAD;
         }
 
-        // If mode is upload perform extra checks on url and also see if there is an ongoing upload on the same.
+        // If mode is upload perform extra checks on url and also see if there
+        // is an ongoing upload on the same.
         if (extractMode == Upload.Mode.FTP_UPLOAD) {
             URI uri = new URI(url);
             if ((uri.getScheme() == null) || (!uri.getScheme().equalsIgnoreCase("ftp"))) {
@@ -3026,7 +3076,8 @@ public class ManagementServerImpl implements ManagementServer {
             }
 
             if (_uploadMonitor.isTypeUploadInProgress(volumeId, Upload.Type.VOLUME)) {
-                throw new IllegalArgumentException(volume.getName() + " upload is in progress. Please wait for some time to schedule another upload for the same");
+                throw new IllegalArgumentException(volume.getName()
+                        + " upload is in progress. Please wait for some time to schedule another upload for the same");
             }
         }
 
@@ -3038,14 +3089,17 @@ public class ManagementServerImpl implements ManagementServer {
         List<UploadVO> extractURLList = _uploadDao.listByTypeUploadStatus(volumeId, Upload.Type.VOLUME, UploadVO.Status.DOWNLOAD_URL_CREATED);
 
         if (extractMode == Upload.Mode.HTTP_DOWNLOAD && extractURLList.size() > 0) {
-            return extractURLList.get(0).getId(); // If download url already exists then return
+            return extractURLList.get(0).getId(); // If download url already
+                                                  // exists then return
         } else {
-            UploadVO uploadJob = _uploadMonitor.createNewUploadEntry(sserver.getId(), volumeId, UploadVO.Status.COPY_IN_PROGRESS, Upload.Type.VOLUME, url, extractMode);
+            UploadVO uploadJob = _uploadMonitor.createNewUploadEntry(sserver.getId(), volumeId, UploadVO.Status.COPY_IN_PROGRESS, Upload.Type.VOLUME,
+                    url, extractMode);
             s_logger.debug("Extract Mode - " + uploadJob.getMode());
             uploadJob = _uploadDao.createForUpdate(uploadJob.getId());
 
             // Update the async Job
-            ExtractResponse resultObj = new ExtractResponse(volumeId, volume.getName(), accountId, UploadVO.Status.COPY_IN_PROGRESS.toString(), uploadJob.getId());
+            ExtractResponse resultObj = new ExtractResponse(volumeId, volume.getName(), accountId, UploadVO.Status.COPY_IN_PROGRESS.toString(),
+                    uploadJob.getId());
             resultObj.setResponseName(cmd.getCommandName());
             AsyncJobExecutor asyncExecutor = BaseAsyncJobExecutor.getCurrentExecutor();
             if (asyncExecutor != null) {
@@ -3091,10 +3145,13 @@ public class ManagementServerImpl implements ManagementServer {
             uploadJob.setInstallPath(volum

<TRUNCATED>