incubator-cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From kis...@apache.org
Subject [1/2] CLOUDSTACK-786, CLOUDSTACK-1014: Moved usage APIs to cloud-api. Removed ManagementServerExt. Usage API related implementation is added to UsageServiceImpl
Date Tue, 05 Feb 2013 11:25:15 GMT
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/fc0bf21a/server/src/com/cloud/api/commands/GetUsageRecordsCmd.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/commands/GetUsageRecordsCmd.java b/server/src/com/cloud/api/commands/GetUsageRecordsCmd.java
deleted file mode 100644
index 7f96b0c..0000000
--- a/server/src/com/cloud/api/commands/GetUsageRecordsCmd.java
+++ /dev/null
@@ -1,370 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License.  You may obtain a copy of the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied.  See the License for the
-// specific language governing permissions and limitations
-// under the License.
-package com.cloud.api.commands;
-
-import java.text.DecimalFormat;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.List;
-import java.util.TimeZone;
-
-import org.apache.cloudstack.api.response.AccountResponse;
-import org.apache.cloudstack.api.response.DomainResponse;
-import org.apache.cloudstack.api.response.ProjectResponse;
-import org.apache.log4j.Logger;
-
-import org.apache.cloudstack.api.ApiConstants;
-import com.cloud.api.ApiDBUtils;
-import com.cloud.dc.DataCenter;
-import com.cloud.domain.Domain;
-
-import org.apache.cloudstack.api.BaseListCmd;
-import org.apache.cloudstack.api.APICommand;
-import org.apache.cloudstack.api.Parameter;
-import org.apache.cloudstack.api.response.ListResponse;
-import com.cloud.projects.Project;
-import com.cloud.server.ManagementServerExt;
-import org.apache.cloudstack.api.response.UsageRecordResponse;
-import com.cloud.storage.VMTemplateVO;
-import com.cloud.usage.UsageTypes;
-import com.cloud.usage.UsageVO;
-import com.cloud.user.Account;
-import com.cloud.uuididentity.dao.IdentityDao;
-import com.cloud.uuididentity.dao.IdentityDaoImpl;
-import com.cloud.vm.VMInstanceVO;
-
-@APICommand(name = "listUsageRecords", description="Lists usage records for accounts", responseObject=UsageRecordResponse.class)
-public class GetUsageRecordsCmd extends BaseListCmd {
-    public static final Logger s_logger = Logger.getLogger(GetUsageRecordsCmd.class.getName());
-
-    private static final String s_name = "listusagerecordsresponse";
-
-    /////////////////////////////////////////////////////
-    //////////////// API parameters /////////////////////
-    /////////////////////////////////////////////////////
-
-    @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="List usage records for the specified user.")
-    private String accountName;
-
-    @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class,
-            description="List usage records for the specified domain.")
-    private Long domainId;
-
-    @Parameter(name=ApiConstants.END_DATE, type=CommandType.DATE, required=true, description="End date range for usage record query. Use yyyy-MM-dd as the date format, e.g. startDate=2009-06-03.")
-    private Date endDate;
-
-    @Parameter(name=ApiConstants.START_DATE, type=CommandType.DATE, required=true, description="Start date range for usage record query. Use yyyy-MM-dd as the date format, e.g. startDate=2009-06-01.")
-    private Date startDate;
-
-    @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.UUID, entityType = AccountResponse.class,
-            description="List usage records for the specified account")
-    private Long accountId;
-
-    @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class,
-            description="List usage records for specified project")
-    private Long projectId;
-
-    @Parameter(name=ApiConstants.TYPE, type=CommandType.LONG, description="List usage records for the specified usage type")
-    private Long usageType;
-
-    /////////////////////////////////////////////////////
-    /////////////////// Accessors ///////////////////////
-    /////////////////////////////////////////////////////
-
-    public String getAccountName() {
-        return accountName;
-    }
-
-    public Long getDomainId() {
-        return domainId;
-    }
-
-    public Date getEndDate() {
-        return endDate;
-    }
-
-    public Date getStartDate() {
-        return startDate;
-    }
-
-    public Long getAccountId() {
-        return accountId;
-    }
-
-    public Long getUsageType() {
-        return usageType;
-    }
-
-    public Long getProjectId() {
-        return projectId;
-    }
-
-    /////////////////////////////////////////////////////
-    ///////////////  Misc parameters  ///////////////////
-    /////////////////////////////////////////////////////
-
-    private TimeZone usageTimezone;
-
-    public TimeZone getUsageTimezone() {
-        return usageTimezone;
-    }
-
-    public void setUsageTimezone(TimeZone tz) {
-        this.usageTimezone = tz;
-    }
-
-    /////////////////////////////////////////////////////
-    /////////////// API Implementation///////////////////
-    /////////////////////////////////////////////////////
-
-    @Override
-    public String getCommandName() {
-        return s_name;
-    }
-
-    public String getDateStringInternal(Date inputDate) {
-        if (inputDate == null) return null;
-
-        TimeZone tz = getUsageTimezone();
-        Calendar cal = Calendar.getInstance(tz);
-        cal.setTime(inputDate);
-
-        StringBuffer sb = new StringBuffer();
-        sb.append(cal.get(Calendar.YEAR)+"-");
-
-        int month = cal.get(Calendar.MONTH) + 1;
-        if (month < 10) {
-            sb.append("0" + month + "-");
-        } else {
-            sb.append(month+"-");
-        }
-
-        int day = cal.get(Calendar.DAY_OF_MONTH);
-        if (day < 10) {
-            sb.append("0" + day);
-        } else {
-            sb.append(""+day);
-        }
-
-        sb.append("'T'");
-
-        int hour = cal.get(Calendar.HOUR_OF_DAY);
-        if (hour < 10) {
-            sb.append("0" + hour + ":");
-        } else {
-            sb.append(hour+":");
-        }
-
-        int minute = cal.get(Calendar.MINUTE);
-        if (minute < 10) {
-            sb.append("0" + minute + ":");
-        } else {
-            sb.append(minute+":");
-        }
-
-        int seconds = cal.get(Calendar.SECOND);
-        if (seconds < 10) {
-            sb.append("0" + seconds);
-        } else {
-            sb.append(""+seconds);
-        }
-
-        double offset = cal.get(Calendar.ZONE_OFFSET);
-        if (tz.inDaylightTime(inputDate)) {
-            offset += (1.0*tz.getDSTSavings()); // add the timezone's DST value (typically 1 hour expressed in milliseconds)
-        }
-
-        offset = offset / (1000d*60d*60d);
-        int hourOffset = (int)offset;
-        double decimalVal = Math.abs(offset) - Math.abs(hourOffset);
-        int minuteOffset = (int)(decimalVal * 60);
-
-        if (hourOffset < 0) {
-            if (hourOffset > -10) {
-                sb.append("-0"+Math.abs(hourOffset));
-            } else {
-                sb.append("-"+Math.abs(hourOffset));
-            }
-        } else {
-            if (hourOffset < 10) {
-                sb.append("+0" + hourOffset);
-            } else {
-                sb.append("+" + hourOffset);
-            }
-        }
-
-        sb.append(":");
-
-        if (minuteOffset == 0) {
-            sb.append("00");
-        } else if (minuteOffset < 10) {
-            sb.append("0" + minuteOffset);
-        } else {
-            sb.append("" + minuteOffset);
-        }
-
-        return sb.toString();
-    }
-
-    @Override
-    public void execute(){
-        ManagementServerExt _mgrExt = (ManagementServerExt)_mgr;
-        List<UsageVO> usageRecords = _mgrExt.getUsageRecords(this);
-        IdentityDao identityDao = new IdentityDaoImpl();
-        ListResponse<UsageRecordResponse> response = new ListResponse<UsageRecordResponse>();
-        List<UsageRecordResponse> usageResponses = new ArrayList<UsageRecordResponse>();
-        for (Object usageRecordGeneric : usageRecords) {
-            UsageRecordResponse usageRecResponse = new UsageRecordResponse();
-            if (usageRecordGeneric instanceof UsageVO) {
-                UsageVO usageRecord = (UsageVO)usageRecordGeneric;
-
-                Account account = ApiDBUtils.findAccountByIdIncludingRemoved(usageRecord.getAccountId());
-                if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
-                    //find the project
-                    Project project = ApiDBUtils.findProjectByProjectAccountIdIncludingRemoved(account.getId());
-                    usageRecResponse.setProjectId(project.getUuid());
-                    usageRecResponse.setProjectName(project.getName());
-                } else {
-                    usageRecResponse.setAccountId(account.getUuid());
-                    usageRecResponse.setAccountName(account.getAccountName());
-                }
-
-                Domain domain = ApiDBUtils.findDomainById(usageRecord.getDomainId());
-                if (domain != null) {
-                    usageRecResponse.setDomainId(domain.getUuid());
-                }
-
-                if (usageRecord.getZoneId() != null) {
-                    DataCenter zone = ApiDBUtils.findZoneById(usageRecord.getZoneId());
-                    if (zone != null) {
-                        usageRecResponse.setZoneId(zone.getUuid());
-                    }
-                }
-                usageRecResponse.setDescription(usageRecord.getDescription());
-                usageRecResponse.setUsage(usageRecord.getUsageDisplay());
-                usageRecResponse.setUsageType(usageRecord.getUsageType());
-                if (usageRecord.getVmInstanceId() != null) {
-                    VMInstanceVO vm = ApiDBUtils.findVMInstanceById(usageRecord.getVmInstanceId());
-                    if (vm != null) {
-                        usageRecResponse.setVirtualMachineId(vm.getUuid());
-                    }
-                }
-                usageRecResponse.setVmName(usageRecord.getVmName());
-                if (usageRecord.getTemplateId() != null) {
-                    VMTemplateVO template = ApiDBUtils.findTemplateById(usageRecord.getTemplateId());
-                    if (template != null) {
-                        usageRecResponse.setTemplateId(template.getUuid());
-                    }
-                }
-
-                if(usageRecord.getUsageType() == UsageTypes.RUNNING_VM || usageRecord.getUsageType() == UsageTypes.ALLOCATED_VM){
-                	//Service Offering Id
-                	usageRecResponse.setOfferingId(identityDao.getIdentityUuid("disk_offering", usageRecord.getOfferingId().toString()));
-                	//VM Instance ID
-                	usageRecResponse.setUsageId(identityDao.getIdentityUuid("vm_instance", usageRecord.getUsageId().toString()));
-                	//Hypervisor Type
-                	usageRecResponse.setType(usageRecord.getType());
-
-                } else if(usageRecord.getUsageType() == UsageTypes.IP_ADDRESS){
-                	//isSourceNAT
-                    usageRecResponse.setSourceNat((usageRecord.getType().equals("SourceNat"))?true:false);
-                    //isSystem
-                    usageRecResponse.setSystem((usageRecord.getSize() == 1)?true:false);
-                    //IP Address ID
-                    usageRecResponse.setUsageId(identityDao.getIdentityUuid("user_ip_address", usageRecord.getUsageId().toString()));
-
-                } else if(usageRecord.getUsageType() == UsageTypes.NETWORK_BYTES_SENT || usageRecord.getUsageType() == UsageTypes.NETWORK_BYTES_RECEIVED){
-                	//Device Type
-                	usageRecResponse.setType(usageRecord.getType());
-                	if(usageRecord.getType().equals("DomainRouter")){
-                        //Domain Router Id
-                        usageRecResponse.setUsageId(identityDao.getIdentityUuid("vm_instance", usageRecord.getUsageId().toString()));
-                	} else {
-                		//External Device Host Id
-                		usageRecResponse.setUsageId(identityDao.getIdentityUuid("host", usageRecord.getUsageId().toString()));
-                	}
-                    //Network ID
-                    usageRecResponse.setNetworkId(identityDao.getIdentityUuid("networks", usageRecord.getNetworkId().toString()));
-
-                } else if(usageRecord.getUsageType() == UsageTypes.VOLUME){
-                    //Volume ID
-                    usageRecResponse.setUsageId(identityDao.getIdentityUuid("volumes", usageRecord.getUsageId().toString()));
-                    //Volume Size
-                    usageRecResponse.setSize(usageRecord.getSize());
-                	//Disk Offering Id
-                    if(usageRecord.getOfferingId() != null){
-                    	usageRecResponse.setOfferingId(identityDao.getIdentityUuid("disk_offering", usageRecord.getOfferingId().toString()));
-                    }
-
-                } else if(usageRecord.getUsageType() == UsageTypes.TEMPLATE || usageRecord.getUsageType() == UsageTypes.ISO){
-                    //Template/ISO ID
-                    usageRecResponse.setUsageId(identityDao.getIdentityUuid("vm_template", usageRecord.getUsageId().toString()));
-                    //Template/ISO Size
-                    usageRecResponse.setSize(usageRecord.getSize());
-
-                } else if(usageRecord.getUsageType() == UsageTypes.SNAPSHOT){
-                    //Snapshot ID
-                    usageRecResponse.setUsageId(identityDao.getIdentityUuid("snapshots", usageRecord.getUsageId().toString()));
-                    //Snapshot Size
-                    usageRecResponse.setSize(usageRecord.getSize());
-
-                } else if(usageRecord.getUsageType() == UsageTypes.LOAD_BALANCER_POLICY){
-                    //Load Balancer Policy ID
-                    usageRecResponse.setUsageId(usageRecord.getUsageId().toString());
-
-                } else if(usageRecord.getUsageType() == UsageTypes.PORT_FORWARDING_RULE){
-                    //Port Forwarding Rule ID
-                    usageRecResponse.setUsageId(usageRecord.getUsageId().toString());
-
-                } else if(usageRecord.getUsageType() == UsageTypes.NETWORK_OFFERING){
-                	//Network Offering Id
-                	usageRecResponse.setOfferingId(identityDao.getIdentityUuid("network_offerings", usageRecord.getOfferingId().toString()));
-                	//is Default
-                	usageRecResponse.setDefault((usageRecord.getUsageId() == 1)? true:false);
-
-                } else if(usageRecord.getUsageType() == UsageTypes.VPN_USERS){
-                    //VPN User ID
-                    usageRecResponse.setUsageId(usageRecord.getUsageId().toString());
-
-                } else if(usageRecord.getUsageType() == UsageTypes.SECURITY_GROUP){
-                	//Security Group Id
-                	usageRecResponse.setUsageId(identityDao.getIdentityUuid("security_group", usageRecord.getUsageId().toString()));
-                }
-
-                if (usageRecord.getRawUsage() != null) {
-                    DecimalFormat decimalFormat = new DecimalFormat("###########.######");
-                    usageRecResponse.setRawUsage(decimalFormat.format(usageRecord.getRawUsage()));
-                }
-
-                if (usageRecord.getStartDate() != null) {
-                    usageRecResponse.setStartDate(getDateStringInternal(usageRecord.getStartDate()));
-                }
-                if (usageRecord.getEndDate() != null) {
-                    usageRecResponse.setEndDate(getDateStringInternal(usageRecord.getEndDate()));
-                }
-            }
-
-            usageRecResponse.setObjectName("usagerecord");
-            usageResponses.add(usageRecResponse);
-        }
-
-        response.setResponses(usageResponses);
-        response.setResponseName(getCommandName());
-        this.setResponseObject(response);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/fc0bf21a/server/src/com/cloud/api/commands/ListTrafficMonitorsCmd.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/commands/ListTrafficMonitorsCmd.java b/server/src/com/cloud/api/commands/ListTrafficMonitorsCmd.java
deleted file mode 100644
index 645bf3b..0000000
--- a/server/src/com/cloud/api/commands/ListTrafficMonitorsCmd.java
+++ /dev/null
@@ -1,86 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License.  You may obtain a copy of the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied.  See the License for the
-// specific language governing permissions and limitations
-// under the License.
-package com.cloud.api.commands;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.inject.Inject;
-
-import org.apache.cloudstack.api.APICommand;
-import org.apache.cloudstack.api.ApiConstants;
-import org.apache.cloudstack.api.BaseListCmd;
-import org.apache.cloudstack.api.Parameter;
-import org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd;
-import org.apache.cloudstack.api.response.ListResponse;
-import org.apache.cloudstack.api.response.TrafficMonitorResponse;
-import org.apache.cloudstack.api.response.ZoneResponse;
-import org.apache.log4j.Logger;
-
-import com.cloud.host.Host;
-import com.cloud.network.NetworkUsageManager;
-
-
-@APICommand(name = "listTrafficMonitors", description="List traffic monitor Hosts.", responseObject = TrafficMonitorResponse.class)
-public class ListTrafficMonitorsCmd extends BaseListCmd {
-    public static final Logger s_logger = Logger.getLogger(ListServiceOfferingsCmd.class.getName());
-    private static final String s_name = "listtrafficmonitorsresponse";
-
-    @Inject NetworkUsageManager networkUsageMgr;
-    /////////////////////////////////////////////////////
-    //////////////// API parameters /////////////////////
-    /////////////////////////////////////////////////////
-
-    @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class,
-            required = true, description="zone Id")
-    private long zoneId;
-
-    /////////////////////////////////////////////////////
-    /////////////////// Accessors ///////////////////////
-    /////////////////////////////////////////////////////
-
-    public long getZoneId() {
-        return zoneId;
-    }
-
-    /////////////////////////////////////////////////////
-    /////////////// API Implementation///////////////////
-    /////////////////////////////////////////////////////
-
-    @Override
-    public String getCommandName() {
-        return s_name;
-    }
-
-    @Override
-    public void execute(){
-        List<? extends Host> trafficMonitors = networkUsageMgr.listTrafficMonitors(this);
-
-        ListResponse<TrafficMonitorResponse> listResponse = new ListResponse<TrafficMonitorResponse>();
-        List<TrafficMonitorResponse> responses = new ArrayList<TrafficMonitorResponse>();
-        for (Host trafficMonitor : trafficMonitors) {
-            TrafficMonitorResponse response = networkUsageMgr.getApiResponse(trafficMonitor);
-            response.setObjectName("trafficmonitor");
-            response.setResponseName(getCommandName());
-            responses.add(response);
-        }
-
-        listResponse.setResponses(responses);
-        listResponse.setResponseName(getCommandName());
-        this.setResponseObject(listResponse);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/fc0bf21a/server/src/com/cloud/api/commands/ListUsageTypesCmd.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/commands/ListUsageTypesCmd.java b/server/src/com/cloud/api/commands/ListUsageTypesCmd.java
deleted file mode 100644
index dfa5dc1..0000000
--- a/server/src/com/cloud/api/commands/ListUsageTypesCmd.java
+++ /dev/null
@@ -1,53 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License.  You may obtain a copy of the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied.  See the License for the
-// specific language governing permissions and limitations
-// under the License.
-package com.cloud.api.commands;
-
-import java.util.List;
-
-import org.apache.cloudstack.api.APICommand;
-import org.apache.log4j.Logger;
-
-import org.apache.cloudstack.api.BaseCmd;
-import org.apache.cloudstack.api.response.ListResponse;
-import com.cloud.server.ManagementServerExt;
-import org.apache.cloudstack.api.response.UsageTypeResponse;
-import com.cloud.user.Account;
-
-@APICommand(name = "listUsageTypes", description = "List Usage Types", responseObject = UsageTypeResponse.class)
-public class ListUsageTypesCmd extends BaseCmd {
-    public static final Logger s_logger = Logger.getLogger(ListUsageTypesCmd.class.getName());
-    private static final String s_name = "listusagetypesresponse";
-
-    @Override
-    public String getCommandName() {
-        return s_name;
-    }
-
-    public long getEntityOwnerId() {
-        return Account.ACCOUNT_ID_SYSTEM;
-    }
-
-    @Override
-    public void execute() {
-    	ManagementServerExt _mgrExt = (ManagementServerExt)_mgr;
-        List<UsageTypeResponse> result = _mgrExt.listUsageTypes();
-        ListResponse<UsageTypeResponse> response = new ListResponse<UsageTypeResponse>();
-        response.setResponses(result);
-        response.setResponseName(getCommandName());
-        this.setResponseObject(response);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/fc0bf21a/server/src/com/cloud/dao/EntityManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/dao/EntityManagerImpl.java b/server/src/com/cloud/dao/EntityManagerImpl.java
index a768588..a3ab5b3 100644
--- a/server/src/com/cloud/dao/EntityManagerImpl.java
+++ b/server/src/com/cloud/dao/EntityManagerImpl.java
@@ -27,7 +27,6 @@ import org.springframework.stereotype.Component;
 
 import net.sf.ehcache.Cache;
 
-import com.cloud.utils.component.Manager;
 import com.cloud.utils.component.ManagerBase;
 import com.cloud.utils.db.GenericDao;
 import com.cloud.utils.db.GenericDaoBase;
@@ -47,6 +46,12 @@ public class EntityManagerImpl extends ManagerBase implements EntityManager {
         GenericDao<? extends T, K> dao = (GenericDao<? extends T, K>)GenericDaoBase.getDao(entityType);
         return dao.findById(id);
     }
+    
+    @Override
+    public <T, K extends Serializable> T findByIdIncludingRemoved(Class<T> entityType, K id) {
+        GenericDao<? extends T, K> dao = (GenericDao<? extends T, K>)GenericDaoBase.getDao(entityType);
+        return dao.findByIdIncludingRemoved(id);
+    }
 
     @Override
     public <T> T findByUuid(Class<T> entityType, String uuid) {

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/fc0bf21a/server/src/com/cloud/network/NetworkUsageManager.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/NetworkUsageManager.java b/server/src/com/cloud/network/NetworkUsageManager.java
index 1f0638b..86bec55 100644
--- a/server/src/com/cloud/network/NetworkUsageManager.java
+++ b/server/src/com/cloud/network/NetworkUsageManager.java
@@ -18,26 +18,12 @@ package com.cloud.network;
 
 import java.util.List;
 
-import com.cloud.api.commands.AddTrafficMonitorCmd;
-import com.cloud.api.commands.DeleteTrafficMonitorCmd;
-import com.cloud.api.commands.ListTrafficMonitorsCmd;
-import com.cloud.host.Host;
-import com.cloud.host.HostVO;
 import com.cloud.network.dao.IPAddressVO;
 
-import org.apache.cloudstack.api.response.TrafficMonitorResponse;
 import com.cloud.utils.component.Manager;
 
 public interface NetworkUsageManager extends Manager {
 
-    Host addTrafficMonitor(AddTrafficMonitorCmd cmd);
-
-    TrafficMonitorResponse getApiResponse(Host trafficMonitor);
-
-    boolean deleteTrafficMonitor(DeleteTrafficMonitorCmd cmd);
-
-    List<HostVO> listTrafficMonitors(ListTrafficMonitorsCmd cmd);
-
     List<IPAddressVO> listAllocatedDirectIps(long zoneId);
 		
 }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/fc0bf21a/server/src/com/cloud/network/NetworkUsageManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/NetworkUsageManagerImpl.java b/server/src/com/cloud/network/NetworkUsageManagerImpl.java
index e148e2c..80f898b 100755
--- a/server/src/com/cloud/network/NetworkUsageManagerImpl.java
+++ b/server/src/com/cloud/network/NetworkUsageManagerImpl.java
@@ -44,9 +44,6 @@ import com.cloud.agent.api.RecurringNetworkUsageCommand;
 import com.cloud.agent.api.StartupCommand;
 import com.cloud.agent.api.StartupTrafficMonitorCommand;
 import com.cloud.agent.manager.Commands;
-import com.cloud.api.commands.AddTrafficMonitorCmd;
-import com.cloud.api.commands.DeleteTrafficMonitorCmd;
-import com.cloud.api.commands.ListTrafficMonitorsCmd;
 import com.cloud.configuration.Config;
 import com.cloud.configuration.dao.ConfigurationDao;
 import com.cloud.dc.DataCenterVO;
@@ -71,6 +68,10 @@ import com.cloud.resource.ResourceManager;
 import com.cloud.resource.ResourceStateAdapter;
 import com.cloud.resource.ServerResource;
 import com.cloud.resource.UnableDeleteHostException;
+
+import org.apache.cloudstack.api.command.admin.usage.AddTrafficMonitorCmd;
+import org.apache.cloudstack.api.command.admin.usage.DeleteTrafficMonitorCmd;
+import org.apache.cloudstack.api.command.admin.usage.ListTrafficMonitorsCmd;
 import org.apache.cloudstack.api.response.TrafficMonitorResponse;
 import com.cloud.usage.UsageIPAddressVO;
 import com.cloud.user.AccountManager;
@@ -93,7 +94,7 @@ import com.cloud.utils.net.MacAddress;
 
 @Component
 @Local(value = {NetworkUsageManager.class})
-public class NetworkUsageManagerImpl extends ManagerBase implements NetworkUsageManager, ResourceStateAdapter {
+public class NetworkUsageManagerImpl extends ManagerBase implements NetworkUsageService, NetworkUsageManager, ResourceStateAdapter {
     public enum NetworkUsageResourceName {
         TrafficSentinel;
     }
@@ -212,17 +213,6 @@ public class NetworkUsageManagerImpl extends ManagerBase implements NetworkUsage
     }
 
     @Override
-    public TrafficMonitorResponse getApiResponse(Host trafficMonitor) {
-        Map<String, String> tmDetails = _detailsDao.findDetails(trafficMonitor.getId());
-        TrafficMonitorResponse response = new TrafficMonitorResponse();
-        response.setId(trafficMonitor.getUuid());
-        response.setIpAddress(trafficMonitor.getPrivateIpAddress());
-        response.setNumRetries(tmDetails.get("numRetries"));
-        response.setTimeout(tmDetails.get("timeout"));
-        return response;
-    }
-
-    @Override
     public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
         AllocatedIpSearch = _ipAddressDao.createSearchBuilder();
         AllocatedIpSearch.and("allocated", AllocatedIpSearch.entity().getAllocatedTime(), Op.NNULL);

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/fc0bf21a/server/src/com/cloud/server/ManagementServerExt.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/server/ManagementServerExt.java b/server/src/com/cloud/server/ManagementServerExt.java
deleted file mode 100644
index 4e506a3..0000000
--- a/server/src/com/cloud/server/ManagementServerExt.java
+++ /dev/null
@@ -1,63 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License.  You may obtain a copy of the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied.  See the License for the
-// specific language governing permissions and limitations
-// under the License.
-package com.cloud.server;
-
-import java.util.List;
-import java.util.TimeZone;
-
-import com.cloud.api.commands.GenerateUsageRecordsCmd;
-import com.cloud.api.commands.GetUsageRecordsCmd;
-import org.apache.cloudstack.api.response.UsageTypeResponse;
-import com.cloud.usage.UsageVO;
-public interface ManagementServerExt extends ManagementServer {
-    /**
-     * Generate Billing Records from the last time it was generated to the
-     * time specified.
-     * 
-     * @param cmd the command wrapping the generate parameters
-     *   - userId unique id of the user, pass in -1 to generate billing records
-     *            for all users
-     *   - startDate
-     *   - endDate inclusive.  If date specified is greater than the current time, the
-     *             system will use the current time.
-     */
-    boolean generateUsageRecords(GenerateUsageRecordsCmd cmd);
-    
-    /**
-     * Retrieves all Usage Records generated between the start and end date specified
-     * 
-     * @param userId unique id of the user, pass in -1 to retrieve billing records
-     *        for all users
-     * @param startDate inclusive.
-     * @param endDate inclusive.  If date specified is greater than the current time, the
-     *                system will use the current time.
-     * @param page The page of usage records to see (500 results are returned at a time, if
-     *             more than 500 records exist then additional results can be retrieved by
-     *             the appropriate page number)
-     * @return a list of usage records
-     */
-    List<UsageVO> getUsageRecords(GetUsageRecordsCmd cmd);
-
-    /**
-     * Retrieves the timezone used for usage aggregation.  One day is represented as midnight to 11:59:59pm
-     * in the given time zone
-     * @return the timezone specified by the config value usage.aggregation.timezone, or GMT if null
-     */
-    TimeZone getUsageTimezone();
-
-	List<UsageTypeResponse> listUsageTypes();
-}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/fc0bf21a/server/src/com/cloud/server/ManagementServerExtImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/server/ManagementServerExtImpl.java b/server/src/com/cloud/server/ManagementServerExtImpl.java
deleted file mode 100644
index 52ad3df..0000000
--- a/server/src/com/cloud/server/ManagementServerExtImpl.java
+++ /dev/null
@@ -1,254 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License.  You may obtain a copy of the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied.  See the License for the
-// specific language governing permissions and limitations
-// under the License.
-package com.cloud.server;
-
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-import java.util.TimeZone;
-
-import javax.inject.Inject;
-import javax.naming.ConfigurationException;
-
-import com.cloud.api.commands.GenerateUsageRecordsCmd;
-import com.cloud.api.commands.GetUsageRecordsCmd;
-import com.cloud.domain.dao.DomainDao;
-import com.cloud.exception.InvalidParameterValueException;
-import com.cloud.exception.PermissionDeniedException;
-import com.cloud.projects.Project;
-import org.apache.cloudstack.api.response.UsageTypeResponse;
-
-import com.cloud.usage.UsageJobVO;
-import com.cloud.usage.UsageTypes;
-import com.cloud.usage.UsageVO;
-import com.cloud.usage.dao.UsageDao;
-import com.cloud.usage.dao.UsageJobDao;
-import com.cloud.user.Account;
-import com.cloud.user.AccountVO;
-import com.cloud.user.UserContext;
-import com.cloud.user.dao.AccountDao;
-import com.cloud.utils.db.Filter;
-import com.cloud.utils.db.SearchCriteria;
-import com.cloud.utils.db.Transaction;
-
-public class ManagementServerExtImpl extends ManagementServerImpl implements ManagementServerExt {
-    @Inject private AccountDao _accountDao;
-    @Inject private DomainDao _domainDao;
-    @Inject private UsageDao _usageDao;
-    @Inject private UsageJobDao _usageJobDao;
-    private TimeZone _usageTimezone;
-
-    public ManagementServerExtImpl() {
-    }
-    
-    @Override
-    public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
-    	super.configure(name,  params);
-        Map<String, String> configs = getConfigs();
-        String timeZoneStr = configs.get("usage.aggregation.timezone");
-        if (timeZoneStr == null) {
-           timeZoneStr = "GMT";
-        }
-        _usageTimezone = TimeZone.getTimeZone(timeZoneStr);
-        return true;
-    }
-
-    @Override
-    public boolean generateUsageRecords(GenerateUsageRecordsCmd cmd) {
-        Transaction txn = Transaction.open(Transaction.USAGE_DB);
-        try {
-            UsageJobVO immediateJob = _usageJobDao.getNextImmediateJob();
-            if (immediateJob == null) {
-                UsageJobVO job = _usageJobDao.getLastJob();
-
-                String host = null;
-                int pid = 0;
-                if (job != null) {
-                    host = job.getHost();
-                    pid = ((job.getPid() == null) ? 0 : job.getPid().intValue());
-                }
-                _usageJobDao.createNewJob(host, pid, UsageJobVO.JOB_TYPE_SINGLE);
-            }
-        } finally {
-            txn.close();
-
-            // switch back to VMOPS_DB
-            Transaction swap = Transaction.open(Transaction.CLOUD_DB);
-            swap.close();
-        }
-        return true;
-    }
-
-    @Override
-    public List<UsageVO> getUsageRecords(GetUsageRecordsCmd cmd) {
-        Long accountId = cmd.getAccountId();
-        Long domainId = cmd.getDomainId();
-        String accountName = cmd.getAccountName();
-        Account userAccount = null;
-        Account caller = (Account)UserContext.current().getCaller();
-        Long usageType = cmd.getUsageType();
-        Long projectId = cmd.getProjectId();
-        
-        if (projectId != null) {
-            if (accountId != null) {
-                throw new InvalidParameterValueException("Projectid and accountId can't be specified together");
-            }
-            Project project = _projectMgr.getProject(projectId);
-            if (project == null) {
-                throw new InvalidParameterValueException("Unable to find project by id " + projectId);
-            }
-            accountId = project.getProjectAccountId();
-        }
-        
-        //if accountId is not specified, use accountName and domainId
-        if ((accountId == null) && (accountName != null) && (domainId != null)) {
-            if (_domainDao.isChildDomain(caller.getDomainId(), domainId)) {
-                Filter filter = new Filter(AccountVO.class, "id", Boolean.FALSE, null, null);
-                List<AccountVO> accounts = _accountDao.listAccounts(accountName, domainId, filter); 
-                if(accounts.size() > 0){
-                    userAccount = accounts.get(0);
-                }
-                if (userAccount != null) {
-                    accountId = userAccount.getId();
-                } else {
-                    throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId);
-                }
-            } else {
-                throw new PermissionDeniedException("Invalid Domain Id or Account");
-            }
-        } 
-
-        boolean isAdmin = false;
-        
-        //If accountId couldn't be found using accountName and domainId, get it from userContext
-        if(accountId == null){
-            accountId = caller.getId();
-            //List records for all the accounts if the caller account is of type admin. 
-            //If account_id or account_name is explicitly mentioned, list records for the specified account only even if the caller is of type admin
-            if(caller.getType() == Account.ACCOUNT_TYPE_ADMIN){
-                isAdmin = true;
-            }
-            s_logger.debug("Account details not available. Using userContext accountId: " + accountId);
-        }
-
-        Date startDate = cmd.getStartDate();
-        Date endDate = cmd.getEndDate();
-        if(startDate.after(endDate)){
-        	throw new InvalidParameterValueException("Incorrect Date Range. Start date: "+startDate+" is after end date:"+endDate);
-        }
-        TimeZone usageTZ = getUsageTimezone();
-        Date adjustedStartDate = computeAdjustedTime(startDate, usageTZ, true);
-        Date adjustedEndDate = computeAdjustedTime(endDate, usageTZ, false);
-
-        if (s_logger.isDebugEnabled()) {
-            s_logger.debug("getting usage records for account: " + accountId + ", domainId: " + domainId + ", between " + startDate + " and " + endDate + ", using pageSize: " + cmd.getPageSizeVal() + " and startIndex: " + cmd.getStartIndex());
-        }
-
-        Filter usageFilter = new Filter(UsageVO.class, "startDate", false, cmd.getStartIndex(), cmd.getPageSizeVal());
-        
-        SearchCriteria<UsageVO> sc = _usageDao.createSearchCriteria();
-
-        if (accountId != -1 && accountId != Account.ACCOUNT_ID_SYSTEM && !isAdmin) {
-            sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId);
-        }
-
-        if (domainId != null) {
-            sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
-        }
-        
-        if (usageType != null) {
-            sc.addAnd("usageType", SearchCriteria.Op.EQ, usageType);
-        }
-
-        if ((adjustedStartDate != null) && (adjustedEndDate != null) && adjustedStartDate.before(adjustedEndDate)) {
-            sc.addAnd("startDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate);
-            sc.addAnd("endDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate);
-        } else {
-            return new ArrayList<UsageVO>(); // return an empty list if we fail to validate the dates
-        }
-
-        List<UsageVO> usageRecords = null;
-        Transaction txn = Transaction.open(Transaction.USAGE_DB);
-        try {
-            usageRecords = _usageDao.searchAllRecords(sc, usageFilter);
-        } finally {
-            txn.close();
-
-            // switch back to VMOPS_DB
-            Transaction swap = Transaction.open(Transaction.CLOUD_DB);
-            swap.close();
-        }
-
-        // now that we are done with the records, update the command with the correct timezone so it can write the proper response
-        cmd.setUsageTimezone(getUsageTimezone());
-
-        return usageRecords;
-    }
-
-    @Override
-    public TimeZone getUsageTimezone() {
-        return _usageTimezone;
-    }
-
-    @Override
-    public List<Class<?>> getCommands() {
-        //TODO: Add api cmd classes
-        return null;
-    }
-
-    private Date computeAdjustedTime(Date initialDate, TimeZone targetTZ, boolean adjustToDayStart) {
-        Calendar cal = Calendar.getInstance();
-        cal.setTime(initialDate);
-        TimeZone localTZ = cal.getTimeZone();
-        int timezoneOffset = cal.get(Calendar.ZONE_OFFSET);
-        if (localTZ.inDaylightTime(initialDate)) {
-            timezoneOffset += (60 * 60 * 1000);
-        }
-        cal.add(Calendar.MILLISECOND, timezoneOffset);
-
-        Date newTime = cal.getTime();
-
-        Calendar calTS = Calendar.getInstance(targetTZ);
-        calTS.setTime(newTime);
-        timezoneOffset = calTS.get(Calendar.ZONE_OFFSET);
-        if (targetTZ.inDaylightTime(initialDate)) {
-            timezoneOffset += (60 * 60 * 1000);
-        }
-
-        calTS.add(Calendar.MILLISECOND, -1*timezoneOffset);
-        if (adjustToDayStart) {
-            calTS.set(Calendar.HOUR_OF_DAY, 0);
-            calTS.set(Calendar.MINUTE, 0);
-            calTS.set(Calendar.SECOND, 0);
-            calTS.set(Calendar.MILLISECOND, 0);
-        } else {
-            calTS.set(Calendar.HOUR_OF_DAY, 23);
-            calTS.set(Calendar.MINUTE, 59);
-            calTS.set(Calendar.SECOND, 59);
-            calTS.set(Calendar.MILLISECOND, 999);
-        }
-
-        return calTS.getTime();
-    }
-
-	@Override
-	public List<UsageTypeResponse> listUsageTypes() {
-		return UsageTypes.listUsageTypes();
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/fc0bf21a/server/src/com/cloud/usage/UsageServiceImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/usage/UsageServiceImpl.java b/server/src/com/cloud/usage/UsageServiceImpl.java
new file mode 100755
index 0000000..ae0a585
--- /dev/null
+++ b/server/src/com/cloud/usage/UsageServiceImpl.java
@@ -0,0 +1,261 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.usage;
+
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+import java.util.TimeZone;
+
+import javax.ejb.Local;
+import javax.inject.Inject;
+import javax.naming.ConfigurationException;
+
+import org.apache.cloudstack.api.command.admin.usage.GenerateUsageRecordsCmd;
+import org.apache.cloudstack.api.command.admin.usage.GetUsageRecordsCmd;
+import org.apache.cloudstack.api.response.UsageTypeResponse;
+import org.apache.cloudstack.usage.UsageService;
+import org.apache.cloudstack.usage.UsageTypes;
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+import com.cloud.configuration.Config;
+import com.cloud.configuration.dao.ConfigurationDao;
+import com.cloud.domain.dao.DomainDao;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.exception.PermissionDeniedException;
+import com.cloud.projects.Project;
+import com.cloud.projects.ProjectManager;
+import com.cloud.usage.dao.UsageDao;
+import com.cloud.usage.dao.UsageJobDao;
+import com.cloud.user.Account;
+import com.cloud.user.AccountVO;
+import com.cloud.user.UserContext;
+import com.cloud.user.dao.AccountDao;
+import com.cloud.utils.component.Manager;
+import com.cloud.utils.component.ManagerBase;
+import com.cloud.utils.db.Filter;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.db.Transaction;
+
+@Component
+@Local(value = { UsageService.class })
+public class UsageServiceImpl extends ManagerBase implements UsageService, Manager {
+    public static final Logger s_logger = Logger.getLogger(UsageServiceImpl.class);
+    
+    //ToDo: Move implementation to ManagaerImpl
+    
+    @Inject private AccountDao _accountDao;
+    @Inject private DomainDao _domainDao;
+    @Inject private UsageDao _usageDao;
+    @Inject private UsageJobDao _usageJobDao;
+    @Inject private ConfigurationDao _configDao;
+    @Inject private ProjectManager _projectMgr;
+    private TimeZone _usageTimezone;
+
+    public UsageServiceImpl() {
+    }
+    
+    @Override
+    public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
+    	super.configure(name,  params);
+        String timeZoneStr = _configDao.getValue(Config.UsageAggregationTimezone.toString());
+        if (timeZoneStr == null) {
+           timeZoneStr = "GMT";
+        }
+        _usageTimezone = TimeZone.getTimeZone(timeZoneStr);
+        return true;
+    }
+
+    @Override
+    public boolean generateUsageRecords(GenerateUsageRecordsCmd cmd) {
+        Transaction txn = Transaction.open(Transaction.USAGE_DB);
+        try {
+            UsageJobVO immediateJob = _usageJobDao.getNextImmediateJob();
+            if (immediateJob == null) {
+                UsageJobVO job = _usageJobDao.getLastJob();
+
+                String host = null;
+                int pid = 0;
+                if (job != null) {
+                    host = job.getHost();
+                    pid = ((job.getPid() == null) ? 0 : job.getPid().intValue());
+                }
+                _usageJobDao.createNewJob(host, pid, UsageJobVO.JOB_TYPE_SINGLE);
+            }
+        } finally {
+            txn.close();
+
+            // switch back to VMOPS_DB
+            Transaction swap = Transaction.open(Transaction.CLOUD_DB);
+            swap.close();
+        }
+        return true;
+    }
+
+    @Override
+    public List<UsageVO> getUsageRecords(GetUsageRecordsCmd cmd) {
+        Long accountId = cmd.getAccountId();
+        Long domainId = cmd.getDomainId();
+        String accountName = cmd.getAccountName();
+        Account userAccount = null;
+        Account caller = (Account)UserContext.current().getCaller();
+        Long usageType = cmd.getUsageType();
+        Long projectId = cmd.getProjectId();
+        
+        if (projectId != null) {
+            if (accountId != null) {
+                throw new InvalidParameterValueException("Projectid and accountId can't be specified together");
+            }
+            Project project = _projectMgr.getProject(projectId);
+            if (project == null) {
+                throw new InvalidParameterValueException("Unable to find project by id " + projectId);
+            }
+            accountId = project.getProjectAccountId();
+        }
+        
+        //if accountId is not specified, use accountName and domainId
+        if ((accountId == null) && (accountName != null) && (domainId != null)) {
+            if (_domainDao.isChildDomain(caller.getDomainId(), domainId)) {
+                Filter filter = new Filter(AccountVO.class, "id", Boolean.FALSE, null, null);
+                List<AccountVO> accounts = _accountDao.listAccounts(accountName, domainId, filter); 
+                if(accounts.size() > 0){
+                    userAccount = accounts.get(0);
+                }
+                if (userAccount != null) {
+                    accountId = userAccount.getId();
+                } else {
+                    throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId);
+                }
+            } else {
+                throw new PermissionDeniedException("Invalid Domain Id or Account");
+            }
+        } 
+
+        boolean isAdmin = false;
+        
+        //If accountId couldn't be found using accountName and domainId, get it from userContext
+        if(accountId == null){
+            accountId = caller.getId();
+            //List records for all the accounts if the caller account is of type admin. 
+            //If account_id or account_name is explicitly mentioned, list records for the specified account only even if the caller is of type admin
+            if(caller.getType() == Account.ACCOUNT_TYPE_ADMIN){
+                isAdmin = true;
+            }
+            s_logger.debug("Account details not available. Using userContext accountId: " + accountId);
+        }
+
+        Date startDate = cmd.getStartDate();
+        Date endDate = cmd.getEndDate();
+        if(startDate.after(endDate)){
+        	throw new InvalidParameterValueException("Incorrect Date Range. Start date: "+startDate+" is after end date:"+endDate);
+        }
+        TimeZone usageTZ = getUsageTimezone();
+        Date adjustedStartDate = computeAdjustedTime(startDate, usageTZ, true);
+        Date adjustedEndDate = computeAdjustedTime(endDate, usageTZ, false);
+
+        if (s_logger.isDebugEnabled()) {
+            s_logger.debug("getting usage records for account: " + accountId + ", domainId: " + domainId + ", between " + startDate + " and " + endDate + ", using pageSize: " + cmd.getPageSizeVal() + " and startIndex: " + cmd.getStartIndex());
+        }
+
+        Filter usageFilter = new Filter(UsageVO.class, "startDate", false, cmd.getStartIndex(), cmd.getPageSizeVal());
+        
+        SearchCriteria<UsageVO> sc = _usageDao.createSearchCriteria();
+
+        if (accountId != -1 && accountId != Account.ACCOUNT_ID_SYSTEM && !isAdmin) {
+            sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId);
+        }
+
+        if (domainId != null) {
+            sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
+        }
+        
+        if (usageType != null) {
+            sc.addAnd("usageType", SearchCriteria.Op.EQ, usageType);
+        }
+
+        if ((adjustedStartDate != null) && (adjustedEndDate != null) && adjustedStartDate.before(adjustedEndDate)) {
+            sc.addAnd("startDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate);
+            sc.addAnd("endDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate);
+        } else {
+            return new ArrayList<UsageVO>(); // return an empty list if we fail to validate the dates
+        }
+
+        List<UsageVO> usageRecords = null;
+        Transaction txn = Transaction.open(Transaction.USAGE_DB);
+        try {
+            usageRecords = _usageDao.searchAllRecords(sc, usageFilter);
+        } finally {
+            txn.close();
+
+            // switch back to VMOPS_DB
+            Transaction swap = Transaction.open(Transaction.CLOUD_DB);
+            swap.close();
+        }
+
+        return usageRecords;
+    }
+
+    @Override
+    public TimeZone getUsageTimezone() {
+        return _usageTimezone;
+    }
+
+    private Date computeAdjustedTime(Date initialDate, TimeZone targetTZ, boolean adjustToDayStart) {
+        Calendar cal = Calendar.getInstance();
+        cal.setTime(initialDate);
+        TimeZone localTZ = cal.getTimeZone();
+        int timezoneOffset = cal.get(Calendar.ZONE_OFFSET);
+        if (localTZ.inDaylightTime(initialDate)) {
+            timezoneOffset += (60 * 60 * 1000);
+        }
+        cal.add(Calendar.MILLISECOND, timezoneOffset);
+
+        Date newTime = cal.getTime();
+
+        Calendar calTS = Calendar.getInstance(targetTZ);
+        calTS.setTime(newTime);
+        timezoneOffset = calTS.get(Calendar.ZONE_OFFSET);
+        if (targetTZ.inDaylightTime(initialDate)) {
+            timezoneOffset += (60 * 60 * 1000);
+        }
+
+        calTS.add(Calendar.MILLISECOND, -1*timezoneOffset);
+        if (adjustToDayStart) {
+            calTS.set(Calendar.HOUR_OF_DAY, 0);
+            calTS.set(Calendar.MINUTE, 0);
+            calTS.set(Calendar.SECOND, 0);
+            calTS.set(Calendar.MILLISECOND, 0);
+        } else {
+            calTS.set(Calendar.HOUR_OF_DAY, 23);
+            calTS.set(Calendar.MINUTE, 59);
+            calTS.set(Calendar.SECOND, 59);
+            calTS.set(Calendar.MILLISECOND, 999);
+        }
+
+        return calTS.getTime();
+    }
+
+	@Override
+	public List<UsageTypeResponse> listUsageTypes() {
+		return UsageTypes.listUsageTypes();
+	}
+
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/fc0bf21a/server/src/com/cloud/usage/UsageTypes.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/usage/UsageTypes.java b/server/src/com/cloud/usage/UsageTypes.java
deleted file mode 100644
index e5a48d5..0000000
--- a/server/src/com/cloud/usage/UsageTypes.java
+++ /dev/null
@@ -1,58 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License.  You may obtain a copy of the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied.  See the License for the
-// specific language governing permissions and limitations
-// under the License.
-package com.cloud.usage;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.cloudstack.api.response.UsageTypeResponse;
-
-public class UsageTypes {
-    public static final int RUNNING_VM = 1;
-    public static final int ALLOCATED_VM = 2; // used for tracking how long storage has been allocated for a VM
-    public static final int IP_ADDRESS = 3;
-    public static final int NETWORK_BYTES_SENT = 4;
-    public static final int NETWORK_BYTES_RECEIVED = 5;
-    public static final int VOLUME = 6;
-    public static final int TEMPLATE = 7;
-    public static final int ISO = 8;
-    public static final int SNAPSHOT = 9;
-    public static final int SECURITY_GROUP = 10;
-    public static final int LOAD_BALANCER_POLICY = 11;
-    public static final int PORT_FORWARDING_RULE = 12;
-    public static final int NETWORK_OFFERING = 13;
-    public static final int VPN_USERS = 14;
-    
-    public static List<UsageTypeResponse> listUsageTypes(){
-    	List<UsageTypeResponse> responseList = new ArrayList<UsageTypeResponse>();
-    	responseList.add(new UsageTypeResponse(RUNNING_VM, "Running Vm Usage"));
-    	responseList.add(new UsageTypeResponse(ALLOCATED_VM, "Allocated Vm Usage"));
-    	responseList.add(new UsageTypeResponse(IP_ADDRESS, "IP Address Usage"));
-    	responseList.add(new UsageTypeResponse(NETWORK_BYTES_SENT, "Network Usage (Bytes Sent)"));
-    	responseList.add(new UsageTypeResponse(NETWORK_BYTES_RECEIVED, "Network Usage (Bytes Received)"));
-    	responseList.add(new UsageTypeResponse(VOLUME, "Volume Usage"));
-    	responseList.add(new UsageTypeResponse(TEMPLATE, "Template Usage"));
-    	responseList.add(new UsageTypeResponse(ISO, "ISO Usage"));
-    	responseList.add(new UsageTypeResponse(SNAPSHOT, "Snapshot Usage"));
-    	responseList.add(new UsageTypeResponse(SECURITY_GROUP, "Security Group Usage"));
-    	responseList.add(new UsageTypeResponse(LOAD_BALANCER_POLICY, "Load Balancer Usage"));
-    	responseList.add(new UsageTypeResponse(PORT_FORWARDING_RULE, "Port Forwarding Usage"));
-    	responseList.add(new UsageTypeResponse(NETWORK_OFFERING, "Network Offering Usage"));
-    	responseList.add(new UsageTypeResponse(VPN_USERS, "VPN users usage"));
-    	return responseList;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/fc0bf21a/server/src/com/cloud/usage/UsageVO.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/usage/UsageVO.java b/server/src/com/cloud/usage/UsageVO.java
index bcb9c2d..18a3a6b 100644
--- a/server/src/com/cloud/usage/UsageVO.java
+++ b/server/src/com/cloud/usage/UsageVO.java
@@ -17,6 +17,7 @@
 package com.cloud.usage;
 
 import org.apache.cloudstack.api.InternalIdentity;
+import org.apache.cloudstack.usage.Usage;
 
 import java.util.Date;
 
@@ -31,7 +32,7 @@ import javax.persistence.TemporalType;
 
 @Entity
 @Table(name="cloud_usage")
-public class UsageVO implements InternalIdentity {
+public class UsageVO implements Usage, InternalIdentity {
 	@Id
     @GeneratedValue(strategy=GenerationType.IDENTITY)
     @Column(name="id")
@@ -167,74 +168,92 @@ public class UsageVO implements InternalIdentity {
 	    this.endDate = endDate;
 	}
 	
+	@Override
 	public long getId() {
 		return id;
 	}
 
+	@Override
 	public Long getZoneId() {
 	    return zoneId;
 	}
 
+	@Override
 	public Long getAccountId() {
 		return accountId;
 	}
 
+	@Override
     public Long getDomainId() {
         return domainId;
     }
 
+	@Override
 	public String getDescription() {
 		return description;
 	}
-
+	
+	@Override
 	public String getUsageDisplay() {
 		return usageDisplay;
 	}
 
+	@Override
 	public int getUsageType() {
 	    return usageType;
 	}
 
+	@Override
     public Double getRawUsage() {
         return rawUsage;
     }
 
+	@Override
     public Long getVmInstanceId() {
         return vmInstanceId;
     }
 
+	@Override
     public String getVmName() {
         return vmName;
     }
 
+	@Override
     public Long getOfferingId() {
         return offeringId;
     }
 
+	@Override
     public Long getTemplateId() {
         return templateId;
     }
 
+	@Override
     public Long getUsageId() {
         return usageId;
     }
     
+	@Override
     public String getType() {
         return type;
     }
     
+	@Override
     public Long getNetworkId() {
         return networkId;
     }
 
+	@Override
     public Long getSize() {
         return size;
     }
     
+	@Override
 	public Date getStartDate() {
 		return startDate;
 	}
 
+	@Override
 	public Date getEndDate() {
         return endDate;
     }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/fc0bf21a/usage/src/com/cloud/usage/UsageManagerImpl.java
----------------------------------------------------------------------
diff --git a/usage/src/com/cloud/usage/UsageManagerImpl.java b/usage/src/com/cloud/usage/UsageManagerImpl.java
index 3e143b1..1ebe892 100644
--- a/usage/src/com/cloud/usage/UsageManagerImpl.java
+++ b/usage/src/com/cloud/usage/UsageManagerImpl.java
@@ -34,6 +34,7 @@ import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
 import org.apache.log4j.Logger;
+import org.apache.cloudstack.usage.UsageTypes;
 
 import com.cloud.alert.AlertManager;
 import com.cloud.configuration.dao.ConfigurationDao;

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/fc0bf21a/usage/src/com/cloud/usage/parser/IPAddressUsageParser.java
----------------------------------------------------------------------
diff --git a/usage/src/com/cloud/usage/parser/IPAddressUsageParser.java b/usage/src/com/cloud/usage/parser/IPAddressUsageParser.java
index a5a40c0..0889203 100644
--- a/usage/src/com/cloud/usage/parser/IPAddressUsageParser.java
+++ b/usage/src/com/cloud/usage/parser/IPAddressUsageParser.java
@@ -26,11 +26,11 @@ import javax.annotation.PostConstruct;
 import javax.inject.Inject;
 
 import org.apache.log4j.Logger;
+import org.apache.cloudstack.usage.UsageTypes;
 import org.springframework.stereotype.Component;
 
 import com.cloud.usage.UsageIPAddressVO;
 import com.cloud.usage.UsageServer;
-import com.cloud.usage.UsageTypes;
 import com.cloud.usage.UsageVO;
 import com.cloud.usage.dao.UsageDao;
 import com.cloud.usage.dao.UsageIPAddressDao;

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/fc0bf21a/usage/src/com/cloud/usage/parser/LoadBalancerUsageParser.java
----------------------------------------------------------------------
diff --git a/usage/src/com/cloud/usage/parser/LoadBalancerUsageParser.java b/usage/src/com/cloud/usage/parser/LoadBalancerUsageParser.java
index edea320..84d0b32 100644
--- a/usage/src/com/cloud/usage/parser/LoadBalancerUsageParser.java
+++ b/usage/src/com/cloud/usage/parser/LoadBalancerUsageParser.java
@@ -26,11 +26,11 @@ import javax.annotation.PostConstruct;
 import javax.inject.Inject;
 
 import org.apache.log4j.Logger;
+import org.apache.cloudstack.usage.UsageTypes;
 import org.springframework.stereotype.Component;
 
 import com.cloud.usage.UsageLoadBalancerPolicyVO;
 import com.cloud.usage.UsageServer;
-import com.cloud.usage.UsageTypes;
 import com.cloud.usage.UsageVO;
 import com.cloud.usage.dao.UsageDao;
 import com.cloud.usage.dao.UsageLoadBalancerPolicyDao;

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/fc0bf21a/usage/src/com/cloud/usage/parser/NetworkOfferingUsageParser.java
----------------------------------------------------------------------
diff --git a/usage/src/com/cloud/usage/parser/NetworkOfferingUsageParser.java b/usage/src/com/cloud/usage/parser/NetworkOfferingUsageParser.java
index f6ddf9f..d026b76 100644
--- a/usage/src/com/cloud/usage/parser/NetworkOfferingUsageParser.java
+++ b/usage/src/com/cloud/usage/parser/NetworkOfferingUsageParser.java
@@ -26,10 +26,10 @@ import javax.annotation.PostConstruct;
 import javax.inject.Inject;
 
 import org.apache.log4j.Logger;
+import org.apache.cloudstack.usage.UsageTypes;
 
 import com.cloud.usage.UsageNetworkOfferingVO;
 import com.cloud.usage.UsageServer;
-import com.cloud.usage.UsageTypes;
 import com.cloud.usage.UsageVO;
 import com.cloud.usage.dao.UsageDao;
 import com.cloud.usage.dao.UsageNetworkOfferingDao;

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/fc0bf21a/usage/src/com/cloud/usage/parser/NetworkUsageParser.java
----------------------------------------------------------------------
diff --git a/usage/src/com/cloud/usage/parser/NetworkUsageParser.java b/usage/src/com/cloud/usage/parser/NetworkUsageParser.java
index fb673d7..a891fdd 100644
--- a/usage/src/com/cloud/usage/parser/NetworkUsageParser.java
+++ b/usage/src/com/cloud/usage/parser/NetworkUsageParser.java
@@ -25,9 +25,9 @@ import javax.annotation.PostConstruct;
 import javax.inject.Inject;
 
 import org.apache.log4j.Logger;
+import org.apache.cloudstack.usage.UsageTypes;
 
 import com.cloud.usage.UsageNetworkVO;
-import com.cloud.usage.UsageTypes;
 import com.cloud.usage.UsageVO;
 import com.cloud.usage.dao.UsageDao;
 import com.cloud.usage.dao.UsageNetworkDao;

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/fc0bf21a/usage/src/com/cloud/usage/parser/PortForwardingUsageParser.java
----------------------------------------------------------------------
diff --git a/usage/src/com/cloud/usage/parser/PortForwardingUsageParser.java b/usage/src/com/cloud/usage/parser/PortForwardingUsageParser.java
index 1692180..4780d14 100644
--- a/usage/src/com/cloud/usage/parser/PortForwardingUsageParser.java
+++ b/usage/src/com/cloud/usage/parser/PortForwardingUsageParser.java
@@ -26,10 +26,10 @@ import javax.annotation.PostConstruct;
 import javax.inject.Inject;
 
 import org.apache.log4j.Logger;
+import org.apache.cloudstack.usage.UsageTypes;
 
 import com.cloud.usage.UsagePortForwardingRuleVO;
 import com.cloud.usage.UsageServer;
-import com.cloud.usage.UsageTypes;
 import com.cloud.usage.UsageVO;
 import com.cloud.usage.dao.UsageDao;
 import com.cloud.usage.dao.UsagePortForwardingRuleDao;

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/fc0bf21a/usage/src/com/cloud/usage/parser/SecurityGroupUsageParser.java
----------------------------------------------------------------------
diff --git a/usage/src/com/cloud/usage/parser/SecurityGroupUsageParser.java b/usage/src/com/cloud/usage/parser/SecurityGroupUsageParser.java
index ed7acf3..df859b8 100644
--- a/usage/src/com/cloud/usage/parser/SecurityGroupUsageParser.java
+++ b/usage/src/com/cloud/usage/parser/SecurityGroupUsageParser.java
@@ -26,10 +26,10 @@ import javax.annotation.PostConstruct;
 import javax.inject.Inject;
 
 import org.apache.log4j.Logger;
+import org.apache.cloudstack.usage.UsageTypes;
 
 import com.cloud.usage.UsageSecurityGroupVO;
 import com.cloud.usage.UsageServer;
-import com.cloud.usage.UsageTypes;
 import com.cloud.usage.UsageVO;
 import com.cloud.usage.dao.UsageDao;
 import com.cloud.usage.dao.UsageSecurityGroupDao;

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/fc0bf21a/usage/src/com/cloud/usage/parser/StorageUsageParser.java
----------------------------------------------------------------------
diff --git a/usage/src/com/cloud/usage/parser/StorageUsageParser.java b/usage/src/com/cloud/usage/parser/StorageUsageParser.java
index 7542063..4e3817e 100644
--- a/usage/src/com/cloud/usage/parser/StorageUsageParser.java
+++ b/usage/src/com/cloud/usage/parser/StorageUsageParser.java
@@ -26,11 +26,11 @@ import javax.annotation.PostConstruct;
 import javax.inject.Inject;
 
 import org.apache.log4j.Logger;
+import org.apache.cloudstack.usage.UsageTypes;
 
 import com.cloud.usage.StorageTypes;
 import com.cloud.usage.UsageServer;
 import com.cloud.usage.UsageStorageVO;
-import com.cloud.usage.UsageTypes;
 import com.cloud.usage.UsageVO;
 import com.cloud.usage.dao.UsageDao;
 import com.cloud.usage.dao.UsageStorageDao;

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/fc0bf21a/usage/src/com/cloud/usage/parser/VMInstanceUsageParser.java
----------------------------------------------------------------------
diff --git a/usage/src/com/cloud/usage/parser/VMInstanceUsageParser.java b/usage/src/com/cloud/usage/parser/VMInstanceUsageParser.java
index 8d2e465..2e7ee59 100644
--- a/usage/src/com/cloud/usage/parser/VMInstanceUsageParser.java
+++ b/usage/src/com/cloud/usage/parser/VMInstanceUsageParser.java
@@ -26,9 +26,9 @@ import javax.annotation.PostConstruct;
 import javax.inject.Inject;
 
 import org.apache.log4j.Logger;
+import org.apache.cloudstack.usage.UsageTypes;
 
 import com.cloud.usage.UsageServer;
-import com.cloud.usage.UsageTypes;
 import com.cloud.usage.UsageVMInstanceVO;
 import com.cloud.usage.UsageVO;
 import com.cloud.usage.dao.UsageDao;

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/fc0bf21a/usage/src/com/cloud/usage/parser/VPNUserUsageParser.java
----------------------------------------------------------------------
diff --git a/usage/src/com/cloud/usage/parser/VPNUserUsageParser.java b/usage/src/com/cloud/usage/parser/VPNUserUsageParser.java
index c9a863b..c76de28 100644
--- a/usage/src/com/cloud/usage/parser/VPNUserUsageParser.java
+++ b/usage/src/com/cloud/usage/parser/VPNUserUsageParser.java
@@ -26,10 +26,10 @@ import javax.annotation.PostConstruct;
 import javax.inject.Inject;
 
 import org.apache.log4j.Logger;
+import org.apache.cloudstack.usage.UsageTypes;
 
 import com.cloud.usage.UsageVPNUserVO;
 import com.cloud.usage.UsageServer;
-import com.cloud.usage.UsageTypes;
 import com.cloud.usage.UsageVO;
 import com.cloud.usage.dao.UsageDao;
 import com.cloud.usage.dao.UsageVPNUserDao;

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/fc0bf21a/usage/src/com/cloud/usage/parser/VolumeUsageParser.java
----------------------------------------------------------------------
diff --git a/usage/src/com/cloud/usage/parser/VolumeUsageParser.java b/usage/src/com/cloud/usage/parser/VolumeUsageParser.java
index e797f1c..6d9fe5d 100644
--- a/usage/src/com/cloud/usage/parser/VolumeUsageParser.java
+++ b/usage/src/com/cloud/usage/parser/VolumeUsageParser.java
@@ -26,9 +26,9 @@ import javax.annotation.PostConstruct;
 import javax.inject.Inject;
 
 import org.apache.log4j.Logger;
+import org.apache.cloudstack.usage.UsageTypes;
 
 import com.cloud.usage.UsageServer;
-import com.cloud.usage.UsageTypes;
 import com.cloud.usage.UsageVO;
 import com.cloud.usage.UsageVolumeVO;
 import com.cloud.usage.dao.UsageDao;


Mime
View raw message