cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From prachida...@apache.org
Subject [24/91] [abbrv] [partial] Moved most of the VOs and DAOs from server package into engine-schema as well
Date Thu, 09 May 2013 00:20:35 GMT
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/usage/dao/UsageStorageDaoImpl.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/usage/dao/UsageStorageDaoImpl.java b/engine/schema/src/com/cloud/usage/dao/UsageStorageDaoImpl.java
new file mode 100644
index 0000000..297c8f4
--- /dev/null
+++ b/engine/schema/src/com/cloud/usage/dao/UsageStorageDaoImpl.java
@@ -0,0 +1,211 @@
+// 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.dao;
+
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.TimeZone;
+
+import javax.ejb.Local;
+
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+import com.cloud.usage.UsageStorageVO;
+import com.cloud.utils.DateUtil;
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.db.Transaction;
+
+@Component
+@Local(value={UsageStorageDao.class})
+public class UsageStorageDaoImpl extends GenericDaoBase<UsageStorageVO, Long> implements UsageStorageDao {
+	public static final Logger s_logger = Logger.getLogger(UsageStorageDaoImpl.class.getName());
+
+	protected static final String REMOVE_BY_USERID_STORAGEID = "DELETE FROM usage_storage WHERE account_id = ? AND id = ? AND storage_type = ?";
+	protected static final String UPDATE_DELETED = "UPDATE usage_storage SET deleted = ? WHERE account_id = ? AND id = ? AND storage_type = ? and deleted IS NULL";
+    protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT id, zone_id, account_id, domain_id, storage_type, source_id, size, created, deleted " +
+                                                                 "FROM usage_storage " +
+                                                                 "WHERE account_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " +
+                                                                 "      (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))";
+    protected static final String GET_USAGE_RECORDS_BY_DOMAIN = "SELECT id, zone_id, account_id, domain_id, storage_type, source_id, size, created, deleted " +
+                                                                "FROM usage_storage " +
+                                                                "WHERE domain_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " +
+                                                                "      (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))";
+    protected static final String GET_ALL_USAGE_RECORDS = "SELECT id, zone_id, account_id, domain_id, storage_type, source_id, size, created, deleted " +
+                                                          "FROM usage_storage " +
+                                                          "WHERE (deleted IS NULL) OR (created BETWEEN ? AND ?) OR " +
+                                                          "      (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?))";
+
+    private final SearchBuilder<UsageStorageVO> IdSearch;
+    private final SearchBuilder<UsageStorageVO> IdZoneSearch;
+    
+	public UsageStorageDaoImpl() {
+	    IdSearch = createSearchBuilder();
+	    IdSearch.and("accountId", IdSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
+	    IdSearch.and("id", IdSearch.entity().getId(), SearchCriteria.Op.EQ);
+	    IdSearch.and("type", IdSearch.entity().getStorageType(), SearchCriteria.Op.EQ);
+	    IdSearch.done();
+	    
+	    IdZoneSearch = createSearchBuilder();
+	    IdZoneSearch.and("accountId", IdZoneSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
+	    IdZoneSearch.and("id", IdZoneSearch.entity().getId(), SearchCriteria.Op.EQ);
+	    IdZoneSearch.and("type", IdZoneSearch.entity().getStorageType(), SearchCriteria.Op.EQ);
+	    IdZoneSearch.and("dcId", IdZoneSearch.entity().getZoneId(), SearchCriteria.Op.EQ);
+	    IdZoneSearch.done();
+	}
+
+    @Override
+    public List<UsageStorageVO> listById(long accountId, long id, int type) {
+        SearchCriteria<UsageStorageVO> sc = IdSearch.create();
+        sc.setParameters("accountId", accountId);
+        sc.setParameters("id", id);
+        sc.setParameters("type", type);
+        return listBy(sc, null);
+    }
+    
+    @Override
+    public List<UsageStorageVO> listByIdAndZone(long accountId, long id, int type, long dcId) {
+        SearchCriteria<UsageStorageVO> sc = IdZoneSearch.create();
+        sc.setParameters("accountId", accountId);
+        sc.setParameters("id", id);
+        sc.setParameters("type", type);
+        sc.setParameters("dcId", dcId);
+        return listBy(sc, null);
+    }
+	
+	public void removeBy(long accountId, long volId, int storage_type) {
+	    Transaction txn = Transaction.open(Transaction.USAGE_DB);
+		PreparedStatement pstmt = null;
+		try {
+		    txn.start();
+			String sql = REMOVE_BY_USERID_STORAGEID;
+			pstmt = txn.prepareAutoCloseStatement(sql);
+			pstmt.setLong(1, accountId);
+			pstmt.setLong(2, volId);
+			pstmt.setInt(3, storage_type);
+			pstmt.executeUpdate();
+			txn.commit();
+		} catch (Exception e) {
+			txn.rollback();
+			s_logger.warn("Error removing usageStorageVO", e);
+		} finally {
+		    txn.close();
+		}
+	}
+
+	public void update(UsageStorageVO usage) {
+	    Transaction txn = Transaction.open(Transaction.USAGE_DB);
+		PreparedStatement pstmt = null;
+		try {
+		    txn.start();
+			if (usage.getDeleted() != null) {
+				pstmt = txn.prepareAutoCloseStatement(UPDATE_DELETED);
+				pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), usage.getDeleted()));
+				pstmt.setLong(2, usage.getAccountId());
+				pstmt.setLong(3, usage.getId());
+				pstmt.setInt(4, usage.getStorageType());
+			}
+			pstmt.executeUpdate();
+			txn.commit();
+		} catch (Exception e) {
+			txn.rollback();
+			s_logger.warn("Error updating UsageStorageVO", e);
+		} finally {
+		    txn.close();
+		}
+	}
+
+    @Override
+	public List<UsageStorageVO> getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page) {
+        List<UsageStorageVO> usageRecords = new ArrayList<UsageStorageVO>();
+
+        Long param1 = null;
+        String sql = null;
+        if (accountId != null) {
+            sql = GET_USAGE_RECORDS_BY_ACCOUNT;
+            param1 = accountId;
+        } else if (domainId != null) {
+            sql = GET_USAGE_RECORDS_BY_DOMAIN;
+            param1 = domainId;
+        } else {
+            sql = GET_ALL_USAGE_RECORDS;
+        }
+
+        if (limit) {
+            int startIndex = 0;
+            if (page > 0) {
+                startIndex = 500 * (page-1);
+            }
+            sql += " LIMIT " + startIndex + ",500";
+        }
+
+        Transaction txn = Transaction.open(Transaction.USAGE_DB);
+        PreparedStatement pstmt = null;
+
+        try {
+            int i = 1;
+            pstmt = txn.prepareAutoCloseStatement(sql);
+            if (param1 != null) {
+                pstmt.setLong(i++, param1);
+            }
+            pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate));
+            pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate));
+            pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate));
+            pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate));
+            pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate));
+            pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate));
+
+            ResultSet rs = pstmt.executeQuery();
+            while (rs.next()) {
+                //id, zone_id, account_id, domain_id, storage_type, size, created, deleted
+            	Long id = Long.valueOf(rs.getLong(1));
+            	Long zoneId = Long.valueOf(rs.getLong(2));
+                Long acctId = Long.valueOf(rs.getLong(3));
+                Long dId = Long.valueOf(rs.getLong(4));
+                Integer type = Integer.valueOf(rs.getInt(5));
+                Long sourceId = Long.valueOf(rs.getLong(6));
+                Long size = Long.valueOf(rs.getLong(7));
+                Date createdDate = null;
+                Date deletedDate = null;
+                String createdTS = rs.getString(8);
+                String deletedTS = rs.getString(9);
+                
+
+                if (createdTS != null) {
+                	createdDate = DateUtil.parseDateString(s_gmtTimeZone, createdTS);
+                }
+                if (deletedTS != null) {
+                	deletedDate = DateUtil.parseDateString(s_gmtTimeZone, deletedTS);
+                }
+
+                usageRecords.add(new UsageStorageVO(id, zoneId, acctId, dId, type, sourceId, size, createdDate, deletedDate));
+            }
+        } catch (Exception e) {
+            txn.rollback();
+            s_logger.warn("Error getting usage records", e);
+        } finally {
+            txn.close();
+        }
+
+        return usageRecords;
+	}
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/usage/dao/UsageVMInstanceDao.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/usage/dao/UsageVMInstanceDao.java b/engine/schema/src/com/cloud/usage/dao/UsageVMInstanceDao.java
new file mode 100644
index 0000000..67a24f3
--- /dev/null
+++ b/engine/schema/src/com/cloud/usage/dao/UsageVMInstanceDao.java
@@ -0,0 +1,29 @@
+// 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.dao;
+
+import java.util.Date;
+import java.util.List;
+
+import com.cloud.usage.UsageVMInstanceVO;
+import com.cloud.utils.db.GenericDao;
+
+public interface UsageVMInstanceDao extends GenericDao<UsageVMInstanceVO, Long> {
+    public void update(UsageVMInstanceVO instance);
+    public void delete(UsageVMInstanceVO instance);
+    public List<UsageVMInstanceVO> getUsageRecords(long userId, Date startDate, Date endDate);
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/usage/dao/UsageVMInstanceDaoImpl.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/usage/dao/UsageVMInstanceDaoImpl.java b/engine/schema/src/com/cloud/usage/dao/UsageVMInstanceDaoImpl.java
new file mode 100644
index 0000000..fc82754
--- /dev/null
+++ b/engine/schema/src/com/cloud/usage/dao/UsageVMInstanceDaoImpl.java
@@ -0,0 +1,137 @@
+// 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.dao;
+
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.TimeZone;
+
+import javax.ejb.Local;
+
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+import com.cloud.usage.UsageVMInstanceVO;
+import com.cloud.utils.DateUtil;
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.Transaction;
+
+@Component
+@Local(value={UsageVMInstanceDao.class})
+public class UsageVMInstanceDaoImpl extends GenericDaoBase<UsageVMInstanceVO, Long> implements UsageVMInstanceDao {
+	public static final Logger s_logger = Logger.getLogger(UsageVMInstanceDaoImpl.class.getName());
+	
+	protected static final String UPDATE_USAGE_INSTANCE_SQL =
+		"UPDATE usage_vm_instance SET end_date = ? "
+	+   "WHERE account_id = ? and vm_instance_id = ? and usage_type = ? and end_date IS NULL";
+    protected static final String DELETE_USAGE_INSTANCE_SQL =
+        "DELETE FROM usage_vm_instance WHERE account_id = ? and vm_instance_id = ? and usage_type = ?";
+    protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT usage_type, zone_id, account_id, vm_instance_id, vm_name, service_offering_id, template_id, hypervisor_type, start_date, end_date " +
+                                                                  "FROM usage_vm_instance " +
+                                                                  "WHERE account_id = ? AND ((end_date IS NULL) OR (start_date BETWEEN ? AND ?) OR " +
+                                                                  "      (end_date BETWEEN ? AND ?) OR ((start_date <= ?) AND (end_date >= ?)))";
+
+	public UsageVMInstanceDaoImpl() {}
+
+    public void update(UsageVMInstanceVO instance) {
+        Transaction txn = Transaction.open(Transaction.USAGE_DB);
+        PreparedStatement pstmt = null;
+        try {
+            txn.start();
+            String sql = UPDATE_USAGE_INSTANCE_SQL;
+            pstmt = txn.prepareAutoCloseStatement(sql);
+            pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), instance.getEndDate()));
+            pstmt.setLong(2, instance.getAccountId());
+            pstmt.setLong(3, instance.getVmInstanceId());
+            pstmt.setInt(4, instance.getUsageType());
+            pstmt.executeUpdate();
+            txn.commit();
+        } catch (Exception e) {
+            s_logger.warn(e);
+        } finally {
+            txn.close();
+        }
+    }
+
+    public void delete(UsageVMInstanceVO instance) {
+        Transaction txn = Transaction.open(Transaction.USAGE_DB);
+        PreparedStatement pstmt = null;
+        try {
+            txn.start();
+            String sql = DELETE_USAGE_INSTANCE_SQL;
+            pstmt = txn.prepareAutoCloseStatement(sql);
+            pstmt.setLong(1, instance.getAccountId());
+            pstmt.setLong(2, instance.getVmInstanceId());
+            pstmt.setInt(3, instance.getUsageType());
+            pstmt.executeUpdate();
+            txn.commit();
+        } catch (Exception ex) {
+        	txn.rollback();
+            s_logger.error("error deleting usage vm instance with vmId: " + instance.getVmInstanceId() + ", for account with id: " + instance.getAccountId());
+        } finally {
+            txn.close();
+        }
+    }
+
+    public List<UsageVMInstanceVO> getUsageRecords(long accountId, Date startDate, Date endDate) {
+        Transaction txn = Transaction.open(Transaction.USAGE_DB);
+        PreparedStatement pstmt = null;
+        List<UsageVMInstanceVO> usageInstances = new ArrayList<UsageVMInstanceVO>();
+        try {
+            String sql = GET_USAGE_RECORDS_BY_ACCOUNT;
+            pstmt = txn.prepareAutoCloseStatement(sql);
+            pstmt.setLong(1, accountId);
+            pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate));
+            pstmt.setString(3, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate));
+            pstmt.setString(4, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate));
+            pstmt.setString(5, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate));
+            pstmt.setString(6, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate));
+            pstmt.setString(7, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate));
+            ResultSet rs = pstmt.executeQuery();
+            while (rs.next()) {
+                int r_usageType = rs.getInt(1);
+                long r_zoneId = rs.getLong(2);
+                long r_accountId = rs.getLong(3);
+                long r_vmId = rs.getLong(4);
+                String r_vmName = rs.getString(5);
+                long r_soId = rs.getLong(6);
+                long r_tId = rs.getLong(7);
+                String hypervisorType = rs.getString(8);
+                String r_startDate = rs.getString(9);
+                String r_endDate = rs.getString(10);
+                Date instanceStartDate = null;
+                Date instanceEndDate = null;
+                if (r_startDate != null) {
+                    instanceStartDate = DateUtil.parseDateString(s_gmtTimeZone, r_startDate);
+                }
+                if (r_endDate != null) {
+                    instanceEndDate = DateUtil.parseDateString(s_gmtTimeZone, r_endDate);
+                }
+                UsageVMInstanceVO usageInstance = new UsageVMInstanceVO(r_usageType, r_zoneId, r_accountId, r_vmId, r_vmName, r_soId, r_tId, hypervisorType, instanceStartDate, instanceEndDate);
+                usageInstances.add(usageInstance);
+            }
+        } catch (Exception ex) {
+            s_logger.error("error retrieving usage vm instances for account id: " + accountId, ex);
+        } finally {
+            txn.close();
+        }
+        return usageInstances;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/usage/dao/UsageVPNUserDao.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/usage/dao/UsageVPNUserDao.java b/engine/schema/src/com/cloud/usage/dao/UsageVPNUserDao.java
new file mode 100644
index 0000000..8056d3d
--- /dev/null
+++ b/engine/schema/src/com/cloud/usage/dao/UsageVPNUserDao.java
@@ -0,0 +1,28 @@
+// 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.dao;
+
+import java.util.Date;
+import java.util.List;
+
+import com.cloud.usage.UsageVPNUserVO;
+import com.cloud.utils.db.GenericDao;
+
+public interface UsageVPNUserDao extends GenericDao<UsageVPNUserVO, Long> {
+	public void update(UsageVPNUserVO usage);
+	public List<UsageVPNUserVO> getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page);
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/usage/dao/UsageVPNUserDaoImpl.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/usage/dao/UsageVPNUserDaoImpl.java b/engine/schema/src/com/cloud/usage/dao/UsageVPNUserDaoImpl.java
new file mode 100644
index 0000000..d6bf13b
--- /dev/null
+++ b/engine/schema/src/com/cloud/usage/dao/UsageVPNUserDaoImpl.java
@@ -0,0 +1,150 @@
+// 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.dao;
+
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.TimeZone;
+
+import javax.ejb.Local;
+
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+import com.cloud.usage.UsageVPNUserVO;
+import com.cloud.utils.DateUtil;
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.Transaction;
+
+@Component
+@Local(value={UsageVPNUserDao.class})
+public class UsageVPNUserDaoImpl extends GenericDaoBase<UsageVPNUserVO, Long> implements UsageVPNUserDao {
+	public static final Logger s_logger = Logger.getLogger(UsageVPNUserDaoImpl.class.getName());
+
+	protected static final String UPDATE_DELETED = "UPDATE usage_vpn_user SET deleted = ? WHERE account_id = ? AND user_id = ? and deleted IS NULL";
+    protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT zone_id, account_id, domain_id, user_id, user_name, created, deleted " +
+                                                                 "FROM usage_vpn_user " +
+                                                                 "WHERE account_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " +
+                                                                 "      (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))";
+    protected static final String GET_USAGE_RECORDS_BY_DOMAIN = "SELECT zone_id, account_id, domain_id, user_id, user_name, created, deleted " +
+                                                                "FROM usage_vpn_user " +
+                                                                "WHERE domain_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " +
+                                                                "      (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))";
+    protected static final String GET_ALL_USAGE_RECORDS = "SELECT zone_id, account_id, domain_id, user_id, user_name, created, deleted " +
+                                                          "FROM usage_vpn_user " +
+                                                          "WHERE (deleted IS NULL) OR (created BETWEEN ? AND ?) OR " +
+                                                          "      (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?))";
+
+	public UsageVPNUserDaoImpl() {}
+
+	public void update(UsageVPNUserVO usage) {
+	    Transaction txn = Transaction.open(Transaction.USAGE_DB);
+		PreparedStatement pstmt = null;
+		try {
+		    txn.start();
+			if (usage.getDeleted() != null) {
+				pstmt = txn.prepareAutoCloseStatement(UPDATE_DELETED);
+				pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), usage.getDeleted()));
+				pstmt.setLong(2, usage.getAccountId());
+				pstmt.setLong(3, usage.getUserId());
+			}
+			pstmt.executeUpdate();
+			txn.commit();
+		} catch (Exception e) {
+			txn.rollback();
+			s_logger.warn("Error updating UsageVPNUserVO", e);
+		} finally {
+		    txn.close();
+		}
+	}
+
+    @Override
+	public List<UsageVPNUserVO> getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page) {
+        List<UsageVPNUserVO> usageRecords = new ArrayList<UsageVPNUserVO>();
+
+        Long param1 = null;
+        String sql = null;
+        if (accountId != null) {
+            sql = GET_USAGE_RECORDS_BY_ACCOUNT;
+            param1 = accountId;
+        } else if (domainId != null) {
+            sql = GET_USAGE_RECORDS_BY_DOMAIN;
+            param1 = domainId;
+        } else {
+            sql = GET_ALL_USAGE_RECORDS;
+        }
+
+        if (limit) {
+            int startIndex = 0;
+            if (page > 0) {
+                startIndex = 500 * (page-1);
+            }
+            sql += " LIMIT " + startIndex + ",500";
+        }
+
+        Transaction txn = Transaction.open(Transaction.USAGE_DB);
+        PreparedStatement pstmt = null;
+
+        try {
+            int i = 1;
+            pstmt = txn.prepareAutoCloseStatement(sql);
+            if (param1 != null) {
+                pstmt.setLong(i++, param1);
+            }
+            pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate));
+            pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate));
+            pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate));
+            pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate));
+            pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate));
+            pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate));
+
+            ResultSet rs = pstmt.executeQuery();
+            while (rs.next()) {
+                //zoneId, account_id, domain_id, user_id, user_name, created, deleted
+            	Long zoneId = Long.valueOf(rs.getLong(1));
+                Long acctId = Long.valueOf(rs.getLong(2));
+                Long dId = Long.valueOf(rs.getLong(3));
+                long userId = Long.valueOf(rs.getLong(4));
+                String userName = rs.getString(5);
+                Date createdDate = null;
+                Date deletedDate = null;
+                String createdTS = rs.getString(6);
+                String deletedTS = rs.getString(7);
+                
+
+                if (createdTS != null) {
+                	createdDate = DateUtil.parseDateString(s_gmtTimeZone, createdTS);
+                }
+                if (deletedTS != null) {
+                	deletedDate = DateUtil.parseDateString(s_gmtTimeZone, deletedTS);
+                }
+
+                usageRecords.add(new UsageVPNUserVO(zoneId, acctId, dId, userId, userName, createdDate, deletedDate));
+            }
+        } catch (Exception e) {
+            txn.rollback();
+            s_logger.warn("Error getting usage records", e);
+        } finally {
+            txn.close();
+        }
+
+        return usageRecords;
+	}
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/usage/dao/UsageVolumeDao.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/usage/dao/UsageVolumeDao.java b/engine/schema/src/com/cloud/usage/dao/UsageVolumeDao.java
new file mode 100644
index 0000000..00a8f4a
--- /dev/null
+++ b/engine/schema/src/com/cloud/usage/dao/UsageVolumeDao.java
@@ -0,0 +1,29 @@
+// 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.dao;
+
+import java.util.Date;
+import java.util.List;
+
+import com.cloud.usage.UsageVolumeVO;
+import com.cloud.utils.db.GenericDao;
+
+public interface UsageVolumeDao extends GenericDao<UsageVolumeVO, Long> {
+	public void removeBy(long userId, long id);
+	public void update(UsageVolumeVO usage);
+	public List<UsageVolumeVO> getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page);
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/usage/dao/UsageVolumeDaoImpl.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/usage/dao/UsageVolumeDaoImpl.java b/engine/schema/src/com/cloud/usage/dao/UsageVolumeDaoImpl.java
new file mode 100644
index 0000000..039d8f4
--- /dev/null
+++ b/engine/schema/src/com/cloud/usage/dao/UsageVolumeDaoImpl.java
@@ -0,0 +1,178 @@
+// 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.dao;
+
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.TimeZone;
+
+import javax.ejb.Local;
+
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+import com.cloud.usage.UsageVolumeVO;
+import com.cloud.utils.DateUtil;
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.Transaction;
+
+@Component
+@Local(value={UsageVolumeDao.class})
+public class UsageVolumeDaoImpl extends GenericDaoBase<UsageVolumeVO, Long> implements UsageVolumeDao {
+	public static final Logger s_logger = Logger.getLogger(UsageVolumeDaoImpl.class.getName());
+
+	protected static final String REMOVE_BY_USERID_VOLID = "DELETE FROM usage_volume WHERE account_id = ? AND id = ?";
+	protected static final String UPDATE_DELETED = "UPDATE usage_volume SET deleted = ? WHERE account_id = ? AND id = ? and deleted IS NULL";
+    protected static final String GET_USAGE_RECORDS_BY_ACCOUNT = "SELECT id, zone_id, account_id, domain_id, disk_offering_id, template_id, size, created, deleted " +
+                                                                 "FROM usage_volume " +
+                                                                 "WHERE account_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " +
+                                                                 "      (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))";
+    protected static final String GET_USAGE_RECORDS_BY_DOMAIN = "SELECT id, zone_id, account_id, domain_id, disk_offering_id, template_id, size, created, deleted " +
+                                                                "FROM usage_volume " +
+                                                                "WHERE domain_id = ? AND ((deleted IS NULL) OR (created BETWEEN ? AND ?) OR " +
+                                                                "      (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?)))";
+    protected static final String GET_ALL_USAGE_RECORDS = "SELECT id, zone_id, account_id, domain_id, disk_offering_id, template_id, size, created, deleted " +
+                                                          "FROM usage_volume " +
+                                                          "WHERE (deleted IS NULL) OR (created BETWEEN ? AND ?) OR " +
+                                                          "      (deleted BETWEEN ? AND ?) OR ((created <= ?) AND (deleted >= ?))";
+
+	public UsageVolumeDaoImpl() {}
+
+	public void removeBy(long accountId, long volId) {
+	    Transaction txn = Transaction.open(Transaction.USAGE_DB);
+		PreparedStatement pstmt = null;
+		try {
+		    txn.start();
+			String sql = REMOVE_BY_USERID_VOLID;
+			pstmt = txn.prepareAutoCloseStatement(sql);
+			pstmt.setLong(1, accountId);
+			pstmt.setLong(2, volId);
+			pstmt.executeUpdate();
+			txn.commit();
+		} catch (Exception e) {
+			txn.rollback();
+			s_logger.warn("Error removing usageVolumeVO", e);
+		} finally {
+		    txn.close();
+		}
+	}
+
+	public void update(UsageVolumeVO usage) {
+	    Transaction txn = Transaction.open(Transaction.USAGE_DB);
+		PreparedStatement pstmt = null;
+		try {
+		    txn.start();
+			if (usage.getDeleted() != null) {
+				pstmt = txn.prepareAutoCloseStatement(UPDATE_DELETED);
+				pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), usage.getDeleted()));
+				pstmt.setLong(2, usage.getAccountId());
+				pstmt.setLong(3, usage.getId());
+			}
+			pstmt.executeUpdate();
+			txn.commit();
+		} catch (Exception e) {
+			txn.rollback();
+			s_logger.warn("Error updating UsageVolumeVO", e);
+		} finally {
+		    txn.close();
+		}
+	}
+
+    @Override
+	public List<UsageVolumeVO> getUsageRecords(Long accountId, Long domainId, Date startDate, Date endDate, boolean limit, int page) {
+        List<UsageVolumeVO> usageRecords = new ArrayList<UsageVolumeVO>();
+
+        Long param1 = null;
+        String sql = null;
+        if (accountId != null) {
+            sql = GET_USAGE_RECORDS_BY_ACCOUNT;
+            param1 = accountId;
+        } else if (domainId != null) {
+            sql = GET_USAGE_RECORDS_BY_DOMAIN;
+            param1 = domainId;
+        } else {
+            sql = GET_ALL_USAGE_RECORDS;
+        }
+
+        if (limit) {
+            int startIndex = 0;
+            if (page > 0) {
+                startIndex = 500 * (page-1);
+            }
+            sql += " LIMIT " + startIndex + ",500";
+        }
+
+        Transaction txn = Transaction.open(Transaction.USAGE_DB);
+        PreparedStatement pstmt = null;
+
+        try {
+            int i = 1;
+            pstmt = txn.prepareAutoCloseStatement(sql);
+            if (param1 != null) {
+                pstmt.setLong(i++, param1);
+            }
+            pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate));
+            pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate));
+            pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate));
+            pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate));
+            pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), startDate));
+            pstmt.setString(i++, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), endDate));
+
+            ResultSet rs = pstmt.executeQuery();
+            while (rs.next()) {
+                //id, zoneId, account_id, domain_id, disk_offering_id, template_id created, deleted
+            	Long vId = Long.valueOf(rs.getLong(1));
+            	Long zoneId = Long.valueOf(rs.getLong(2));
+                Long acctId = Long.valueOf(rs.getLong(3));
+                Long dId = Long.valueOf(rs.getLong(4));
+                Long doId = Long.valueOf(rs.getLong(5));
+                if(doId == 0){
+                    doId = null;
+                }
+                Long tId = Long.valueOf(rs.getLong(6));
+                if(tId == 0){
+                    tId = null;
+                }
+                long size = Long.valueOf(rs.getLong(7));
+                Date createdDate = null;
+                Date deletedDate = null;
+                String createdTS = rs.getString(8);
+                String deletedTS = rs.getString(9);
+                
+
+                if (createdTS != null) {
+                	createdDate = DateUtil.parseDateString(s_gmtTimeZone, createdTS);
+                }
+                if (deletedTS != null) {
+                	deletedDate = DateUtil.parseDateString(s_gmtTimeZone, deletedTS);
+                }
+
+                usageRecords.add(new UsageVolumeVO(vId, zoneId, acctId, dId, doId, tId, size, createdDate, deletedDate));
+            }
+        } catch (Exception e) {
+            txn.rollback();
+            s_logger.warn("Error getting usage records", e);
+        } finally {
+            txn.close();
+        }
+
+        return usageRecords;
+	}
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/user/AccountDetailVO.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/user/AccountDetailVO.java b/engine/schema/src/com/cloud/user/AccountDetailVO.java
new file mode 100755
index 0000000..a8afadb
--- /dev/null
+++ b/engine/schema/src/com/cloud/user/AccountDetailVO.java
@@ -0,0 +1,75 @@
+// 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.user;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+import com.cloud.utils.db.Encrypt;
+import org.apache.cloudstack.api.InternalIdentity;
+
+@Entity
+@Table(name="account_details")
+public class AccountDetailVO implements InternalIdentity {
+    @Id
+    @GeneratedValue(strategy=GenerationType.IDENTITY)
+    @Column(name="id")
+    private long id;
+
+    @Column(name="account_id")
+    private long accountId;
+
+    @Column(name="name")
+    private String name;
+
+    @Encrypt
+    @Column(name="value")
+    private String value;
+
+    protected AccountDetailVO() {
+    }
+
+    public AccountDetailVO(long accountId, String name, String value) {
+        this.accountId = accountId;
+        this.name = name;
+        this.value = value;
+    }
+
+    public long getAccountId() {
+        return accountId;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public String getValue() {
+        return value;
+    }
+
+    public void setValue(String value) {
+        this.value = value;
+    }
+
+    public long getId() {
+        return id;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/user/AccountDetailsDao.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/user/AccountDetailsDao.java b/engine/schema/src/com/cloud/user/AccountDetailsDao.java
new file mode 100755
index 0000000..f2a1f0e
--- /dev/null
+++ b/engine/schema/src/com/cloud/user/AccountDetailsDao.java
@@ -0,0 +1,37 @@
+// 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.user;
+
+import java.util.Map;
+import com.cloud.utils.db.GenericDao;
+
+
+public interface AccountDetailsDao extends GenericDao<AccountDetailVO, Long> {
+    Map<String, String> findDetails(long accountId);
+    
+    void persist(long accountId, Map<String, String> details);
+    
+    AccountDetailVO findDetail(long accountId, String name);
+
+	void deleteDetails(long accountId);
+	
+	/*
+	 * For these existing entries, they will get updated. For these new entries,
+	 * they will get created 
+	 */
+	void update(long accountId, Map<String, String> details);
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/user/AccountDetailsDaoImpl.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/user/AccountDetailsDaoImpl.java b/engine/schema/src/com/cloud/user/AccountDetailsDaoImpl.java
new file mode 100755
index 0000000..c123f54
--- /dev/null
+++ b/engine/schema/src/com/cloud/user/AccountDetailsDaoImpl.java
@@ -0,0 +1,96 @@
+// 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.user;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.ejb.Local;
+
+import org.springframework.stereotype.Component;
+
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.db.SearchCriteria2;
+import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.SearchCriteria.Op;
+import com.cloud.utils.db.SearchCriteriaService;
+
+@Component
+@Local(value={AccountDetailsDao.class})
+public class AccountDetailsDaoImpl extends GenericDaoBase<AccountDetailVO, Long> implements AccountDetailsDao {
+	protected final SearchBuilder<AccountDetailVO> accountSearch;
+	
+	protected AccountDetailsDaoImpl() {
+		accountSearch = createSearchBuilder();
+		accountSearch.and("accountId", accountSearch.entity().getAccountId(), Op.EQ);
+		accountSearch.done();
+	}
+	
+	@Override
+	public Map<String, String> findDetails(long accountId) {
+		SearchCriteriaService<AccountDetailVO, AccountDetailVO> sc = SearchCriteria2.create(AccountDetailVO.class);
+		sc.addAnd(sc.getEntity().getAccountId(), Op.EQ, accountId);
+		List<AccountDetailVO> results = sc.list();
+		Map<String, String> details = new HashMap<String, String>(results.size());
+		for (AccountDetailVO r : results) {
+			details.put(r.getName(), r.getValue());
+		}
+		return details;
+	}
+
+	@Override
+	public void persist(long accountId, Map<String, String> details) {
+        Transaction txn = Transaction.currentTxn();
+        txn.start();
+        SearchCriteria<AccountDetailVO> sc = accountSearch.create();
+        sc.setParameters("accountId", accountId);
+        expunge(sc);
+        for (Map.Entry<String, String> detail : details.entrySet()) {
+        	AccountDetailVO vo = new AccountDetailVO(accountId, detail.getKey(), detail.getValue());
+        	persist(vo);
+        }
+        txn.commit();
+	}
+
+	@Override
+	public AccountDetailVO findDetail(long accountId, String name) {
+		SearchCriteriaService<AccountDetailVO, AccountDetailVO> sc = SearchCriteria2.create(AccountDetailVO.class);
+		sc.addAnd(sc.getEntity().getAccountId(), Op.EQ, accountId);
+		sc.addAnd(sc.getEntity().getName(), Op.EQ, name);
+		return sc.find();
+	}
+
+	@Override
+	public void deleteDetails(long accountId) {
+		SearchCriteria<AccountDetailVO> sc = accountSearch.create();
+        sc.setParameters("accountId", accountId);
+        List<AccountDetailVO> results = search(sc, null);
+        for (AccountDetailVO result : results) {
+        	remove(result.getId());
+        }
+	}
+
+	@Override
+    public void update(long accountId, Map<String, String> details) {
+	    Map<String, String> oldDetails = findDetails(accountId);
+	    oldDetails.putAll(details);
+	    persist(accountId, oldDetails);
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/user/dao/AccountDao.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/user/dao/AccountDao.java b/engine/schema/src/com/cloud/user/dao/AccountDao.java
new file mode 100644
index 0000000..3b7fa66
--- /dev/null
+++ b/engine/schema/src/com/cloud/user/dao/AccountDao.java
@@ -0,0 +1,52 @@
+// 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.user.dao;
+
+import java.util.Date;
+import java.util.List;
+
+import com.cloud.user.Account;
+import com.cloud.user.AccountVO;
+import com.cloud.user.User;
+import com.cloud.utils.Pair;
+import com.cloud.utils.db.Filter;
+import com.cloud.utils.db.GenericDao;
+
+public interface AccountDao extends GenericDao<AccountVO, Long> {
+    Pair<User, Account> findUserAccountByApiKey(String apiKey);
+    List<AccountVO> findAccountsLike(String accountName);
+    List<AccountVO> findActiveAccounts(Long maxAccountId, Filter filter);
+    List<AccountVO> findRecentlyDeletedAccounts(Long maxAccountId, Date earliestRemovedDate, Filter filter);
+    List<AccountVO> findNewAccounts(Long minAccountId, Filter filter);
+    List<AccountVO> findCleanupsForRemovedAccounts(Long domainId);
+    List<AccountVO> findActiveAccountsForDomain(Long domain);     
+    void markForCleanup(long accountId);
+    List<AccountVO> listAccounts(String accountName, Long domainId, Filter filter);
+    List<AccountVO> findCleanupsForDisabledAccounts();
+    
+    //return account only in enabled state
+    Account findEnabledAccount(String accountName, Long domainId);
+    Account findEnabledNonProjectAccount(String accountName, Long domainId);
+    
+    //returns account even when it's removed
+    Account findAccountIncludingRemoved(String accountName, Long domainId);
+    Account findNonProjectAccountIncludingRemoved(String accountName, Long domainId);
+    
+    //returns only non-removed account
+    Account findActiveAccount(String accountName, Long domainId);
+    Account findActiveNonProjectAccount(String accountName, Long domainId);
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/user/dao/AccountDaoImpl.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/user/dao/AccountDaoImpl.java b/engine/schema/src/com/cloud/user/dao/AccountDaoImpl.java
new file mode 100755
index 0000000..892fdcd
--- /dev/null
+++ b/engine/schema/src/com/cloud/user/dao/AccountDaoImpl.java
@@ -0,0 +1,267 @@
+// 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.user.dao;
+
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.util.Date;
+import java.util.List;
+
+import javax.ejb.Local;
+
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+import com.cloud.user.Account;
+import com.cloud.user.Account.State;
+import com.cloud.user.AccountVO;
+import com.cloud.user.User;
+import com.cloud.user.UserVO;
+import com.cloud.utils.Pair;
+import com.cloud.utils.crypt.DBEncryptionUtil;
+import com.cloud.utils.db.Filter;
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.db.Transaction;
+
+@Component
+@Local(value={AccountDao.class})
+public class AccountDaoImpl extends GenericDaoBase<AccountVO, Long> implements AccountDao {
+    private static final Logger s_logger = Logger.getLogger(AccountDaoImpl.class);
+    private final String FIND_USER_ACCOUNT_BY_API_KEY = "SELECT u.id, u.username, u.account_id, u.secret_key, u.state, " +
+    		                                      "a.id, a.account_name, a.type, a.domain_id, a.state " +
+    		                                      "FROM `cloud`.`user` u, `cloud`.`account` a " +
+    		                                      "WHERE u.account_id = a.id AND u.api_key = ? and u.removed IS NULL";
+    
+    protected final SearchBuilder<AccountVO> AllFieldsSearch;
+    protected final SearchBuilder<AccountVO> AccountTypeSearch;
+    protected final SearchBuilder<AccountVO> DomainAccountsSearch;
+    protected final SearchBuilder<AccountVO> CleanupForRemovedAccountsSearch;
+    protected final SearchBuilder<AccountVO> CleanupForDisabledAccountsSearch;
+    protected final SearchBuilder<AccountVO> NonProjectAccountSearch;
+    
+    public AccountDaoImpl() {
+        AllFieldsSearch = createSearchBuilder();
+        AllFieldsSearch.and("accountName", AllFieldsSearch.entity().getAccountName(), SearchCriteria.Op.EQ);
+        AllFieldsSearch.and("domainId", AllFieldsSearch.entity().getDomainId(), SearchCriteria.Op.EQ);
+        AllFieldsSearch.and("state", AllFieldsSearch.entity().getState(), SearchCriteria.Op.EQ);
+        AllFieldsSearch.and("type", AllFieldsSearch.entity().getType(), SearchCriteria.Op.EQ);
+        AllFieldsSearch.done();
+        
+        AccountTypeSearch = createSearchBuilder();
+        AccountTypeSearch.and("domainId", AccountTypeSearch.entity().getDomainId(), SearchCriteria.Op.EQ);
+        AccountTypeSearch.and("type", AccountTypeSearch.entity().getType(), SearchCriteria.Op.EQ);
+        AccountTypeSearch.done();
+
+        DomainAccountsSearch = createSearchBuilder();
+        DomainAccountsSearch.and("domainId", DomainAccountsSearch.entity().getDomainId(), SearchCriteria.Op.EQ);
+        DomainAccountsSearch.and("removed", DomainAccountsSearch.entity().getRemoved(), SearchCriteria.Op.NULL);
+        DomainAccountsSearch.done();
+        
+        CleanupForRemovedAccountsSearch = createSearchBuilder();
+        CleanupForRemovedAccountsSearch.and("cleanup", CleanupForRemovedAccountsSearch.entity().getNeedsCleanup(), SearchCriteria.Op.EQ);
+        CleanupForRemovedAccountsSearch.and("removed", CleanupForRemovedAccountsSearch.entity().getRemoved(), SearchCriteria.Op.NNULL);
+        CleanupForRemovedAccountsSearch.and("domainid", CleanupForRemovedAccountsSearch.entity().getDomainId(), SearchCriteria.Op.EQ);
+        CleanupForRemovedAccountsSearch.done();
+        
+        CleanupForDisabledAccountsSearch = createSearchBuilder();
+        CleanupForDisabledAccountsSearch.and("cleanup", CleanupForDisabledAccountsSearch.entity().getNeedsCleanup(), SearchCriteria.Op.EQ);
+        CleanupForDisabledAccountsSearch.and("removed", CleanupForDisabledAccountsSearch.entity().getRemoved(), SearchCriteria.Op.NULL);
+        CleanupForDisabledAccountsSearch.and("state", CleanupForDisabledAccountsSearch.entity().getState(), SearchCriteria.Op.EQ);
+        CleanupForDisabledAccountsSearch.done();
+        
+        NonProjectAccountSearch = createSearchBuilder();
+        NonProjectAccountSearch.and("accountName", NonProjectAccountSearch.entity().getAccountName(), SearchCriteria.Op.EQ);
+        NonProjectAccountSearch.and("domainId", NonProjectAccountSearch.entity().getDomainId(), SearchCriteria.Op.EQ);
+        NonProjectAccountSearch.and("state", NonProjectAccountSearch.entity().getState(), SearchCriteria.Op.EQ);
+        NonProjectAccountSearch.and("type", NonProjectAccountSearch.entity().getType(), SearchCriteria.Op.NEQ);
+        NonProjectAccountSearch.done();
+    }
+    
+    @Override
+    public List<AccountVO> findCleanupsForRemovedAccounts(Long domainId) {
+    	SearchCriteria<AccountVO> sc = CleanupForRemovedAccountsSearch.create();
+    	sc.setParameters("cleanup", true);
+    	
+    	if (domainId != null) {
+    	    sc.setParameters("domainid", domainId);
+    	}
+    	
+    	return searchIncludingRemoved(sc, null, null, false);
+    }
+    
+    @Override
+    public List<AccountVO> findCleanupsForDisabledAccounts() {
+        SearchCriteria<AccountVO> sc = CleanupForDisabledAccountsSearch.create();
+        sc.setParameters("cleanup", true);
+        sc.setParameters("state", State.disabled);
+        
+        return listBy(sc);
+    }
+    
+    @Override
+    public Pair<User, Account> findUserAccountByApiKey(String apiKey) {
+        Transaction txn = Transaction.currentTxn();
+        PreparedStatement pstmt = null;
+        Pair<User, Account> userAcctPair = null;
+        try {
+            String sql = FIND_USER_ACCOUNT_BY_API_KEY;
+            pstmt = txn.prepareAutoCloseStatement(sql);
+            pstmt.setString(1, apiKey);
+            ResultSet rs = pstmt.executeQuery();
+            // TODO:  make sure we don't have more than 1 result?  ApiKey had better be unique
+            if (rs.next()) {
+                User u = new UserVO(rs.getLong(1));
+                u.setUsername(rs.getString(2));
+                u.setAccountId(rs.getLong(3));
+                u.setSecretKey(DBEncryptionUtil.decrypt(rs.getString(4)));
+                u.setState(State.valueOf(rs.getString(5)));
+
+                AccountVO a = new AccountVO(rs.getLong(6));
+                a.setAccountName(rs.getString(7));
+                a.setType(rs.getShort(8));
+                a.setDomainId(rs.getLong(9));
+                a.setState(State.valueOf(rs.getString(10)));
+
+                userAcctPair = new Pair<User, Account>(u, a);
+            }
+        } catch (Exception e) {
+            s_logger.warn("Exception finding user/acct by api key: " + apiKey, e);
+        }
+        return userAcctPair;
+    }
+
+    @Override
+    public List<AccountVO> findAccountsLike(String accountName) {
+        SearchCriteria<AccountVO> sc = createSearchCriteria();
+        sc.addAnd("accountName", SearchCriteria.Op.LIKE, "%"+accountName+"%");
+        return listBy(sc);
+    }
+
+    @Override
+    public Account findEnabledAccount(String accountName, Long domainId) {
+        SearchCriteria<AccountVO> sc = AllFieldsSearch.create("accountName", accountName);
+        sc.setParameters("domainId",domainId);
+        sc.setParameters("state", State.enabled);
+        return findOneBy(sc);
+    }
+    
+    @Override
+    public Account findEnabledNonProjectAccount(String accountName, Long domainId) {
+        SearchCriteria<AccountVO> sc = NonProjectAccountSearch.create("accountName", accountName);
+        sc.setParameters("domainId", domainId);
+        sc.setParameters("state", State.enabled);
+        sc.setParameters("type", Account.ACCOUNT_TYPE_PROJECT);
+        return findOneBy(sc);
+    }
+
+	@Override
+	public Account findActiveAccount(String accountName, Long domainId) {
+        SearchCriteria<AccountVO> sc = AllFieldsSearch.create("accountName", accountName);
+        sc.setParameters("domainId", domainId);
+        return findOneBy(sc);
+    }
+	
+	@Override
+	public Account findActiveNonProjectAccount(String accountName, Long domainId) {
+        SearchCriteria<AccountVO> sc = NonProjectAccountSearch.create("accountName", accountName);
+        sc.setParameters("domainId", domainId);
+        sc.setParameters("type", Account.ACCOUNT_TYPE_PROJECT);
+        return findOneBy(sc);
+    }
+
+    @Override
+    public Account findAccountIncludingRemoved(String accountName, Long domainId) {
+        SearchCriteria<AccountVO> sc = AllFieldsSearch.create("accountName", accountName);
+        sc.setParameters("domainId", domainId);
+        return findOneIncludingRemovedBy(sc);
+    }
+    
+    @Override
+    public Account findNonProjectAccountIncludingRemoved(String accountName, Long domainId) {
+        SearchCriteria<AccountVO> sc = NonProjectAccountSearch.create("accountName", accountName);
+        sc.setParameters("domainId", domainId);
+        sc.setParameters("type", Account.ACCOUNT_TYPE_PROJECT);
+        return findOneIncludingRemovedBy(sc);
+    }
+    
+    @Override
+    public List<AccountVO> listAccounts(String accountName, Long domainId, Filter filter) {
+        SearchCriteria<AccountVO> sc = AllFieldsSearch.create("accountName", accountName);
+        sc.setParameters("domainId", domainId);
+        return listIncludingRemovedBy(sc, filter);
+    }
+
+    @Override
+    public List<AccountVO> findActiveAccounts(Long maxAccountId, Filter filter) {
+        if (maxAccountId == null) {
+            return null;
+        }
+
+        SearchCriteria<AccountVO> sc = createSearchCriteria();
+        sc.addAnd("id", SearchCriteria.Op.LTEQ, maxAccountId);
+
+        return listBy(sc, filter);
+    }
+
+    @Override
+    public List<AccountVO> findRecentlyDeletedAccounts(Long maxAccountId, Date earliestRemovedDate, Filter filter) {
+        if (earliestRemovedDate == null) {
+            return null;
+        }
+        SearchCriteria<AccountVO> sc = createSearchCriteria();
+        if (maxAccountId != null) {
+            sc.addAnd("id", SearchCriteria.Op.LTEQ, maxAccountId);
+        }
+        sc.addAnd("removed", SearchCriteria.Op.NNULL);
+        sc.addAnd("removed", SearchCriteria.Op.GTEQ, earliestRemovedDate);
+
+        return listIncludingRemovedBy(sc, filter);
+    }
+
+    @Override
+    public List<AccountVO> findNewAccounts(Long minAccountId, Filter filter) {
+        if (minAccountId == null) {
+            return null;
+        }
+
+        SearchCriteria<AccountVO> sc = createSearchCriteria();
+        sc.addAnd("id", SearchCriteria.Op.GT, minAccountId);
+
+        return listIncludingRemovedBy(sc, filter);
+    }
+
+	@Override
+	public List<AccountVO> findActiveAccountsForDomain(Long domain) {
+        SearchCriteria<AccountVO> sc = DomainAccountsSearch.create();
+        sc.setParameters("domainId", domain);
+		return listBy(sc);
+	}
+	
+	@Override
+	public void markForCleanup(long accountId) {
+		AccountVO account = findByIdIncludingRemoved(accountId);
+		if (!account.getNeedsCleanup()) {
+			account.setNeedsCleanup(true);
+        	if (!update(accountId, account)) {
+        	    s_logger.warn("Failed to mark account id=" + accountId + " for cleanup");
+        	}
+		}
+	}
+	
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/user/dao/SSHKeyPairDao.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/user/dao/SSHKeyPairDao.java b/engine/schema/src/com/cloud/user/dao/SSHKeyPairDao.java
new file mode 100644
index 0000000..b1833bf
--- /dev/null
+++ b/engine/schema/src/com/cloud/user/dao/SSHKeyPairDao.java
@@ -0,0 +1,38 @@
+// 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.user.dao;
+
+import java.util.List;
+
+import com.cloud.user.SSHKeyPairVO;
+import com.cloud.utils.db.GenericDao;
+
+public interface SSHKeyPairDao extends GenericDao<SSHKeyPairVO, Long> {
+
+	public List<SSHKeyPairVO> listKeyPairs(long accountId, long domainId);
+	
+	public List<SSHKeyPairVO> listKeyPairsByName(long accountId, long domainId, String name);
+
+	public List<SSHKeyPairVO> listKeyPairsByFingerprint(long accountId, long domainId, String fingerprint);
+	
+	public SSHKeyPairVO findByName(long accountId, long domainId, String name);
+
+	public SSHKeyPairVO findByPublicKey(String publicKey);
+
+	public boolean deleteByName(long accountId, long domainId, String name);
+
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/user/dao/SSHKeyPairDaoImpl.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/user/dao/SSHKeyPairDaoImpl.java b/engine/schema/src/com/cloud/user/dao/SSHKeyPairDaoImpl.java
new file mode 100644
index 0000000..fbed8bf
--- /dev/null
+++ b/engine/schema/src/com/cloud/user/dao/SSHKeyPairDaoImpl.java
@@ -0,0 +1,85 @@
+// 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.user.dao;
+
+import java.util.List;
+
+import javax.ejb.Local;
+
+import org.springframework.stereotype.Component;
+
+import com.cloud.user.SSHKeyPairVO;
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.SearchCriteria;
+
+@Component
+@Local(value={SSHKeyPairDao.class})
+public class SSHKeyPairDaoImpl extends GenericDaoBase<SSHKeyPairVO, Long> implements SSHKeyPairDao {
+
+	@Override
+	public List<SSHKeyPairVO> listKeyPairs(long accountId, long domainId) {
+		SearchCriteria<SSHKeyPairVO> sc = createSearchCriteria();
+        sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId);
+        sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
+		return listBy(sc);
+	}
+	
+	@Override 
+	public List<SSHKeyPairVO> listKeyPairsByName(long accountId, long domainId, String name) {
+		SearchCriteria<SSHKeyPairVO> sc = createSearchCriteria();
+        sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId);
+        sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
+        sc.addAnd("name", SearchCriteria.Op.EQ, name);
+		return listBy(sc);
+	}
+	
+	@Override 
+	public List<SSHKeyPairVO> listKeyPairsByFingerprint(long accountId, long domainId, String fingerprint) {
+		SearchCriteria<SSHKeyPairVO> sc = createSearchCriteria();
+        sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId);
+        sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
+        sc.addAnd("fingerprint", SearchCriteria.Op.EQ, fingerprint);
+		return listBy(sc);
+	}
+	
+	@Override
+	public SSHKeyPairVO findByName(long accountId, long domainId, String name) {
+		SearchCriteria<SSHKeyPairVO> sc = createSearchCriteria();
+        sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId);
+        sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
+		sc.addAnd("name", SearchCriteria.Op.EQ, name);
+		return findOneBy(sc);
+	}
+
+    @Override
+    public SSHKeyPairVO findByPublicKey(String publicKey) {
+        SearchCriteria<SSHKeyPairVO> sc = createSearchCriteria();
+        sc.addAnd("publicKey", SearchCriteria.Op.EQ, publicKey);
+        return findOneBy(sc);
+    }
+
+	@Override
+	public boolean deleteByName(long accountId, long domainId, String name) {
+		SSHKeyPairVO pair = findByName(accountId, domainId, name);
+		if (pair == null) 
+			return false;
+		
+		expunge(pair.getId());
+		return true;
+	}
+		
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/user/dao/UserAccountDao.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/user/dao/UserAccountDao.java b/engine/schema/src/com/cloud/user/dao/UserAccountDao.java
new file mode 100644
index 0000000..eb4e0cd
--- /dev/null
+++ b/engine/schema/src/com/cloud/user/dao/UserAccountDao.java
@@ -0,0 +1,27 @@
+// 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.user.dao;
+
+import com.cloud.user.UserAccount;
+import com.cloud.user.UserAccountVO;
+import com.cloud.utils.db.GenericDao;
+
+public interface UserAccountDao extends GenericDao<UserAccountVO, Long> {
+    UserAccount getUserAccount(String username, Long domainId);
+    boolean validateUsernameInDomain(String username, Long domainId);
+    UserAccount getUserByApiKey(String apiKey);
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/user/dao/UserAccountDaoImpl.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/user/dao/UserAccountDaoImpl.java b/engine/schema/src/com/cloud/user/dao/UserAccountDaoImpl.java
new file mode 100644
index 0000000..8bb822a
--- /dev/null
+++ b/engine/schema/src/com/cloud/user/dao/UserAccountDaoImpl.java
@@ -0,0 +1,69 @@
+// 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.user.dao;
+
+import javax.ejb.Local;
+
+import org.springframework.stereotype.Component;
+
+import com.cloud.user.UserAccount;
+import com.cloud.user.UserAccountVO;
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+
+@Component
+@Local(value={UserAccountDao.class})
+public class UserAccountDaoImpl extends GenericDaoBase<UserAccountVO, Long> implements UserAccountDao {
+	
+	protected final SearchBuilder<UserAccountVO> userAccountSearch;
+	
+    public UserAccountDaoImpl() {
+    	userAccountSearch = createSearchBuilder();
+    	userAccountSearch.and("apiKey", userAccountSearch.entity().getApiKey(), SearchCriteria.Op.EQ);
+        userAccountSearch.done();
+    }
+	
+    @Override
+    public UserAccount getUserAccount(String username, Long domainId) {
+        if ((username == null) || (domainId == null)) {
+            return null;
+        }
+
+        SearchCriteria<UserAccountVO> sc = createSearchCriteria();
+        sc.addAnd("username", SearchCriteria.Op.EQ, username);
+        sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
+        return findOneBy(sc);
+    }
+
+    @Override
+    public boolean validateUsernameInDomain(String username, Long domainId) {
+        UserAccount userAcct = getUserAccount(username, domainId);
+        if (userAcct == null) {
+            return true;
+        }
+        return false;
+    }
+
+	@Override
+	public UserAccount getUserByApiKey(String apiKey) {
+		SearchCriteria<UserAccountVO> sc = userAccountSearch.create();
+		sc.setParameters("apiKey",apiKey);
+		return findOneBy(sc);
+	}
+	
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/user/dao/UserDao.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/user/dao/UserDao.java b/engine/schema/src/com/cloud/user/dao/UserDao.java
new file mode 100644
index 0000000..e910b73
--- /dev/null
+++ b/engine/schema/src/com/cloud/user/dao/UserDao.java
@@ -0,0 +1,52 @@
+// 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.user.dao;
+
+import java.util.List;
+
+import com.cloud.user.UserVO;
+import com.cloud.utils.db.GenericDao;
+
+
+/*
+ * Data Access Object for user table
+ */
+public interface UserDao extends GenericDao<UserVO, Long>{
+	UserVO getUser(String username, String password);
+	UserVO getUser(String username);
+	UserVO getUser(long userId);
+	List<UserVO> findUsersLike(String username);
+	
+	List<UserVO> listByAccount(long accountId);
+
+	/**
+	 * Finds a user based on the secret key provided.
+	 * @param secretKey
+	 * @return
+	 */
+	UserVO findUserBySecretKey(String secretKey);
+	
+	/**
+	 * Finds a user based on the registration token provided.
+	 * @param registrationToken
+	 * @return
+	 */
+	UserVO findUserByRegistrationToken(String registrationToken);
+	
+	List<UserVO> findUsersByName(String username);
+	
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/user/dao/UserDaoImpl.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/user/dao/UserDaoImpl.java b/engine/schema/src/com/cloud/user/dao/UserDaoImpl.java
new file mode 100644
index 0000000..4124a6a
--- /dev/null
+++ b/engine/schema/src/com/cloud/user/dao/UserDaoImpl.java
@@ -0,0 +1,131 @@
+// 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.user.dao;
+
+import java.util.List;
+
+import javax.ejb.Local;
+
+import org.springframework.stereotype.Component;
+
+import com.cloud.user.UserVO;
+import com.cloud.utils.db.DB;
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+
+@Component
+@Local(value={UserDao.class})
+@DB
+public class UserDaoImpl extends GenericDaoBase<UserVO, Long> implements UserDao {
+    protected SearchBuilder<UserVO> UsernamePasswordSearch;
+    protected SearchBuilder<UserVO> UsernameSearch;
+    protected SearchBuilder<UserVO> UsernameLikeSearch;
+    protected SearchBuilder<UserVO> UserIdSearch;
+    protected SearchBuilder<UserVO> AccountIdSearch;
+    protected SearchBuilder<UserVO> SecretKeySearch;
+    protected SearchBuilder<UserVO> RegistrationTokenSearch;
+    
+    protected UserDaoImpl () {
+    	UsernameSearch = createSearchBuilder();
+    	UsernameSearch.and("username", UsernameSearch.entity().getUsername(), SearchCriteria.Op.EQ);
+    	UsernameSearch.done();
+    	
+        UsernameLikeSearch = createSearchBuilder();
+        UsernameLikeSearch.and("username", UsernameLikeSearch.entity().getUsername(), SearchCriteria.Op.LIKE);
+        UsernameLikeSearch.done();
+        
+        AccountIdSearch = createSearchBuilder();
+        AccountIdSearch.and("account", AccountIdSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
+        AccountIdSearch.done();
+        
+        UsernamePasswordSearch = createSearchBuilder();
+        UsernamePasswordSearch.and("username", UsernamePasswordSearch.entity().getUsername(), SearchCriteria.Op.EQ);
+        UsernamePasswordSearch.and("password", UsernamePasswordSearch.entity().getPassword(), SearchCriteria.Op.EQ);
+        UsernamePasswordSearch.done();
+
+        UserIdSearch = createSearchBuilder();
+        UserIdSearch.and("id", UserIdSearch.entity().getId(), SearchCriteria.Op.EQ);
+        UserIdSearch.done();
+
+        SecretKeySearch = createSearchBuilder();
+        SecretKeySearch.and("secretKey", SecretKeySearch.entity().getSecretKey(), SearchCriteria.Op.EQ);
+        SecretKeySearch.done();
+        
+        RegistrationTokenSearch = createSearchBuilder();
+        RegistrationTokenSearch.and("registrationToken", RegistrationTokenSearch.entity().getRegistrationToken(), SearchCriteria.Op.EQ);
+        RegistrationTokenSearch.done();
+    }
+
+	@Override
+	public UserVO getUser(String username, String password) {
+	    SearchCriteria<UserVO> sc = UsernamePasswordSearch.create();
+	    sc.setParameters("username", username);
+	    sc.setParameters("password", password);
+	    return findOneBy(sc);
+	}
+	
+	@Override
+    public List<UserVO> listByAccount(long accountId) {
+	    SearchCriteria<UserVO> sc = AccountIdSearch.create();
+	    sc.setParameters("account", accountId);
+	    return listBy(sc, null);
+	}
+
+	@Override
+	public UserVO getUser(String username) {
+	    SearchCriteria<UserVO> sc = UsernameSearch.create();
+	    sc.setParameters("username", username);
+	    return findOneBy(sc);
+	}
+
+    @Override
+    public UserVO getUser(long userId) {
+        SearchCriteria<UserVO> sc = UserIdSearch.create();
+        sc.setParameters("id", userId);
+        return findOneBy(sc);
+    }
+
+	@Override
+	public List<UserVO> findUsersLike(String username) {
+        SearchCriteria<UserVO> sc = UsernameLikeSearch.create();
+        sc.setParameters("username", "%" + username + "%");
+        return listBy(sc);
+    }
+	
+    @Override
+    public UserVO findUserBySecretKey(String secretKey) {
+        SearchCriteria<UserVO> sc = SecretKeySearch.create();
+        sc.setParameters("secretKey", secretKey);
+        return findOneBy(sc);
+    }
+
+	@Override
+	public UserVO findUserByRegistrationToken(String registrationToken) {
+        SearchCriteria<UserVO> sc = RegistrationTokenSearch.create();
+        sc.setParameters("registrationToken", registrationToken);
+        return findOneBy(sc);
+	}
+	
+	@Override
+	public List<UserVO> findUsersByName(String username) {
+	    SearchCriteria<UserVO> sc = UsernameSearch.create();
+        sc.setParameters("username", username);
+        return listBy(sc);
+	}
+	
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/user/dao/UserStatisticsDao.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/user/dao/UserStatisticsDao.java b/engine/schema/src/com/cloud/user/dao/UserStatisticsDao.java
new file mode 100644
index 0000000..eb175ca
--- /dev/null
+++ b/engine/schema/src/com/cloud/user/dao/UserStatisticsDao.java
@@ -0,0 +1,35 @@
+// 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.user.dao;
+
+import java.util.Date;
+import java.util.List;
+
+import com.cloud.user.UserStatisticsVO;
+import com.cloud.utils.db.GenericDao;
+
+public interface UserStatisticsDao extends GenericDao<UserStatisticsVO, Long> {
+    UserStatisticsVO findBy(long accountId, long dcId, long networkId, String publicIp, Long deviceId, String deviceType);
+
+    UserStatisticsVO lock(long accountId, long dcId, long networkId, String publicIp, Long hostId, String deviceType);
+
+    List<UserStatisticsVO> listBy(long accountId);
+
+    List<UserStatisticsVO> listActiveAndRecentlyDeleted(Date minRemovedDate, int startIndex, int limit);
+
+	List<UserStatisticsVO> listUpdatedStats();
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/user/dao/UserStatisticsDaoImpl.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/user/dao/UserStatisticsDaoImpl.java b/engine/schema/src/com/cloud/user/dao/UserStatisticsDaoImpl.java
new file mode 100644
index 0000000..4a1a51c
--- /dev/null
+++ b/engine/schema/src/com/cloud/user/dao/UserStatisticsDaoImpl.java
@@ -0,0 +1,137 @@
+// 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.user.dao;
+
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.TimeZone;
+
+import javax.ejb.Local;
+
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+import com.cloud.user.UserStatisticsVO;
+import com.cloud.utils.DateUtil;
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.db.Transaction;
+
+@Component
+@Local(value={UserStatisticsDao.class})
+public class UserStatisticsDaoImpl extends GenericDaoBase<UserStatisticsVO, Long> implements UserStatisticsDao {
+    private static final Logger s_logger = Logger.getLogger(UserStatisticsDaoImpl.class);
+    private static final String ACTIVE_AND_RECENTLY_DELETED_SEARCH = "SELECT us.id, us.data_center_id, us.account_id, us.public_ip_address, us.device_id, us.device_type, us.network_id, us.agg_bytes_received, us.agg_bytes_sent " +
+                                                                     "FROM user_statistics us, account a " +
+                                                                     "WHERE us.account_id = a.id AND (a.removed IS NULL OR a.removed >= ?) " +
+                                                                     "ORDER BY us.id";
+    private static final String UPDATED_STATS_SEARCH = "SELECT id, current_bytes_received, current_bytes_sent, net_bytes_received, net_bytes_sent, agg_bytes_received, agg_bytes_sent from  user_statistics " +
+                                                                    "where (agg_bytes_received < net_bytes_received + current_bytes_received) OR (agg_bytes_sent < net_bytes_sent + current_bytes_sent)";
+    private final SearchBuilder<UserStatisticsVO> AllFieldsSearch;
+    private final SearchBuilder<UserStatisticsVO> AccountSearch;
+
+
+    public UserStatisticsDaoImpl() {
+        AccountSearch = createSearchBuilder();
+        AccountSearch.and("account", AccountSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
+        AccountSearch.done();
+
+        AllFieldsSearch = createSearchBuilder();
+        AllFieldsSearch.and("account", AllFieldsSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
+        AllFieldsSearch.and("dc", AllFieldsSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
+        AllFieldsSearch.and("network", AllFieldsSearch.entity().getNetworkId(), SearchCriteria.Op.EQ);
+        AllFieldsSearch.and("ip", AllFieldsSearch.entity().getPublicIpAddress(), SearchCriteria.Op.EQ);
+        AllFieldsSearch.and("device", AllFieldsSearch.entity().getDeviceId(), SearchCriteria.Op.EQ);
+        AllFieldsSearch.and("deviceType", AllFieldsSearch.entity().getDeviceType(), SearchCriteria.Op.EQ);        
+        AllFieldsSearch.done();
+    }
+
+    @Override
+    public UserStatisticsVO findBy(long accountId, long dcId, long networkId, String publicIp, Long deviceId, String deviceType) {
+        SearchCriteria<UserStatisticsVO> sc = AllFieldsSearch.create();
+        sc.setParameters("account", accountId);
+        sc.setParameters("dc", dcId);
+        sc.setParameters("network", networkId);
+        sc.setParameters("ip", publicIp);
+        sc.setParameters("device", deviceId);
+        sc.setParameters("deviceType", deviceType);        
+        return findOneBy(sc);
+    }
+
+    @Override
+    public UserStatisticsVO lock(long accountId, long dcId, long networkId, String publicIp, Long deviceId, String deviceType) {
+        SearchCriteria<UserStatisticsVO> sc = AllFieldsSearch.create();
+        sc.setParameters("account", accountId);
+        sc.setParameters("dc", dcId);
+        sc.setParameters("network", networkId);
+        sc.setParameters("ip", publicIp);
+        sc.setParameters("device", deviceId);
+        sc.setParameters("deviceType", deviceType);        
+        return lockOneRandomRow(sc, true);
+    }
+
+    @Override
+    public List<UserStatisticsVO> listBy(long accountId) {
+        SearchCriteria<UserStatisticsVO> sc = AccountSearch.create();
+        sc.setParameters("account", accountId);
+        return search(sc, null);
+    }
+
+    @Override
+    public List<UserStatisticsVO> listActiveAndRecentlyDeleted(Date minRemovedDate, int startIndex, int limit) {
+        List<UserStatisticsVO> userStats = new ArrayList<UserStatisticsVO>();
+        if (minRemovedDate == null) return userStats;
+
+        Transaction txn = Transaction.currentTxn();
+        try {
+            String sql = ACTIVE_AND_RECENTLY_DELETED_SEARCH + " LIMIT " + startIndex + "," + limit;
+            PreparedStatement pstmt = null;
+            pstmt = txn.prepareAutoCloseStatement(sql);
+            pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), minRemovedDate));
+            ResultSet rs = pstmt.executeQuery();
+            while (rs.next()) {
+                userStats.add(toEntityBean(rs, false));
+            }
+        } catch (Exception ex) {
+            s_logger.error("error saving user stats to cloud_usage db", ex);
+        }
+        return userStats;
+    }
+
+    @Override
+    public List<UserStatisticsVO> listUpdatedStats() {
+        List<UserStatisticsVO> userStats = new ArrayList<UserStatisticsVO>();
+
+        Transaction txn = Transaction.currentTxn();
+        try {
+            PreparedStatement pstmt = null;
+            pstmt = txn.prepareAutoCloseStatement(UPDATED_STATS_SEARCH);
+            ResultSet rs = pstmt.executeQuery();
+            while (rs.next()) {
+                userStats.add(toEntityBean(rs, false));
+            }
+        } catch (Exception ex) {
+            s_logger.error("error lisitng updated user stats", ex);
+        }
+        return userStats;
+    }
+
+}


Mime
View raw message