cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ahu...@apache.org
Subject [43/50] [abbrv] merge is complete
Date Mon, 24 Jun 2013 23:52:19 GMT
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/element/InternalLoadBalancerElement.java
----------------------------------------------------------------------
diff --cc plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/element/InternalLoadBalancerElement.java
index 17fc568,18ac13b..f5c1fcd
--- a/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/element/InternalLoadBalancerElement.java
+++ b/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/element/InternalLoadBalancerElement.java
@@@ -202,12 -179,23 +179,23 @@@ public class InternalLoadBalancerElemen
          }
          
          if (vm.getType() == VirtualMachine.Type.User) {
+             return implementInternalLbVms(network, dest);
+         }
+         return true;
+     }
+ 
+ 
+     protected boolean implementInternalLbVms(Network network, DeployDestination dest) throws ResourceUnavailableException {
 -        //1) Get all the Ips from the network having LB rules assigned
 -        List<String> ips = _appLbDao.listLbIpsBySourceIpNetworkIdAndScheme(network.getId(), Scheme.Internal);
 -        
 +          //1) Get all the Ips from the network having LB rules assigned
 +            List<String> ips = _appLbDao.listLbIpsBySourceIpNetworkIdAndScheme(network.getId(), Scheme.Internal);
 +            
-             //2) Start those vms
+         //2) Start internal lb vms for the ips having active rules
 -        for (String ip : ips) {
 -            Ip sourceIp = new Ip(ip);
 +            for (String ip : ips) {
 +                Ip sourceIp = new Ip(ip);
+             long active = _appLbDao.countActiveBySourceIp(sourceIp, network.getId());
+             if (active > 0) {
+                 s_logger.debug("Have to implement internal lb vm for source ip " + sourceIp + " as a part of network " + network
+                         + " implement as there are " + active + " internal lb rules exist for this ip");
                  List<? extends VirtualRouter> internalLbVms;
                  try {
                      internalLbVms = _internalLbMgr.deployInternalLbVm(network, sourceIp, dest, _accountMgr.getAccount(network.getAccountId()), null);
@@@ -410,17 -398,21 +398,21 @@@
      protected Map<Ip, List<LoadBalancingRule>> groupBySourceIp(List<LoadBalancingRule> rules) {
          Map<Ip, List<LoadBalancingRule>> groupedRules = new HashMap<Ip, List<LoadBalancingRule>>();
          for (LoadBalancingRule rule : rules) {
+             if (rule.getDestinations() != null && !rule.getDestinations().isEmpty()) {
 -                Ip sourceIp = rule.getSourceIp();
 -                if (!groupedRules.containsKey(sourceIp)) {
 -                    groupedRules.put(sourceIp, null);
 -                }
 -                
 -                List<LoadBalancingRule> rulesToApply = groupedRules.get(sourceIp);
 -                if (rulesToApply == null) {
 -                    rulesToApply = new ArrayList<LoadBalancingRule>();
 -                }
 -                rulesToApply.add(rule);
 -                groupedRules.put(sourceIp, rulesToApply);
 +            Ip sourceIp = rule.getSourceIp();
 +            if (!groupedRules.containsKey(sourceIp)) {
 +                groupedRules.put(sourceIp, null);
 +            }
 +            
 +            List<LoadBalancingRule> rulesToApply = groupedRules.get(sourceIp);
 +            if (rulesToApply == null) {
 +                rulesToApply = new ArrayList<LoadBalancingRule>();
 +            }
 +            rulesToApply.add(rule);
 +            groupedRules.put(sourceIp, rulesToApply);
+             } else {
+                 s_logger.debug("Internal lb rule " + rule + " doesn't have any vms assigned, skipping");
+             }
          }
          return groupedRules;
      }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java
----------------------------------------------------------------------
diff --cc plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java
index b0ac526,c633d57..f49ea69
--- a/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java
+++ b/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java
@@@ -381,10 -394,19 +381,19 @@@ public class InternalLoadBalancerVMMana
          _mgmtHost = configs.get("host");
          _mgmtCidr = _configDao.getValue(Config.ManagementNetwork.key());
          
-         String offIdStr = configs.get(Config.InternalLbVmServiceOfferingId.key());
-         if (offIdStr != null && !offIdStr.isEmpty()) {
-             _internalLbVmOfferingId = Long.parseLong(offIdStr);
+         String offUUID = configs.get(Config.InternalLbVmServiceOfferingId.key());
+         if (offUUID != null && !offUUID.isEmpty()) {
+             //get the id by offering UUID
+             ServiceOfferingVO off = _serviceOfferingDao.findByUuid(offUUID);
+             if (off != null) {
+                 _internalLbVmOfferingId = off.getId();
 -            } else {
 +        } else {
+                 s_logger.warn("Invalid offering UUID is passed in " + Config.InternalLbVmServiceOfferingId.key() + "; the default offering will be used instead");
+             }
+         }
+         
+         //if offering wasn't set, try to get the default one
+         if (_internalLbVmOfferingId == 0L) {
              boolean useLocalStorage = Boolean.parseBoolean(configs.get(Config.SystemVMUseLocalStorage.key()));
              ServiceOfferingVO newOff = new ServiceOfferingVO("System Offering For Internal LB VM", 1, InternalLoadBalancerVMManager.DEFAULT_INTERNALLB_VM_RAMSIZE, InternalLoadBalancerVMManager.DEFAULT_INTERNALLB_VM_CPU_MHZ, null,
                      null, true, null, useLocalStorage, true, null, true, VirtualMachine.Type.InternalLoadBalancerVm, true);
@@@ -749,46 -765,44 +755,49 @@@
          DomainRouterVO internalLbVm = null;
          for (Iterator<HypervisorType> iter = hypervisors.iterator(); iter.hasNext();) {
              HypervisorType hType = iter.next();
-             s_logger.debug("Allocating the Internal lb with the hypervisor type " + hType);
 -            try {
 -                long id = _internalLbVmDao.getNextInSequence(Long.class, "id");
 -                if (s_logger.isDebugEnabled()) {
 -                    s_logger.debug("Creating the internal lb vm " + id + " in datacenter "  + dest.getDataCenter() + " with hypervisor type " + hType);
 -                }                String templateName = null;
 -                switch (hType) {
 -                    case XenServer:
 -                        templateName = _configServer.getConfigValue(Config.RouterTemplateXen.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 -                        break;
 -                    case KVM:
 -                        templateName = _configServer.getConfigValue(Config.RouterTemplateKVM.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 -                        break;
 -                    case VMware:
 -                        templateName = _configServer.getConfigValue(Config.RouterTemplateVmware.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 -                        break;
 -                    case Hyperv:
 -                        templateName = _configServer.getConfigValue(Config.RouterTemplateHyperv.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 -                        break;
 -                    case LXC:
 -                        templateName = _configServer.getConfigValue(Config.RouterTemplateLXC.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 -                        break;
 -                    default: break;
 -                }
 -                VMTemplateVO template = _templateDao.findRoutingTemplate(hType, templateName);
++            long id = _internalLbVmDao.getNextInSequence(Long.class, "id");
++            if (s_logger.isDebugEnabled()) {
++                s_logger.debug("Creating the internal lb vm " + id + " in datacenter " + dest.getDataCenter() + " with hypervisor type " + hType);
++            }
 +            String templateName = null;
 +            switch (hType) {
 +            case XenServer:
 +                templateName = _configServer.getConfigValue(Config.RouterTemplateXen.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 +                break;
 +            case KVM:
 +                templateName = _configServer.getConfigValue(Config.RouterTemplateKVM.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 +                break;
 +            case VMware:
 +                templateName = _configServer.getConfigValue(Config.RouterTemplateVmware.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 +                break;
 +            case Hyperv:
 +                templateName = _configServer.getConfigValue(Config.RouterTemplateHyperv.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 +                break;
 +            case LXC:
 +                templateName = _configServer.getConfigValue(Config.RouterTemplateLXC.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 +                break;
 +            default:
 +                break;
 +            }
 +            VMTemplateVO template = _templateDao.findRoutingTemplate(hType, templateName);
  
 -                if (template == null) {
 -                    s_logger.debug(hType + " won't support system vm, skip it");
 -                    continue;
 -                }
 +            if (template == null) {
 +                s_logger.debug(hType + " won't support system vm, skip it");
 +                continue;
 +            }
  
 -                internalLbVm = new DomainRouterVO(id, routerOffering.getId(), internalLbProviderId, 
 -                VirtualMachineName.getSystemVmName(id, _instance, _internalLbVmNamePrefix), template.getId(), template.getHypervisorType(),
 -                template.getGuestOSId(), owner.getDomainId(), owner.getId(), false, 0, false, 
 -                RedundantState.UNKNOWN, false, false, VirtualMachine.Type.InternalLoadBalancerVm, vpcId);
 -                internalLbVm.setRole(Role.INTERNAL_LB_VM);
 -                internalLbVm = _itMgr.allocate(internalLbVm, template, routerOffering, networks, plan, null, owner);
 -            } catch (InsufficientCapacityException ex) {
 +            internalLbVm = new DomainRouterVO(id, routerOffering.getId(), internalLbProviderId,
 +                    VirtualMachineName.getSystemVmName(id, _instance, _internalLbVmNamePrefix), template.getId(), template.getHypervisorType(),
 +                    template.getGuestOSId(), owner.getDomainId(), owner.getId(), false, 0, false,
 +                    RedundantState.UNKNOWN, false, false, VirtualMachine.Type.InternalLoadBalancerVm, vpcId);
 +            internalLbVm.setRole(Role.INTERNAL_LB_VM);
 +            internalLbVm = _internalLbVmDao.persist(internalLbVm);
 +            try {
 +                _itMgr.allocate(internalLbVm.getInstanceName(), template, routerOffering, networks, plan, null, owner);
 +            } catch (CloudRuntimeException e) {
                  if (allocateRetry < 2 && iter.hasNext()) {
 +                    allocateRetry++;
 +                    _internalLbVmDao.remove(internalLbVm.getId());
                      s_logger.debug("Failed to allocate the Internal lb vm with hypervisor type " + hType + ", retrying one more time");
                      continue;
                  } else {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/pom.xml
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/storage-allocators/random/src/org/apache/cloudstack/storage/allocator/RandomStoragePoolAllocator.java
----------------------------------------------------------------------
diff --cc plugins/storage-allocators/random/src/org/apache/cloudstack/storage/allocator/RandomStoragePoolAllocator.java
index 0be2dba,76ce663..73f308b
--- a/plugins/storage-allocators/random/src/org/apache/cloudstack/storage/allocator/RandomStoragePoolAllocator.java
+++ b/plugins/storage-allocators/random/src/org/apache/cloudstack/storage/allocator/RandomStoragePoolAllocator.java
@@@ -21,52 -21,53 +21,53 @@@ import java.util.List
  
  import javax.ejb.Local;
  
- import org.apache.cloudstack.engine.subsystem.api.storage.ScopeType;
++import org.apache.log4j.Logger;
++
  import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator;
  import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
  
  import com.cloud.deploy.DeploymentPlan;
  import com.cloud.deploy.DeploymentPlanner.ExcludeList;
+ import com.cloud.storage.ScopeType;
  import com.cloud.storage.StoragePool;
  import com.cloud.vm.DiskProfile;
--import com.cloud.vm.VirtualMachine;
  import com.cloud.vm.VirtualMachineProfile;
  
- @Local(value=StoragePoolAllocator.class)
+ @Local(value = StoragePoolAllocator.class)
  public class RandomStoragePoolAllocator extends AbstractStoragePoolAllocator {
      private static final Logger s_logger = Logger.getLogger(RandomStoragePoolAllocator.class);
 -
 +    
      @Override
-     public List<StoragePool> select(DiskProfile dskCh, VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid, int returnUpTo) {
 -    public List<StoragePool> select(DiskProfile dskCh, VirtualMachineProfile<? extends VirtualMachine> vmProfile,
++    public List<StoragePool> select(DiskProfile dskCh, VirtualMachineProfile vmProfile,
+             DeploymentPlan plan, ExcludeList avoid, int returnUpTo) {
  
 -        List<StoragePool> suitablePools = new ArrayList<StoragePool>();
 -
 -        long dcId = plan.getDataCenterId();
 -        Long podId = plan.getPodId();
 -        Long clusterId = plan.getClusterId();
 +    	List<StoragePool> suitablePools = new ArrayList<StoragePool>();
 +    	
 +		long dcId = plan.getDataCenterId();
 +		Long podId = plan.getPodId();
 +		Long clusterId = plan.getClusterId();
          s_logger.debug("Looking for pools in dc: " + dcId + "  pod:" + podId + "  cluster:" + clusterId);
 -        List<StoragePoolVO> pools = _storagePoolDao.listBy(dcId, podId, clusterId, ScopeType.CLUSTER);
 +    	List<StoragePoolVO> pools = _storagePoolDao.listBy(dcId, podId, clusterId, ScopeType.CLUSTER);
          if (pools.size() == 0) {
 -            if (s_logger.isDebugEnabled()) {
 -                s_logger.debug("No storage pools available for allocation, returning");
 -            }
 +        	if (s_logger.isDebugEnabled()) {
 +        		s_logger.debug("No storage pools available for allocation, returning");
 +    		}
              return suitablePools;
          }
 -
 +        
          Collections.shuffle(pools);
 -        if (s_logger.isDebugEnabled()) {
 +    	if (s_logger.isDebugEnabled()) {
              s_logger.debug("RandomStoragePoolAllocator has " + pools.size() + " pools to check for allocation");
          }
-         for (StoragePoolVO pool: pools) {
-         	if(suitablePools.size() == returnUpTo){
+         for (StoragePoolVO pool : pools) {
+             if (suitablePools.size() == returnUpTo) {
 -                break;
 -            }
 -            StoragePool pol = (StoragePool) this.dataStoreMgr.getPrimaryDataStore(pool.getId());
 -
 -            if (filter(avoid, pol, dskCh, plan)) {
 -                suitablePools.add(pol);
 -            }
 +        		break;
-         	}        	
-         	StoragePool pol = (StoragePool)this.dataStoreMgr.getPrimaryDataStore(pool.getId());
++        	}
++            StoragePool pol = (StoragePool) dataStoreMgr.getPrimaryDataStore(pool.getId());
 +            
 +        	if (filter(avoid, pol, dskCh, plan)) {
 +        		suitablePools.add(pol);
 +        	}
          }
  
          if (s_logger.isDebugEnabled()) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/agent/manager/AgentManagerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/api/ApiDBUtils.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/api/ApiResponseHelper.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/api/ApiResponseHelper.java
index caef5e9,b56aa4a..9fd101e
--- a/server/src/com/cloud/api/ApiResponseHelper.java
+++ b/server/src/com/cloud/api/ApiResponseHelper.java
@@@ -74,6 -70,6 +71,7 @@@ import org.apache.cloudstack.api.respon
  import org.apache.cloudstack.api.response.HostResponse;
  import org.apache.cloudstack.api.response.HypervisorCapabilitiesResponse;
  import org.apache.cloudstack.api.response.IPAddressResponse;
++import org.apache.cloudstack.api.response.ImageStoreResponse;
  import org.apache.cloudstack.api.response.InstanceGroupResponse;
  import org.apache.cloudstack.api.response.InternalLoadBalancerElementResponse;
  import org.apache.cloudstack.api.response.IpForwardingRuleResponse;
@@@ -175,9 -176,9 +176,8 @@@ import com.cloud.configuration.Resource
  import com.cloud.configuration.Resource.ResourceType;
  import com.cloud.configuration.ResourceCount;
  import com.cloud.configuration.ResourceLimit;
 -import com.cloud.dao.EntityManager;
  import com.cloud.dc.ClusterVO;
  import com.cloud.dc.DataCenter;
- import com.cloud.dc.DataCenterVO;
  import com.cloud.dc.HostPodVO;
  import com.cloud.dc.Pod;
  import com.cloud.dc.StorageNetworkIpRange;
@@@ -261,15 -262,11 +263,11 @@@ import com.cloud.storage.ImageStore
  import com.cloud.storage.S3;
  import com.cloud.storage.Snapshot;
  import com.cloud.storage.SnapshotVO;
- import com.cloud.storage.Storage.ImageFormat;
- import com.cloud.storage.Storage.TemplateType;
 -import com.cloud.storage.Upload;
+ import com.cloud.storage.Storage.StoragePoolType;
  import com.cloud.storage.StoragePool;
  import com.cloud.storage.Swift;
++import com.cloud.storage.Upload;
  import com.cloud.storage.UploadVO;
- import com.cloud.storage.VMTemplateHostVO;
- import com.cloud.storage.VMTemplateS3VO;
- import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
- import com.cloud.storage.VMTemplateSwiftVO;
  import com.cloud.storage.VMTemplateVO;
  import com.cloud.storage.Volume;
  import com.cloud.storage.VolumeVO;
@@@ -302,13 -299,11 +300,15 @@@ public class ApiResponseHelper implemen
  
      public final Logger s_logger = Logger.getLogger(ApiResponseHelper.class);
      private static final DecimalFormat s_percentFormat = new DecimalFormat("##.##");
-     @Inject private final EntityManager _entityMgr = null;
-     @Inject private final UsageService _usageSvc = null;
+     @Inject
 -    private EntityManager _entityMgr = null;
++    private final EntityManager _entityMgr = null;
+     @Inject
 -    private UsageService _usageSvc = null;
++    private final UsageService _usageSvc = null;
      @Inject NetworkModel _ntwkModel;
 +    @Inject
 +    AccountManager _accountMgr;
 +    @Inject
 +    AsyncJobManager _jobMgr;
  
      @Override
      public UserResponse createUserResponse(User user) {
@@@ -1142,15 -1136,15 +1141,15 @@@
              vmResponse.setSystemVmType(vm.getType().toString().toLowerCase());
  
              vmResponse.setName(vm.getHostName());
-             if ( vm.getPodIdToDeployIn() != null ){
+             if (vm.getPodIdToDeployIn() != null) {
                  HostPodVO pod = ApiDBUtils.findPodById(vm.getPodIdToDeployIn());
-                 if ( pod != null ){
+                 if (pod != null) {
 -                    vmResponse.setPodId(pod.getUuid());
 +            vmResponse.setPodId(pod.getUuid());
                  }
              }
              VMTemplateVO template = ApiDBUtils.findTemplateById(vm.getTemplateId());
-             if (template != null){
+             if (template != null) {
 -                vmResponse.setTemplateId(template.getUuid());
 +            vmResponse.setTemplateId(template.getUuid());
              }
              vmResponse.setCreated(vm.getCreated());
  
@@@ -1417,126 -1288,25 +1293,24 @@@
      }
  
      @Override
-     public List<TemplateResponse> createTemplateResponses(long templateId, long zoneId, boolean readyOnly) {
+     public List<TemplateResponse> createTemplateResponses(long templateId, Long zoneId, boolean readyOnly) {
          VirtualMachineTemplate template = findTemplateById(templateId);
-         List<TemplateResponse> responses = new ArrayList<TemplateResponse>();
-         VMTemplateHostVO templateHostRef = ApiDBUtils.findTemplateHostRef(templateId, zoneId, readyOnly);
-         if (templateHostRef == null) {
-             return responses;
-         }
- 
-         HostVO host = ApiDBUtils.findHostById(templateHostRef.getHostId());
-         if (host.getType() == Host.Type.LocalSecondaryStorage && host.getStatus() != com.cloud.host.Status.Up) {
-             return responses;
-         }
- 
-         TemplateResponse templateResponse = new TemplateResponse();
-         templateResponse.setId(template.getUuid());
-         templateResponse.setName(template.getName());
-         templateResponse.setDisplayText(template.getDisplayText());
-         templateResponse.setPublic(template.isPublicTemplate());
-         templateResponse.setCreated(templateHostRef.getCreated());
- 
-         templateResponse.setReady(templateHostRef.getDownloadState() == Status.DOWNLOADED);
-         templateResponse.setFeatured(template.isFeatured());
-         templateResponse.setExtractable(template.isExtractable() && !(template.getTemplateType() == TemplateType.SYSTEM));
-         templateResponse.setPasswordEnabled(template.getEnablePassword());
-         templateResponse.setSshKeyEnabled(template.getEnableSshKey());
-         templateResponse.setCrossZones(template.isCrossZones());
-         templateResponse.setFormat(template.getFormat());
-         if (template.getTemplateType() != null) {
-             templateResponse.setTemplateType(template.getTemplateType().toString());
-         }
- 
-         templateResponse.setHypervisor(template.getHypervisorType().toString());
-         templateResponse.setDetails(template.getDetails());
- 
-         GuestOS os = ApiDBUtils.findGuestOSById(template.getGuestOSId());
-         if (os != null) {
-             templateResponse.setOsTypeId(os.getUuid());
-             templateResponse.setOsTypeName(os.getDisplayName());
-         } else {
-             templateResponse.setOsTypeId("-1");
-             templateResponse.setOsTypeName("");
-         }
- 
-         Account account = ApiDBUtils.findAccountByIdIncludingRemoved(template.getAccountId());
-         populateAccount(templateResponse, account.getId());
-         populateDomain(templateResponse, account.getDomainId());
- 
-         DataCenter datacenter = ApiDBUtils.findZoneById(zoneId);
- 
-         if (datacenter != null) {
-             // Add the zone ID
-             templateResponse.setZoneId(datacenter.getUuid());
-             templateResponse.setZoneName(datacenter.getName());
-             templateResponse.setZoneType(datacenter.getNetworkType().toString());
-         }
- 
-         boolean isAdmin = false;
-         Account caller = CallContext.current().getCallingAccount();
-         if ((caller == null) || BaseCmd.isAdmin(caller.getType())) {
-             isAdmin = true;
-         }
- 
-         // If the user is an Admin, add the template download status
-         if (isAdmin || caller.getId() == template.getAccountId()) {
-             // add download status
-             if (templateHostRef.getDownloadState() != Status.DOWNLOADED) {
-                 String templateStatus = "Processing";
-                 if (templateHostRef.getDownloadState() == VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS) {
-                     if (templateHostRef.getDownloadPercent() == 100) {
-                         templateStatus = "Installing Template";
-                     } else {
-                         templateStatus = templateHostRef.getDownloadPercent() + "% Downloaded";
-                     }
-                 } else {
-                     templateStatus = templateHostRef.getErrorString();
-                 }
-                 templateResponse.setStatus(templateStatus);
-             } else if (templateHostRef.getDownloadState() == VMTemplateHostVO.Status.DOWNLOADED) {
-                 templateResponse.setStatus("Download Complete");
-             } else {
-                 templateResponse.setStatus("Successfully Installed");
-             }
-         }
- 
-         Long templateSize = templateHostRef.getSize();
-         if (templateSize > 0) {
-             templateResponse.setSize(templateSize);
-         }
- 
-         templateResponse.setChecksum(template.getChecksum());
-         if (template.getSourceTemplateId() != null) {
-             VirtualMachineTemplate tmpl = ApiDBUtils.findTemplateById(template.getSourceTemplateId());
-             if (tmpl != null) {
-                 templateResponse.setSourceTemplateId(tmpl.getUuid());
-             }
-         }
- 
-         templateResponse.setChecksum(template.getChecksum());
- 
-         templateResponse.setTemplateTag(template.getTemplateTag());
+         return createTemplateResponses(template, zoneId, readyOnly);
+     }
  
-         //set tag information
-         List<? extends ResourceTag> tags = null;
-         if (template.getFormat() == ImageFormat.ISO) {
-             tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.ISO, template.getId());
 -
+     @Override
+     public List<TemplateResponse> createIsoResponses(VirtualMachineTemplate result, Long zoneId, boolean readyOnly) {
+         List<TemplateJoinVO> tvo = null;
+         if (zoneId == null || zoneId == -1) {
+             tvo = ApiDBUtils.newTemplateView(result);
          } else {
-             tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.Template, template.getId());
-         }
-         List<ResourceTagResponse> tagResponses = new ArrayList<ResourceTagResponse>();
-         for (ResourceTag tag : tags) {
-             ResourceTagResponse tagResponse = createResourceTagResponse(tag, true);
-             tagResponses.add(tagResponse);
+             tvo = ApiDBUtils.newTemplateView(result, zoneId, readyOnly);
          }
-         templateResponse.setTags(tagResponses);
  
-         templateResponse.setObjectName("template");
-         responses.add(templateResponse);
-         return responses;
+         return ViewResponseHelper.createIsoResponse(tvo.toArray(new TemplateJoinVO[tvo.size()]));
      }
  
+     /*
      @Override
      public List<TemplateResponse> createIsoResponses(long isoId, Long zoneId, boolean readyOnly) {
  
@@@ -1564,8 -1334,8 +1338,8 @@@
              populateAccount(isoResponse, owner.getId());
              populateDomain(isoResponse, owner.getDomainId());
  
-             //set tag information
+             // set tag information
 -            List<? extends ResourceTag> tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.ISO, iso.getId());
 +            List<? extends ResourceTag> tags =  ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.ISO, iso.getId());
              List<ResourceTagResponse> tagResponses = new ArrayList<ResourceTagResponse>();
              for (ResourceTag tag : tags) {
                  ResourceTagResponse tagResponse = createResourceTagResponse(tag, true);
@@@ -1789,8 -1558,8 +1562,8 @@@
              isoResponse.setSize(isoSize);
          }
  
-         //set tag information
+         // set tag information
 -        List<? extends ResourceTag> tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.ISO, iso.getId());
 +        List<? extends ResourceTag> tags =  ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.ISO, iso.getId());
  
          List<ResourceTagResponse> tagResponses = new ArrayList<ResourceTagResponse>();
          for (ResourceTag tag : tags) {
@@@ -1828,11 -1597,41 +1601,41 @@@
              response.setZoneName(zone.getName());
          }
          response.setMode(mode);
+         response.setUrl(url);
+         response.setState(Upload.Status.DOWNLOAD_URL_CREATED.toString());
+         Account account = ApiDBUtils.findAccountById(accountId);
+         response.setAccountId(account.getUuid());
+ 
+         return response;
+     }
+ 
+     @Override
+     public ExtractResponse createExtractResponse(Long uploadId, Long id, Long zoneId, Long accountId, String mode, String url) {
+ 
+         ExtractResponse response = new ExtractResponse();
+         response.setObjectName("template");
+         VMTemplateVO template = ApiDBUtils.findTemplateById(id);
+         response.setId(template.getUuid());
+         response.setName(template.getName());
+         if (zoneId != null) {
+             DataCenter zone = ApiDBUtils.findZoneById(zoneId);
+             response.setZoneId(zone.getUuid());
+             response.setZoneName(zone.getName());
+         }
+         response.setMode(mode);
+         if (uploadId == null) {
+             // region-wide image store
+             response.setUrl(url);
+             response.setState(Upload.Status.DOWNLOAD_URL_CREATED.toString());
+         } else {
+             UploadVO uploadInfo = ApiDBUtils.findUploadById(uploadId);
 -            response.setUploadId(uploadInfo.getUuid());
 -            response.setState(uploadInfo.getUploadState().toString());
 +        response.setUploadId(uploadInfo.getUuid());
 +        response.setState(uploadInfo.getUploadState().toString());
+             response.setUrl(uploadInfo.getUploadUrl());
+         }
          Account account = ApiDBUtils.findAccountById(accountId);
          response.setAccountId(account.getUuid());
-         response.setUrl(uploadInfo.getUploadUrl());
+ 
          return response;
  
      }
@@@ -2214,40 -2151,41 +2168,41 @@@
          response.setIp6Gateway(network.getIp6Gateway());
          response.setIp6Cidr(network.getIp6Cidr());
  
-         // create response for reserved IP ranges that can be used for non-cloudstack purposes
+         // create response for reserved IP ranges that can be used for
+         // non-cloudstack purposes
 -        String reservation = null;
 +        String  reservation = null;
          if ((network.getCidr() != null) && (NetUtils.isNetworkAWithinNetworkB(network.getCidr(), network.getNetworkCidr()))) {
 -            String[] guestVmCidrPair = network.getCidr().split("\\/");
 -            String[] guestCidrPair = network.getNetworkCidr().split("\\/");
 +                String[] guestVmCidrPair = network.getCidr().split("\\/");
 +                String[] guestCidrPair = network.getNetworkCidr().split("\\/");
  
 -            Long guestVmCidrSize = Long.valueOf(guestVmCidrPair[1]);
 -            Long guestCidrSize = Long.valueOf(guestCidrPair[1]);
 +                Long guestVmCidrSize = Long.valueOf(guestVmCidrPair[1]);
 +                Long guestCidrSize = Long.valueOf(guestCidrPair[1]);
  
 -            String[] guestVmIpRange = NetUtils.getIpRangeFromCidr(guestVmCidrPair[0], guestVmCidrSize);
 -            String[] guestIpRange = NetUtils.getIpRangeFromCidr(guestCidrPair[0], guestCidrSize);
 -            long startGuestIp = NetUtils.ip2Long(guestIpRange[0]);
 -            long endGuestIp = NetUtils.ip2Long(guestIpRange[1]);
 -            long startVmIp = NetUtils.ip2Long(guestVmIpRange[0]);
 -            long endVmIp = NetUtils.ip2Long(guestVmIpRange[1]);
 +                String[] guestVmIpRange = NetUtils.getIpRangeFromCidr(guestVmCidrPair[0], guestVmCidrSize);
 +                String[] guestIpRange = NetUtils.getIpRangeFromCidr(guestCidrPair[0], guestCidrSize);
 +                long startGuestIp = NetUtils.ip2Long(guestIpRange[0]);
 +                long endGuestIp = NetUtils.ip2Long(guestIpRange[1]);
 +                long startVmIp = NetUtils.ip2Long(guestVmIpRange[0]);
 +                long endVmIp = NetUtils.ip2Long(guestVmIpRange[1]);
  
-                 if (startVmIp == startGuestIp && endVmIp < endGuestIp -1) {
+             if (startVmIp == startGuestIp && endVmIp < endGuestIp - 1) {
 -                reservation = (NetUtils.long2Ip(endVmIp + 1) + "-" + NetUtils.long2Ip(endGuestIp));
 -            }
 -            if (endVmIp == endGuestIp && startVmIp > startGuestIp + 1) {
 +                    reservation = (NetUtils.long2Ip(endVmIp + 1) + "-" + NetUtils.long2Ip(endGuestIp));
 +                }
 +                if (endVmIp == endGuestIp && startVmIp > startGuestIp + 1) {
-                     reservation = (NetUtils.long2Ip(startGuestIp) + "-" + NetUtils.long2Ip(startVmIp-1));
+                 reservation = (NetUtils.long2Ip(startGuestIp) + "-" + NetUtils.long2Ip(startVmIp - 1));
 -            }
 +                }
-                 if(startVmIp > startGuestIp + 1 && endVmIp < endGuestIp - 1) {
-                 reservation = (NetUtils.long2Ip(startGuestIp) + "-" +  NetUtils.long2Ip(startVmIp-1) + " ,  " +
-                         NetUtils.long2Ip(endVmIp + 1) + "-"+  NetUtils.long2Ip(endGuestIp));
+             if (startVmIp > startGuestIp + 1 && endVmIp < endGuestIp - 1) {
+                 reservation = (NetUtils.long2Ip(startGuestIp) + "-" + NetUtils.long2Ip(startVmIp - 1) + " ,  " + NetUtils.long2Ip(endVmIp + 1) + "-" + NetUtils
+                         .long2Ip(endGuestIp));
              }
          }
          response.setReservedIpRange(reservation);
  
-         //return vlan information only to Root admin
+         // return vlan information only to Root admin
 -        if (network.getBroadcastUri() != null && UserContext.current().getCaller().getType() == Account.ACCOUNT_TYPE_ADMIN) {
 +        if (network.getBroadcastUri() != null && CallContext.current().getCallingAccount().getType() == Account.ACCOUNT_TYPE_ADMIN) {
              String broadcastUri = network.getBroadcastUri().toString();
              response.setBroadcastUri(broadcastUri);
-             String vlan="N/A";
+             String vlan = "N/A";
              if (broadcastUri.startsWith("vlan")) {
                  vlan = broadcastUri.substring("vlan://".length(), broadcastUri.length());
              }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/api/query/QueryManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/api/query/QueryManagerImpl.java
index de39793,9a80082..a7217ce
--- a/server/src/com/cloud/api/query/QueryManagerImpl.java
+++ b/server/src/com/cloud/api/query/QueryManagerImpl.java
@@@ -54,28 -56,11 +58,31 @@@ import org.apache.cloudstack.api.comman
  import org.apache.cloudstack.api.command.user.volume.ListResourceDetailsCmd;
  import org.apache.cloudstack.api.command.user.volume.ListVolumesCmd;
  import org.apache.cloudstack.api.command.user.zone.ListZonesByCmd;
 -import org.apache.cloudstack.api.response.*;
 +import org.apache.cloudstack.api.response.AccountResponse;
 +import org.apache.cloudstack.api.response.AsyncJobResponse;
 +import org.apache.cloudstack.api.response.DiskOfferingResponse;
 +import org.apache.cloudstack.api.response.DomainRouterResponse;
 +import org.apache.cloudstack.api.response.EventResponse;
 +import org.apache.cloudstack.api.response.HostResponse;
++import org.apache.cloudstack.api.response.ImageStoreResponse;
 +import org.apache.cloudstack.api.response.InstanceGroupResponse;
 +import org.apache.cloudstack.api.response.ListResponse;
 +import org.apache.cloudstack.api.response.ProjectAccountResponse;
 +import org.apache.cloudstack.api.response.ProjectInvitationResponse;
 +import org.apache.cloudstack.api.response.ProjectResponse;
 +import org.apache.cloudstack.api.response.ResourceDetailResponse;
 +import org.apache.cloudstack.api.response.ResourceTagResponse;
 +import org.apache.cloudstack.api.response.SecurityGroupResponse;
 +import org.apache.cloudstack.api.response.ServiceOfferingResponse;
 +import org.apache.cloudstack.api.response.StoragePoolResponse;
++import org.apache.cloudstack.api.response.TemplateResponse;
 +import org.apache.cloudstack.api.response.UserResponse;
 +import org.apache.cloudstack.api.response.UserVmResponse;
 +import org.apache.cloudstack.api.response.VolumeResponse;
 +import org.apache.cloudstack.api.response.ZoneResponse;
 +import org.apache.cloudstack.context.CallContext;
+ import org.apache.cloudstack.engine.subsystem.api.storage.TemplateState;
  import org.apache.cloudstack.query.QueryService;
 -import org.apache.log4j.Logger;
 -import org.springframework.stereotype.Component;
  
  import com.cloud.api.query.dao.AccountJoinDao;
  import com.cloud.api.query.dao.AffinityGroupJoinDao;
@@@ -141,9 -132,11 +154,17 @@@ import com.cloud.server.ResourceTag.Tag
  import com.cloud.server.TaggedResourceService;
  import com.cloud.service.ServiceOfferingVO;
  import com.cloud.service.dao.ServiceOfferingDao;
++import com.cloud.storage.DataStoreRole;
++import com.cloud.storage.ScopeType;
++import com.cloud.storage.Storage;
+ import com.cloud.storage.Storage.ImageFormat;
+ import com.cloud.storage.Storage.TemplateType;
++import com.cloud.storage.VMTemplateVO;
 +import com.cloud.storage.Volume;
 +import com.cloud.storage.VolumeDetailVO;
+ import com.cloud.storage.dao.VMTemplateDao;
  import com.cloud.storage.dao.VolumeDetailsDao;
+ import com.cloud.template.VirtualMachineTemplate.TemplateFilter;
  import com.cloud.user.Account;
  import com.cloud.user.AccountManager;
  import com.cloud.user.AccountVO;
@@@ -295,10 -306,11 +333,10 @@@ public class QueryManagerImpl extends M
          return response;
      }
  
 -    private Pair<List<UserAccountJoinVO>, Integer> searchForUsersInternal(ListUsersCmd cmd)
 -            throws PermissionDeniedException {
 -        Account caller = UserContext.current().getCaller();
 +    private Pair<List<UserAccountJoinVO>, Integer> searchForUsersInternal(ListUsersCmd cmd) throws PermissionDeniedException {
 +        Account caller = CallContext.current().getCallingAccount();
  
-         //TODO: Integrate with ACL checkAccess refactoring
+         // TODO: Integrate with ACL checkAccess refactoring
          Long domainId = cmd.getDomainId();
          if (domainId != null) {
              Domain domain = _domainDao.findById(domainId);
@@@ -871,9 -894,9 +920,9 @@@
          }
  
          // search vm details by ids
 -        Pair<List<UserVmJoinVO>, Integer> uniqueVmPair = _userVmJoinDao.searchAndCount(sc, searchFilter);
 +        Pair<List<UserVmJoinVO>, Integer> uniqueVmPair =  _userVmJoinDao.searchAndCount(sc, searchFilter);
          Integer count = uniqueVmPair.second();
-         if ( count.intValue() == 0 ){
+         if (count.intValue() == 0) {
              // handle empty result cases
              return uniqueVmPair;
          }
@@@ -965,9 -990,9 +1015,9 @@@
          }
  
          // search security group together with rules
 -        Pair<List<SecurityGroupJoinVO>, Integer> uniqueSgPair = _securityGroupJoinDao.searchAndCount(sc, searchFilter);
 +        Pair<List<SecurityGroupJoinVO>, Integer> uniqueSgPair =  _securityGroupJoinDao.searchAndCount(sc, searchFilter);
          Integer count = uniqueSgPair.second();
-         if ( count.intValue() == 0 ){
+         if (count.intValue() == 0) {
              // handle empty result cases
              return uniqueSgPair;
          }
@@@ -1026,12 -1051,10 +1076,10 @@@
          return response;
      }
  
- 
      private Pair<List<DomainRouterJoinVO>, Integer> searchForRoutersInternal(BaseListProjectAndAccountResourcesCmd cmd, Long id,
-             String name, String state, Long zoneId, Long podId, Long hostId, String keyword, Long networkId, Long vpcId, Boolean forVpc, String role, String zoneType) {
-        
+             String name, String state, Long zoneId, Long podId, Long hostId, String keyword, Long networkId, Long vpcId, Boolean forVpc, String role) {
  
 -        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>(
@@@ -1323,11 -1332,13 +1357,13 @@@
          boolean isRecursive = cmd.isRecursive();
          boolean listAll = cmd.listAll();
  
 -        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>(domainId, isRecursive, null);
-         _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, listAll, true);
+         Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
+                 domainId, isRecursive, null);
+         _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts,
+                 domainIdRecursiveListProject, listAll, true);
          domainId = domainIdRecursiveListProject.first();
          isRecursive = domainIdRecursiveListProject.second();
          ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
@@@ -1384,10 -1396,11 +1421,10 @@@
          Long startIndex = cmd.getStartIndex();
          Long pageSizeVal = cmd.getPageSizeVal();
  
 -        // long projectId, String accountName, String role, Long startIndex,
 -        // Long pageSizeVal) {
 -        Account caller = UserContext.current().getCaller();
 +        //long projectId, String accountName, String role, Long startIndex, Long pageSizeVal) {
 +        Account caller = CallContext.current().getCallingAccount();
  
-         //check that the project exists
+         // check that the project exists
          Project project = _projectDao.findById(projectId);
  
          if (project == null) {
@@@ -1521,9 -1539,9 +1563,9 @@@
          }
  
          // search host details by ids
 -        Pair<List<HostJoinVO>, Integer> uniqueHostPair = _hostJoinDao.searchAndCount(sc, searchFilter);
 +        Pair<List<HostJoinVO>, Integer> uniqueHostPair =  _hostJoinDao.searchAndCount(sc, searchFilter);
          Integer count = uniqueHostPair.second();
-         if ( count.intValue() == 0 ){
+         if (count.intValue() == 0) {
              // handle empty result cases
              return uniqueHostPair;
          }
@@@ -1548,10 -1567,9 +1591,9 @@@
          return response;
      }
  
- 
      private Pair<List<VolumeJoinVO>, Integer> searchForVolumesInternal(ListVolumesCmd cmd) {
  
 -        Account caller = UserContext.current().getCaller();
 +        Account caller = CallContext.current().getCallingAccount();
          List<Long> permittedAccounts = new ArrayList<Long>();
  
          Long id = cmd.getId();
@@@ -1684,9 -1703,8 +1727,8 @@@
          return response;
      }
  
- 
      private Pair<List<AccountJoinVO>, Integer> searchForAccountsInternal(ListAccountsCmd cmd) {
 -        Account caller = UserContext.current().getCaller();
 +        Account caller = CallContext.current().getCallingAccount();
          Long domainId = cmd.getDomainId();
          Long accountId = cmd.getId();
          String accountName = cmd.getSearchName();
@@@ -1811,10 -1830,9 +1854,9 @@@
          return response;
      }
  
- 
      private Pair<List<AsyncJobJoinVO>, Integer> searchForAsyncJobsInternal(ListAsyncJobsCmd cmd) {
  
 -        Account caller = UserContext.current().getCaller();
 +        Account caller = CallContext.current().getCallingAccount();
  
          List<Long> permittedAccounts = new ArrayList<Long>();
  
@@@ -1892,8 -1911,16 +1935,16 @@@
      }
  
      private Pair<List<StoragePoolJoinVO>, Integer> searchForStoragePoolsInternal(ListStoragePoolsCmd cmd) {
+         ScopeType scopeType = null;
+         if (cmd.getScope() != null) {
+             try {
+                 scopeType = Enum.valueOf(ScopeType.class, cmd.getScope().toUpperCase());
+             } catch (Exception e) {
+                 throw new InvalidParameterValueException("Invalid scope type: " + cmd.getScope());
+             }
+         }
  
 -        Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId());
 +        Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), cmd.getZoneId());
          Object id = cmd.getId();
          Object name = cmd.getStoragePoolName();
          Object path = cmd.getPath();
@@@ -1972,6 -2000,166 +2024,166 @@@
      }
  
      @Override
+     public ListResponse<ImageStoreResponse> searchForImageStores(ListImageStoresCmd cmd) {
+         Pair<List<ImageStoreJoinVO>, Integer> result = searchForImageStoresInternal(cmd);
+         ListResponse<ImageStoreResponse> response = new ListResponse<ImageStoreResponse>();
+ 
+         List<ImageStoreResponse> poolResponses = ViewResponseHelper.createImageStoreResponse(result.first().toArray(
+                 new ImageStoreJoinVO[result.first().size()]));
+         response.setResponses(poolResponses, result.second());
+         return response;
+     }
+ 
+     private Pair<List<ImageStoreJoinVO>, Integer> searchForImageStoresInternal(ListImageStoresCmd cmd) {
+ 
 -        Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId());
++        Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), cmd.getZoneId());
+         Object id = cmd.getId();
+         Object name = cmd.getStoreName();
+         String provider = cmd.getProvider();
+         String protocol = cmd.getProtocol();
+         Object keyword = cmd.getKeyword();
+         Long startIndex = cmd.getStartIndex();
+         Long pageSize = cmd.getPageSizeVal();
+ 
+         Filter searchFilter = new Filter(ImageStoreJoinVO.class, "id", Boolean.TRUE, startIndex, pageSize);
+ 
+         SearchBuilder<ImageStoreJoinVO> sb = _imageStoreJoinDao.createSearchBuilder();
+         sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
+                                                              // ids
+         sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
+         sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ);
+         sb.and("dataCenterId", sb.entity().getZoneId(), SearchCriteria.Op.EQ);
+         sb.and("protocol", sb.entity().getProtocol(), SearchCriteria.Op.EQ);
+         sb.and("provider", sb.entity().getProviderName(), SearchCriteria.Op.EQ);
+         sb.and("role", sb.entity().getRole(), SearchCriteria.Op.EQ);
+ 
+         SearchCriteria<ImageStoreJoinVO> sc = sb.create();
+         sc.setParameters("role", DataStoreRole.Image);
+ 
+         if (keyword != null) {
+             SearchCriteria<ImageStoreJoinVO> ssc = _imageStoreJoinDao.createSearchCriteria();
+             ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
+             ssc.addOr("provider", SearchCriteria.Op.LIKE, "%" + keyword + "%");
+             sc.addAnd("name", SearchCriteria.Op.SC, ssc);
+         }
+ 
+         if (id != null) {
+             sc.setParameters("id", id);
+         }
+ 
+         if (name != null) {
+             sc.setParameters("name", name);
+         }
+ 
+         if (zoneId != null) {
+             sc.setParameters("dataCenterId", zoneId);
+         }
+         if (provider != null) {
+             sc.setParameters("provider", provider);
+         }
+         if (protocol != null) {
+             sc.setParameters("protocol", protocol);
+         }
+ 
+         // search Store details by ids
+         Pair<List<ImageStoreJoinVO>, Integer> uniqueStorePair = _imageStoreJoinDao.searchAndCount(sc, searchFilter);
+         Integer count = uniqueStorePair.second();
+         if (count.intValue() == 0) {
+             // empty result
+             return uniqueStorePair;
+         }
+         List<ImageStoreJoinVO> uniqueStores = uniqueStorePair.first();
+         Long[] vrIds = new Long[uniqueStores.size()];
+         int i = 0;
+         for (ImageStoreJoinVO v : uniqueStores) {
+             vrIds[i++] = v.getId();
+         }
+         List<ImageStoreJoinVO> vrs = _imageStoreJoinDao.searchByIds(vrIds);
+         return new Pair<List<ImageStoreJoinVO>, Integer>(vrs, count);
+ 
+     }
+ 
+     @Override
+     public ListResponse<ImageStoreResponse> searchForCacheStores(ListCacheStoresCmd cmd) {
+         Pair<List<ImageStoreJoinVO>, Integer> result = searchForCacheStoresInternal(cmd);
+         ListResponse<ImageStoreResponse> response = new ListResponse<ImageStoreResponse>();
+ 
+         List<ImageStoreResponse> poolResponses = ViewResponseHelper.createImageStoreResponse(result.first().toArray(
+                 new ImageStoreJoinVO[result.first().size()]));
+         response.setResponses(poolResponses, result.second());
+         return response;
+     }
+ 
+     private Pair<List<ImageStoreJoinVO>, Integer> searchForCacheStoresInternal(ListCacheStoresCmd cmd) {
+ 
 -        Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId());
++        Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), cmd.getZoneId());
+         Object id = cmd.getId();
+         Object name = cmd.getStoreName();
+         String provider = cmd.getProvider();
+         String protocol = cmd.getProtocol();
+         Object keyword = cmd.getKeyword();
+         Long startIndex = cmd.getStartIndex();
+         Long pageSize = cmd.getPageSizeVal();
+ 
+         Filter searchFilter = new Filter(ImageStoreJoinVO.class, "id", Boolean.TRUE, startIndex, pageSize);
+ 
+         SearchBuilder<ImageStoreJoinVO> sb = _imageStoreJoinDao.createSearchBuilder();
+         sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
+                                                              // ids
+         sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
+         sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ);
+         sb.and("dataCenterId", sb.entity().getZoneId(), SearchCriteria.Op.EQ);
+         sb.and("protocol", sb.entity().getProtocol(), SearchCriteria.Op.EQ);
+         sb.and("provider", sb.entity().getProviderName(), SearchCriteria.Op.EQ);
+         sb.and("role", sb.entity().getRole(), SearchCriteria.Op.EQ);
+ 
+         SearchCriteria<ImageStoreJoinVO> sc = sb.create();
+         sc.setParameters("role", DataStoreRole.ImageCache);
+ 
+         if (keyword != null) {
+             SearchCriteria<ImageStoreJoinVO> ssc = _imageStoreJoinDao.createSearchCriteria();
+             ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
+             ssc.addOr("provider", SearchCriteria.Op.LIKE, "%" + keyword + "%");
+             sc.addAnd("name", SearchCriteria.Op.SC, ssc);
+         }
+ 
+         if (id != null) {
+             sc.setParameters("id", id);
+         }
+ 
+         if (name != null) {
+             sc.setParameters("name", name);
+         }
+ 
+         if (zoneId != null) {
+             sc.setParameters("dataCenterId", zoneId);
+         }
+         if (provider != null) {
+             sc.setParameters("provider", provider);
+         }
+         if (protocol != null) {
+             sc.setParameters("protocol", protocol);
+         }
+ 
+         // search Store details by ids
+         Pair<List<ImageStoreJoinVO>, Integer> uniqueStorePair = _imageStoreJoinDao.searchAndCount(sc, searchFilter);
+         Integer count = uniqueStorePair.second();
+         if (count.intValue() == 0) {
+             // empty result
+             return uniqueStorePair;
+         }
+         List<ImageStoreJoinVO> uniqueStores = uniqueStorePair.first();
+         Long[] vrIds = new Long[uniqueStores.size()];
+         int i = 0;
+         for (ImageStoreJoinVO v : uniqueStores) {
+             vrIds[i++] = v.getId();
+         }
+         List<ImageStoreJoinVO> vrs = _imageStoreJoinDao.searchByIds(vrIds);
+         return new Pair<List<ImageStoreJoinVO>, Integer>(vrs, count);
+ 
+     }
+ 
+     @Override
      public ListResponse<DiskOfferingResponse> searchForDiskOfferings(ListDiskOfferingsCmd cmd) {
          Pair<List<DiskOfferingJoinVO>, Integer> result = searchForDiskOfferingsInternal(cmd);
          ListResponse<DiskOfferingResponse> response = new ListResponse<DiskOfferingResponse>();
@@@ -1993,11 -2182,11 +2206,12 @@@
  
          Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm"));
          isAscending = (isAscending == null ? true : isAscending);
-         Filter searchFilter = new Filter(DiskOfferingJoinVO.class, "sortKey", isAscending, cmd.getStartIndex(), cmd.getPageSizeVal());
+         Filter searchFilter = new Filter(DiskOfferingJoinVO.class, "sortKey", isAscending, cmd.getStartIndex(),
+                 cmd.getPageSizeVal());
          SearchCriteria<DiskOfferingJoinVO> sc = _diskOfferingJoinDao.createSearchCriteria();
  
 -        Account account = UserContext.current().getCaller();
 +
 +        Account account = CallContext.current().getCallingAccount();
          Object name = cmd.getDiskOfferingName();
          Object id = cmd.getId();
          Object keyword = cmd.getKeyword();
@@@ -2108,10 -2303,11 +2328,11 @@@
          // root
          Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm"));
          isAscending = (isAscending == null ? true : isAscending);
-         Filter searchFilter = new Filter(ServiceOfferingJoinVO.class, "sortKey", isAscending, cmd.getStartIndex(), cmd.getPageSizeVal());
+         Filter searchFilter = new Filter(ServiceOfferingJoinVO.class, "sortKey", isAscending, cmd.getStartIndex(),
+                 cmd.getPageSizeVal());
          SearchCriteria<ServiceOfferingJoinVO> sc = _srvOfferingJoinDao.createSearchCriteria();
  
 -        Account caller = UserContext.current().getCaller();
 +        Account caller = CallContext.current().getCallingAccount();
          Object name = cmd.getServiceOfferingName();
          Object id = cmd.getId();
          Object keyword = cmd.getKeyword();
@@@ -2231,9 -2428,8 +2453,8 @@@
          return response;
      }
  
- 
      private Pair<List<DataCenterJoinVO>, Integer> listDataCentersInternal(ListZonesByCmd cmd) {
 -        Account account = UserContext.current().getCaller();
 +        Account account = CallContext.current().getCallingAccount();
          Long domainId = cmd.getDomainId();
          Long id = cmd.getId();
          String keyword = cmd.getKeyword();
@@@ -2243,9 -2439,9 +2464,9 @@@
          Filter searchFilter = new Filter(DataCenterJoinVO.class, null, false, cmd.getStartIndex(), cmd.getPageSizeVal());
          SearchCriteria<DataCenterJoinVO> sc = _dcJoinDao.createSearchCriteria();
  
-         if(networkType != null)
+         if (networkType != null)
 -            sc.addAnd("networkType", SearchCriteria.Op.EQ, networkType);
 -
 +          sc.addAnd("networkType", SearchCriteria.Op.EQ, networkType);
 +        
          if (id != null) {
              sc.addAnd("id", SearchCriteria.Op.EQ, id);
          } else if (name != null) {
@@@ -2402,6 -2610,322 +2635,323 @@@
      }
  
      @Override
+     public ListResponse<TemplateResponse> listTemplates(ListTemplatesCmd cmd) {
+         Pair<List<TemplateJoinVO>, Integer> result = searchForTemplatesInternal(cmd);
+         ListResponse<TemplateResponse> response = new ListResponse<TemplateResponse>();
+ 
+         List<TemplateResponse> templateResponses = ViewResponseHelper.createTemplateResponse(result.first().toArray(
+                 new TemplateJoinVO[result.first().size()]));
+         response.setResponses(templateResponses, result.second());
+         return response;
+     }
+ 
+     private Pair<List<TemplateJoinVO>, Integer> searchForTemplatesInternal(ListTemplatesCmd cmd) {
+         TemplateFilter templateFilter = TemplateFilter.valueOf(cmd.getTemplateFilter());
+         Long id = cmd.getId();
+         Map<String, String> tags = cmd.getTags();
 -        Account caller = UserContext.current().getCaller();
++        Account caller = CallContext.current().getCallingAccount();
+ 
+         boolean listAll = false;
+         if (templateFilter != null && templateFilter == TemplateFilter.all) {
+             if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
+                 throw new InvalidParameterValueException("Filter " + TemplateFilter.all
+                         + " can be specified by admin only");
+             }
+             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);
+         ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
+         List<Account> permittedAccounts = new ArrayList<Account>();
+         for (Long accountId : permittedAccountIds) {
+             permittedAccounts.add(_accountMgr.getAccount(accountId));
+         }
+ 
+         boolean showDomr = ((templateFilter != TemplateFilter.selfexecutable) && (templateFilter != TemplateFilter.featured));
+         HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor());
+ 
+         return searchForTemplatesInternal(id, cmd.getTemplateName(), cmd.getKeyword(), templateFilter, false, null,
+                 cmd.getPageSizeVal(), cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, showDomr,
+                 cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags);
+     }
+ 
+     private Pair<List<TemplateJoinVO>, Integer> searchForTemplatesInternal(Long templateId, String name,
+             String keyword, TemplateFilter templateFilter, boolean isIso, Boolean bootable, Long pageSize,
+             Long startIndex, Long zoneId, HypervisorType hyperType, boolean showDomr, boolean onlyReady,
+             List<Account> permittedAccounts, Account caller, ListProjectResourcesCriteria listProjectResourcesCriteria,
+             Map<String, String> tags) {
+         VMTemplateVO template = null;
+ 
+         Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm"));
+         isAscending = (isAscending == null ? true : isAscending);
+         Filter searchFilter = new Filter(TemplateJoinVO.class, "sortKey", isAscending, startIndex, pageSize);
+         SearchCriteria<TemplateJoinVO> sc = _templateJoinDao.createSearchCriteria();
+ 
+         // verify templateId parameter and specially handle it
+         if (templateId != null) {
+             template = _templateDao.findById(templateId);
+             if (template == null) {
+                 throw new InvalidParameterValueException("Please specify a valid template ID.");
+             }// If ISO requested then it should be ISO.
+             if (isIso && template.getFormat() != ImageFormat.ISO) {
+                 s_logger.error("Template Id " + templateId + " is not an ISO");
+                 InvalidParameterValueException ex = new InvalidParameterValueException(
+                         "Specified Template Id is not an ISO");
+                 ex.addProxyObject(template.getUuid(), "templateId");
+                 throw ex;
+             }// If ISO not requested then it shouldn't be an ISO.
+             if (!isIso && template.getFormat() == ImageFormat.ISO) {
+                 s_logger.error("Incorrect format of the template id " + templateId);
+                 InvalidParameterValueException ex = new InvalidParameterValueException("Incorrect format "
+                         + template.getFormat() + " of the specified template id");
+                 ex.addProxyObject(template.getUuid(), "templateId");
+                 throw ex;
+             }
+ 
+             // if template is not public, perform permission check here
+             if (!template.isPublicTemplate() && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
+                 Account owner = _accountMgr.getAccount(template.getAccountId());
+                 _accountMgr.checkAccess(caller, null, true, owner);
+             }
+ 
+             // if templateId is specified, then we will just use the id to
+             // search and ignore other query parameters
+             sc.addAnd("id", SearchCriteria.Op.EQ, templateId);
+         } else {
+ 
+             DomainVO domain = null;
+             if (!permittedAccounts.isEmpty()) {
+                 domain = _domainDao.findById(permittedAccounts.get(0).getDomainId());
+             } else {
+                 domain = _domainDao.findById(DomainVO.ROOT_DOMAIN);
+             }
+ 
+             List<HypervisorType> hypers = null;
+             if (!isIso) {
+                 hypers = _resourceMgr.listAvailHypervisorInZone(null, null);
+             }
+ 
+             // add criteria for project or not
+             if (listProjectResourcesCriteria == ListProjectResourcesCriteria.SkipProjectResources) {
+                 sc.addAnd("accountType", SearchCriteria.Op.NEQ, Account.ACCOUNT_TYPE_PROJECT);
+             } else if (listProjectResourcesCriteria == ListProjectResourcesCriteria.ListProjectResourcesOnly) {
+                 sc.addAnd("accountType", SearchCriteria.Op.EQ, Account.ACCOUNT_TYPE_PROJECT);
+             }
+ 
+             // add criteria for domain path in case of domain admin
+             if ((templateFilter == TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable)
+                     && (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN)) {
+                 sc.addAnd("domainPath", SearchCriteria.Op.LIKE, domain.getPath() + "%");
+             }
+ 
+             List<Long> relatedDomainIds = new ArrayList<Long>();
+             List<Long> permittedAccountIds = new ArrayList<Long>();
+             if (!permittedAccounts.isEmpty()) {
+                 for (Account account : permittedAccounts) {
+                     permittedAccountIds.add(account.getId());
+                     DomainVO accountDomain = _domainDao.findById(account.getDomainId());
+ 
+                     // get all parent domain ID's all the way till root domain
+                     DomainVO domainTreeNode = accountDomain;
+                     relatedDomainIds.add(domainTreeNode.getId());
+                     while (domainTreeNode.getParent() != null) {
+                         domainTreeNode = _domainDao.findById(domainTreeNode.getParent());
+                         relatedDomainIds.add(domainTreeNode.getId());
+                     }
+ 
+                     // get all child domain ID's
+                     if (_accountMgr.isAdmin(account.getType())) {
+                         List<DomainVO> allChildDomains = _domainDao.findAllChildren(accountDomain.getPath(),
+                                 accountDomain.getId());
+                         for (DomainVO childDomain : allChildDomains) {
+                             relatedDomainIds.add(childDomain.getId());
+                         }
+                     }
+                 }
+             }
+ 
+             if (!isIso) {
+                 // add hypervisor criteria for template case
+                 if (hypers != null && !hypers.isEmpty()) {
+                     String[] relatedHypers = new String[hypers.size()];
+                     for (int i = 0; i < hypers.size(); i++) {
+                         relatedHypers[i] = hypers.get(i).toString();
+                     }
+                     sc.addAnd("hypervisorType", SearchCriteria.Op.IN, relatedHypers);
+                 }
+             }
+ 
+             // control different template filters
+             if (templateFilter == TemplateFilter.featured || templateFilter == TemplateFilter.community) {
+                 sc.addAnd("publicTemplate", SearchCriteria.Op.EQ, true);
+                 if (templateFilter == TemplateFilter.featured) {
+                     sc.addAnd("featured", SearchCriteria.Op.EQ, true);
+                 } else {
+                     sc.addAnd("featured", SearchCriteria.Op.EQ, false);
+                 }
+                 if (!permittedAccounts.isEmpty()) {
+                     SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
+                     scc.addOr("domainId", SearchCriteria.Op.IN, relatedDomainIds.toArray());
+                     scc.addOr("domainId", SearchCriteria.Op.NULL);
+                     sc.addAnd("domainId", SearchCriteria.Op.SC, scc);
+                 }
+             } else if (templateFilter == TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable) {
+                 if (!permittedAccounts.isEmpty()) {
+                     sc.addAnd("accountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
+                 }
+             } else if (templateFilter == TemplateFilter.sharedexecutable || templateFilter == TemplateFilter.shared) {
+                 SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
+                 scc.addOr("accountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
+                 scc.addOr("sharedAccountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
+                 sc.addAnd("accountId", SearchCriteria.Op.SC, scc);
+             } else if (templateFilter == TemplateFilter.executable) {
+                 SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
+                 scc.addOr("publicTemplate", SearchCriteria.Op.EQ, true);
+                 if (!permittedAccounts.isEmpty()) {
+                     scc.addOr("accountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
+                 }
+                 sc.addAnd("publicTemplate", SearchCriteria.Op.SC, scc);
+             }
+ 
+             // add tags criteria
+             if (tags != null && !tags.isEmpty()) {
+                 SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
+                 int count = 0;
+                 for (String key : tags.keySet()) {
+                     SearchCriteria<TemplateJoinVO> scTag = _templateJoinDao.createSearchCriteria();
+                     scTag.addAnd("tagKey", SearchCriteria.Op.EQ, key);
+                     scTag.addAnd("tagValue", SearchCriteria.Op.EQ, tags.get(key));
+                     if (isIso) {
+                         scTag.addAnd("tagResourceType", SearchCriteria.Op.EQ, TaggedResourceType.ISO);
+                     } else {
+                         scTag.addAnd("tagResourceType", SearchCriteria.Op.EQ, TaggedResourceType.Template);
+                     }
+                     scc.addOr("tagKey", SearchCriteria.Op.SC, scTag);
+                     count++;
+                 }
+                 sc.addAnd("tagKey", SearchCriteria.Op.SC, scc);
+             }
+ 
+             // other criteria
+ 
+             if (keyword != null) {
+                 sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
+             } else if (name != null) {
+                 sc.addAnd("name", SearchCriteria.Op.EQ, name);
+             }
+ 
+             if (isIso) {
+                 sc.addAnd("format", SearchCriteria.Op.EQ, "ISO");
+ 
+             } else {
+                 sc.addAnd("format", SearchCriteria.Op.NEQ, "ISO");
+             }
+ 
+             if (!hyperType.equals(HypervisorType.None)) {
+                 sc.addAnd("hypervisorType", SearchCriteria.Op.EQ, hyperType);
+             }
+ 
+             if (bootable != null) {
+                 sc.addAnd("bootable", SearchCriteria.Op.EQ, bootable);
+             }
+ 
+             if (onlyReady) {
+                 SearchCriteria<TemplateJoinVO> readySc = _templateJoinDao.createSearchCriteria();
+                 readySc.addOr("state", SearchCriteria.Op.EQ, TemplateState.Ready);
+                 readySc.addOr("format", SearchCriteria.Op.EQ, ImageFormat.BAREMETAL);
+                 SearchCriteria<TemplateJoinVO> isoPerhostSc = _templateJoinDao.createSearchCriteria();
+                 isoPerhostSc.addAnd("format", SearchCriteria.Op.EQ, ImageFormat.ISO);
+                 isoPerhostSc.addAnd("templateType", SearchCriteria.Op.EQ, TemplateType.PERHOST);
+                 readySc.addOr("templateType", SearchCriteria.Op.SC, isoPerhostSc);
+                 sc.addAnd("state", SearchCriteria.Op.SC, readySc);
+             }
+ 
+             if (zoneId != null) {
+                 sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId);
+             }
+ 
+             if (!showDomr) {
+                 // excluding system template
+                 sc.addAnd("templateType", SearchCriteria.Op.NEQ, Storage.TemplateType.SYSTEM);
+             }
+         }
+ 
+         // don't return removed template, this should not be needed since we
+         // changed annotation for removed field in TemplateJoinVO.
+         // sc.addAnd("removed", SearchCriteria.Op.NULL);
+ 
+         // search unique templates and find details by Ids
+         Pair<List<TemplateJoinVO>, Integer> uniqueTmplPair = _templateJoinDao.searchAndCount(sc, searchFilter);
+         Integer count = uniqueTmplPair.second();
+         if (count.intValue() == 0) {
+             // empty result
+             return uniqueTmplPair;
+         }
+         List<TemplateJoinVO> uniqueTmpls = uniqueTmplPair.first();
+         Long[] vrIds = new Long[uniqueTmpls.size()];
+         int i = 0;
+         for (TemplateJoinVO v : uniqueTmpls) {
+             vrIds[i++] = v.getId();
+         }
+         List<TemplateJoinVO> vrs = _templateJoinDao.searchByIds(vrIds);
+         return new Pair<List<TemplateJoinVO>, Integer>(vrs, count);
+ 
+         // TODO: revisit the special logic for iso search in
+         // VMTemplateDaoImpl.searchForTemplates and understand why we need to
+         // specially handle ISO. The original logic is very twisted and no idea
+         // about what the code was doing.
+ 
+     }
+ 
+     @Override
+     public ListResponse<TemplateResponse> listIsos(ListIsosCmd cmd) {
+         Pair<List<TemplateJoinVO>, Integer> result = searchForIsosInternal(cmd);
+         ListResponse<TemplateResponse> response = new ListResponse<TemplateResponse>();
+ 
+         List<TemplateResponse> templateResponses = ViewResponseHelper.createIsoResponse(result.first().toArray(
+                 new TemplateJoinVO[result.first().size()]));
+         response.setResponses(templateResponses, result.second());
+         return response;
+     }
+ 
+     private Pair<List<TemplateJoinVO>, Integer> searchForIsosInternal(ListIsosCmd cmd) {
+         TemplateFilter isoFilter = TemplateFilter.valueOf(cmd.getIsoFilter());
+         Long id = cmd.getId();
+         Map<String, String> tags = cmd.getTags();
 -        Account caller = UserContext.current().getCaller();
++        Account caller = CallContext.current().getCallingAccount();
+ 
+         boolean listAll = false;
+         if (isoFilter != null && isoFilter == TemplateFilter.all) {
+             if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
+                 throw new InvalidParameterValueException("Filter " + TemplateFilter.all
+                         + " can be specified by admin only");
+             }
+             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);
+         ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
+         List<Account> permittedAccounts = new ArrayList<Account>();
+         for (Long accountId : permittedAccountIds) {
+             permittedAccounts.add(_accountMgr.getAccount(accountId));
+         }
+ 
+         HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor());
+ 
+         return searchForTemplatesInternal(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
      public ListResponse<AffinityGroupResponse> listAffinityGroups(Long affinityGroupId, String affinityGroupName,
              String affinityGroupType, Long vmId, String accountName, Long domainId, boolean isRecursive,
              boolean listAll, Long startIndex, Long pageSize) {
@@@ -2534,13 -3057,12 +3085,12 @@@
  
              return volumeDetailResponseList;
  
 -        } else {
 +        }  else {
  
- 
              List<NicDetailVO> nicDetailList;
-             if(key == null){
+             if (key == null) {
                  nicDetailList = _nicDetailDao.findDetails(id);
-             }else {
+             } else {
                  NicDetailVO nicDetail = _nicDetailDao.findDetail(id, key);
                  nicDetailList = new LinkedList<NicDetailVO>();
                  nicDetailList.add(nicDetail);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/api/query/ViewResponseHelper.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/api/query/ViewResponseHelper.java
index 3daa1c1,b98cea3..0e605a5
--- a/server/src/com/cloud/api/query/ViewResponseHelper.java
+++ b/server/src/com/cloud/api/query/ViewResponseHelper.java
@@@ -33,7 -48,8 +33,8 @@@ import org.apache.cloudstack.api.respon
  import org.apache.cloudstack.api.response.EventResponse;
  import org.apache.cloudstack.api.response.HostForMigrationResponse;
  import org.apache.cloudstack.api.response.HostResponse;
 -import org.apache.cloudstack.api.response.InstanceGroupResponse;
+ import org.apache.cloudstack.api.response.ImageStoreResponse;
 +import org.apache.cloudstack.api.response.InstanceGroupResponse;
  import org.apache.cloudstack.api.response.ProjectAccountResponse;
  import org.apache.cloudstack.api.response.ProjectInvitationResponse;
  import org.apache.cloudstack.api.response.ProjectResponse;
@@@ -45,29 -62,15 +47,31 @@@ import org.apache.cloudstack.api.respon
  import org.apache.cloudstack.api.response.UserVmResponse;
  import org.apache.cloudstack.api.response.VolumeResponse;
  import org.apache.cloudstack.api.response.ZoneResponse;
 -import org.apache.log4j.Logger;
 -
 +import org.apache.cloudstack.context.CallContext;
  
 +import com.cloud.api.ApiDBUtils;
 +import com.cloud.api.query.vo.AccountJoinVO;
 +import com.cloud.api.query.vo.AffinityGroupJoinVO;
 +import com.cloud.api.query.vo.AsyncJobJoinVO;
 +import com.cloud.api.query.vo.DataCenterJoinVO;
 +import com.cloud.api.query.vo.DiskOfferingJoinVO;
 +import com.cloud.api.query.vo.DomainRouterJoinVO;
 +import com.cloud.api.query.vo.EventJoinVO;
 +import com.cloud.api.query.vo.HostJoinVO;
+ import com.cloud.api.query.vo.ImageStoreJoinVO;
 +import com.cloud.api.query.vo.InstanceGroupJoinVO;
 +import com.cloud.api.query.vo.ProjectAccountJoinVO;
 +import com.cloud.api.query.vo.ProjectInvitationJoinVO;
 +import com.cloud.api.query.vo.ProjectJoinVO;
 +import com.cloud.api.query.vo.ResourceTagJoinVO;
 +import com.cloud.api.query.vo.SecurityGroupJoinVO;
 +import com.cloud.api.query.vo.ServiceOfferingJoinVO;
 +import com.cloud.api.query.vo.StoragePoolJoinVO;
+ import com.cloud.api.query.vo.TemplateJoinVO;
 -import java.util.ArrayList;
 -import java.util.EnumSet;
 -import java.util.Hashtable;
 -import java.util.List;
 +import com.cloud.api.query.vo.UserAccountJoinVO;
 +import com.cloud.api.query.vo.UserVmJoinVO;
 +import com.cloud.api.query.vo.VolumeJoinVO;
 +import com.cloud.user.Account;
  
  /**
   * Helper class to generate response from DB view VO objects.


Mime
View raw message