You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by ah...@apache.org on 2013/07/27 00:01:55 UTC

[06/10] Moved the DB layer code into framework-db and change only the necessary projects to refer to it. Cut down on the dependencies introduced with all the code in utils.

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/framework/db/src/com/cloud/utils/db/TransactionContextBuilder.java
----------------------------------------------------------------------
diff --git a/framework/db/src/com/cloud/utils/db/TransactionContextBuilder.java b/framework/db/src/com/cloud/utils/db/TransactionContextBuilder.java
new file mode 100644
index 0000000..40fcbbf
--- /dev/null
+++ b/framework/db/src/com/cloud/utils/db/TransactionContextBuilder.java
@@ -0,0 +1,65 @@
+// 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
+// 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.utils.db;
+
+import java.lang.reflect.Method;
+
+import com.cloud.utils.component.ComponentMethodInterceptor;
+
+public class TransactionContextBuilder implements ComponentMethodInterceptor {
+	public TransactionContextBuilder() {
+	}
+	
+	@Override
+	public boolean needToIntercept(Method method) {
+        DB db = method.getAnnotation(DB.class);
+        if (db != null) {
+            return true;
+        }
+        
+        Class<?> clazz = method.getDeclaringClass();
+        
+        do {
+            db = clazz.getAnnotation(DB.class);
+            if (db != null) {
+                return true;
+            }
+            clazz = clazz.getSuperclass();
+        } while (clazz != Object.class && clazz != null);
+        
+        return false;
+    }
+
+	@Override
+    public Object interceptStart(Method method, Object target) {
+    	return Transaction.open(method.getName());
+    }
+    
+	@Override
+    public void interceptComplete(Method method, Object target, Object objReturnedInInterceptStart) {
+    	Transaction txn = (Transaction)objReturnedInInterceptStart;
+    	if(txn != null)
+    		txn.close();
+    }
+    
+	@Override
+    public void interceptException(Method method, Object target, Object objReturnedInInterceptStart) {
+    	Transaction txn = (Transaction)objReturnedInInterceptStart;
+    	if(txn != null)
+    		txn.close();
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/framework/db/src/com/cloud/utils/db/TransactionMBean.java
----------------------------------------------------------------------
diff --git a/framework/db/src/com/cloud/utils/db/TransactionMBean.java b/framework/db/src/com/cloud/utils/db/TransactionMBean.java
new file mode 100644
index 0000000..b868360
--- /dev/null
+++ b/framework/db/src/com/cloud/utils/db/TransactionMBean.java
@@ -0,0 +1,33 @@
+// 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
+// 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.utils.db;
+
+import java.util.List;
+import java.util.Map;
+
+public interface TransactionMBean {
+    int getTransactionCount();
+    
+    int[] getActiveTransactionCount();
+    
+    List<Map<String, String>> getTransactions();
+    
+    List<Map<String, String>> getActiveTransactions();
+    
+    List<Map<String, String>> getTransactionsWithDatabaseConnection();
+    
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/framework/db/src/com/cloud/utils/db/TransactionMBeanImpl.java
----------------------------------------------------------------------
diff --git a/framework/db/src/com/cloud/utils/db/TransactionMBeanImpl.java b/framework/db/src/com/cloud/utils/db/TransactionMBeanImpl.java
new file mode 100644
index 0000000..d51a9bd
--- /dev/null
+++ b/framework/db/src/com/cloud/utils/db/TransactionMBeanImpl.java
@@ -0,0 +1,113 @@
+// 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
+// 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.utils.db;
+
+import java.sql.Connection;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import javax.management.StandardMBean;
+
+import com.cloud.utils.db.Transaction.StackElement;
+
+public class TransactionMBeanImpl extends StandardMBean implements TransactionMBean {
+    
+    Map<Long, Transaction> _txns = new ConcurrentHashMap<Long, Transaction>();
+    
+    public TransactionMBeanImpl() {
+        super(TransactionMBean.class, false);
+    }
+    
+    public void addTransaction(Transaction txn) {
+        _txns.put(txn.getId(), txn);
+    }
+    
+    public void removeTransaction(Transaction txn) {
+        _txns.remove(txn.getId());
+    }
+    
+    @Override
+    public int getTransactionCount() {
+        return _txns.size();
+    }
+    
+    @Override
+    public int[] getActiveTransactionCount() {
+        int[] count = new int[2];
+        count[0] = 0;
+        count[1] = 0;
+        for (Transaction txn : _txns.values()) {
+            if (txn.getStack().size() > 0) {
+                count[0]++;
+            }
+            if (txn.getCurrentConnection() != null) {
+                count[1]++;
+            }
+        }
+        return count;
+    }
+    
+    @Override
+    public List<Map<String, String>> getTransactions() {
+        ArrayList<Map<String, String>> txns = new ArrayList<Map<String, String>>();
+        for (Transaction info : _txns.values()) {
+            txns.add(toMap(info));
+        }
+        return txns;
+    }
+    
+    @Override
+    public List<Map<String, String>> getActiveTransactions() {
+        ArrayList<Map<String, String>> txns = new ArrayList<Map<String, String>>();
+        for (Transaction txn : _txns.values()) {
+            if (txn.getStack().size() > 0 || txn.getCurrentConnection() != null) {
+                txns.add(toMap(txn));
+            }
+        }
+        return txns;
+    }
+    
+    protected Map<String, String> toMap(Transaction txn) {
+        Map<String, String> map = new HashMap<String, String>();
+        map.put("name", txn.getName());
+        map.put("id", Long.toString(txn.getId()));
+        map.put("creator", txn.getCreator());
+        Connection conn = txn.getCurrentConnection();
+        map.put("db", conn != null ? Integer.toString(System.identityHashCode(conn)) : "none");
+        StringBuilder buff = new StringBuilder();
+        for (StackElement element : txn.getStack()) {
+            buff.append(element.toString()).append(",");
+        }
+        map.put("stack", buff.toString());
+        
+        return map;
+    }
+
+    @Override
+    public List<Map<String, String>> getTransactionsWithDatabaseConnection() {
+        ArrayList<Map<String, String>> txns = new ArrayList<Map<String, String>>();
+        for (Transaction txn : _txns.values()) {
+            if (txn.getCurrentConnection() != null) {
+                txns.add(toMap(txn));
+            }
+        }
+        return txns;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/framework/db/src/com/cloud/utils/db/UpdateBuilder.java
----------------------------------------------------------------------
diff --git a/framework/db/src/com/cloud/utils/db/UpdateBuilder.java b/framework/db/src/com/cloud/utils/db/UpdateBuilder.java
new file mode 100755
index 0000000..c13aa51
--- /dev/null
+++ b/framework/db/src/com/cloud/utils/db/UpdateBuilder.java
@@ -0,0 +1,147 @@
+// 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
+// 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.utils.db;
+
+import java.lang.reflect.Method;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+import net.sf.cglib.proxy.MethodInterceptor;
+import net.sf.cglib.proxy.MethodProxy;
+
+import com.cloud.utils.Ternary;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+public class UpdateBuilder implements MethodInterceptor {
+    protected Map<String, Ternary<Attribute, Boolean, Object>> _changes;
+    protected HashMap<Attribute, Object> _collectionChanges;
+    protected GenericDaoBase<?, ?> _dao;
+    
+    protected UpdateBuilder(GenericDaoBase<?, ?> dao) {
+        _dao = dao;
+        _changes = new HashMap<String, Ternary<Attribute, Boolean, Object>>();
+    }
+    
+    @Override
+    public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
+        String name = method.getName();
+        if (name.startsWith("set")) {
+        	String field = methodToField(name, 3);
+            makeChange(field, args[0]);
+        } else if (name.startsWith("incr")) {
+        	makeIncrChange(name, args);
+        } else if (name.startsWith("decr")) {
+        	makeDecrChange(name, args);
+        }
+        return methodProxy.invokeSuper(object, args);
+    }
+    
+    private final String methodToField(String method, int start) {
+    	char[] chs = method.toCharArray();
+    	chs[start] = Character.toLowerCase(chs[start]);
+    	return new String(chs, start, chs.length - start);
+    }
+    
+    protected Attribute makeChange(String field, Object value) {
+        Attribute attr = _dao._allAttributes.get(field);
+        
+        assert (attr == null || attr.isUpdatable()) : "Updating an attribute that's not updatable: " + field;
+        if (attr != null) {
+            if (attr.attache == null) {
+                _changes.put(field, new Ternary<Attribute, Boolean, Object>(attr, null, value));
+            } else {
+                if (_collectionChanges == null) {
+                    _collectionChanges = new HashMap<Attribute, Object>();
+                }
+                _collectionChanges.put(attr, value);
+            }
+        }
+        return attr;
+    }
+    
+    protected void makeIncrChange(String method, Object[] args) {
+    	String field = methodToField(method, 4);
+    	Attribute attr = _dao._allAttributes.get(field);
+        assert (attr != null && attr.isUpdatable()) : "Updating an attribute that's not updatable: " + field;
+    	incr(attr, args == null || args.length == 0 ? 1 : args[0]);
+    }
+    
+    protected void makeDecrChange(String method, Object[] args) {
+    	String field = methodToField(method, 4);
+    	Attribute attr = _dao._allAttributes.get(field);
+        assert (attr != null && attr.isUpdatable()) : "Updating an attribute that's not updatable: " + field;
+    	decr(attr, args == null || args.length == 0 ? 1 : args[0]);
+    }
+    
+    public void set(Object entity, String name, Object value) {
+    	Attribute attr = makeChange(name, value);
+
+    	set(entity, attr, value);
+    }
+    
+    public void set(Object entity, Attribute attr, Object value) {
+        _changes.put(attr.field.getName(), new Ternary<Attribute, Boolean, Object>(attr, null, value));
+        try {
+			attr.field.set(entity, value);
+		} catch (IllegalArgumentException e) {
+			throw new CloudRuntimeException("Unable to update " + attr.field.getName() + " with " + value, e);
+		} catch (IllegalAccessException e) {
+			throw new CloudRuntimeException("Unable to update " + attr.field.getName() + " with " + value, e);
+		}
+    }
+    
+    public void incr(Attribute attr, Object value) {
+        _changes.put(attr.field.getName(), new Ternary<Attribute, Boolean, Object>(attr, true, value));
+    }
+    
+    public void decr(Attribute attr, Object value) {
+        _changes.put(attr.field.getName(), new Ternary<Attribute, Boolean, Object>(attr, false, value));
+    }
+    
+    public boolean hasChanges() {
+        return (_changes.size() + (_collectionChanges != null ? _collectionChanges.size() : 0)) != 0;
+    }
+    
+    public boolean has(String name) {
+        return _changes.containsKey(name);
+    }
+    
+    public Map<Attribute, Object> getCollectionChanges() {
+        return _collectionChanges;
+    }
+    
+    public void clear() {
+        _changes.clear();
+        if (_collectionChanges != null) {
+            _collectionChanges.clear();
+            _collectionChanges = null;
+        }
+    }
+    
+    public StringBuilder toSql(String tables) {
+    	if (_changes.isEmpty()) {
+    		return null;
+    	}
+    	
+    	return SqlGenerator.buildMysqlUpdateSql(tables, _changes.values());
+    }
+    
+    public Collection<Ternary<Attribute, Boolean, Object>> getChanges() {
+    	return _changes.values();
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/framework/db/src/com/cloud/utils/db/UpdateFilter.java
----------------------------------------------------------------------
diff --git a/framework/db/src/com/cloud/utils/db/UpdateFilter.java b/framework/db/src/com/cloud/utils/db/UpdateFilter.java
new file mode 100644
index 0000000..37b35b1
--- /dev/null
+++ b/framework/db/src/com/cloud/utils/db/UpdateFilter.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
+// 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.utils.db;
+
+import java.lang.reflect.Method;
+
+import net.sf.cglib.proxy.CallbackFilter;
+
+public class UpdateFilter implements CallbackFilter {
+    @Override
+    public int accept(Method method) {
+        String name = method.getName();
+        return (name.startsWith("set") || name.startsWith("incr") || name.startsWith("decr")) ? 1 : 0;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/framework/db/test/com/cloud/utils/db/DbAnnotatedBase.java
----------------------------------------------------------------------
diff --git a/framework/db/test/com/cloud/utils/db/DbAnnotatedBase.java b/framework/db/test/com/cloud/utils/db/DbAnnotatedBase.java
new file mode 100644
index 0000000..f87b20f
--- /dev/null
+++ b/framework/db/test/com/cloud/utils/db/DbAnnotatedBase.java
@@ -0,0 +1,44 @@
+// 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
+// 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.utils.db;
+
+
+import javax.annotation.PostConstruct;
+import javax.inject.Inject;
+
+import junit.framework.Assert;
+
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+@Component
+@DB
+public class DbAnnotatedBase {
+    private static final Logger s_logger = Logger.getLogger(DbAnnotatedBase.class);
+
+    @Inject DummyComponent _dummy;
+    
+    @PostConstruct
+    public void initTest() {
+    	Assert.assertTrue(true);
+    }
+    
+    public void MethodWithClassDbAnnotated() {
+    	s_logger.info("called");
+    	_dummy.sayHello();
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/framework/db/test/com/cloud/utils/db/DbAnnotatedBaseDerived.java
----------------------------------------------------------------------
diff --git a/framework/db/test/com/cloud/utils/db/DbAnnotatedBaseDerived.java b/framework/db/test/com/cloud/utils/db/DbAnnotatedBaseDerived.java
new file mode 100644
index 0000000..38e045c
--- /dev/null
+++ b/framework/db/test/com/cloud/utils/db/DbAnnotatedBaseDerived.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
+// 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.utils.db;
+
+import org.springframework.stereotype.Component;
+
+@Component
+public class DbAnnotatedBaseDerived extends DbAnnotatedBase {
+
+	@DB
+	public void DbAnnotatedMethod() {
+	}
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/framework/db/test/com/cloud/utils/db/DbTestDao.java
----------------------------------------------------------------------
diff --git a/framework/db/test/com/cloud/utils/db/DbTestDao.java b/framework/db/test/com/cloud/utils/db/DbTestDao.java
new file mode 100644
index 0000000..9530b3b
--- /dev/null
+++ b/framework/db/test/com/cloud/utils/db/DbTestDao.java
@@ -0,0 +1,66 @@
+// 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
+// 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.utils.db;
+
+import java.sql.PreparedStatement;
+import java.util.Date;
+import java.util.TimeZone;
+
+import com.cloud.utils.DateUtil;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+public class DbTestDao extends GenericDaoBase<DbTestVO, Long> implements GenericDao<DbTestVO, Long> {
+    protected DbTestDao() {
+    }
+
+    @DB
+    public void create(int fldInt, long fldLong, String fldString) {
+        Transaction txn = Transaction.currentTxn();
+        PreparedStatement pstmt = null;
+        try {
+            txn.start();
+            pstmt = txn
+                    .prepareAutoCloseStatement("insert into cloud.test(fld_int, fld_long, fld_string) values(?, ?, ?)");
+            pstmt.setInt(1, fldInt);
+            pstmt.setLong(2, fldLong);
+            pstmt.setString(3, fldString);
+
+            pstmt.executeUpdate();
+            txn.commit();
+        } catch (Exception e) {
+            throw new CloudRuntimeException("Problem with creating a record in test table", e);
+        }
+    }
+
+    @DB
+    public void update(int fldInt, long fldLong, String fldString) {
+        Transaction txn = Transaction.currentTxn();
+        PreparedStatement pstmt = null;
+        try {
+            txn.start();
+            pstmt = txn.prepareAutoCloseStatement("update cloud.test set fld_int=?, fld_long=? where fld_string=?");
+            pstmt.setInt(1, fldInt);
+            pstmt.setLong(2, fldLong);
+            pstmt.setString(3, fldString);
+
+            pstmt.executeUpdate();
+            txn.commit();
+        } catch (Exception e) {
+            throw new CloudRuntimeException("Problem with creating a record in test table", e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/framework/db/test/com/cloud/utils/db/DbTestUtils.java
----------------------------------------------------------------------
diff --git a/framework/db/test/com/cloud/utils/db/DbTestUtils.java b/framework/db/test/com/cloud/utils/db/DbTestUtils.java
new file mode 100644
index 0000000..11ae1aa
--- /dev/null
+++ b/framework/db/test/com/cloud/utils/db/DbTestUtils.java
@@ -0,0 +1,90 @@
+// 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
+// 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.utils.db;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.SQLException;
+
+import com.cloud.utils.PropertiesUtil;
+
+public class DbTestUtils {
+    
+    public static void executeScript(String file, boolean autoCommit, boolean stopOnError) {
+        File cleanScript = PropertiesUtil.findConfigFile(file);
+        if (cleanScript == null) {
+            throw new RuntimeException("Unable to clean the database because I can't find " + file);
+        }
+        
+        Connection conn = Transaction.getStandaloneConnection();
+        
+        ScriptRunner runner = new ScriptRunner(conn, autoCommit, stopOnError);
+        FileReader reader;
+        try {
+            reader = new FileReader(cleanScript);
+        } catch (FileNotFoundException e) {
+            throw new RuntimeException("Unable to read " + file, e);
+        } 
+        try {
+            runner.runScript(reader);
+        } catch (IOException e) {
+            throw new RuntimeException("Unable to read " + file, e);
+        } catch (SQLException e) {
+            throw new RuntimeException("Unable to execute " + file, e);
+        }
+        
+        try {
+            conn.close();
+        } catch (SQLException e) {
+            throw new RuntimeException("Unable to close DB connection", e);
+        }
+    }
+
+    public static void executeUsageScript(String file, boolean autoCommit, boolean stopOnError) {
+        File cleanScript = PropertiesUtil.findConfigFile(file);
+        if (cleanScript == null) {
+            throw new RuntimeException("Unable to clean the database because I can't find " + file);
+        }
+        
+        Connection conn = Transaction.getStandaloneUsageConnection();
+        
+        ScriptRunner runner = new ScriptRunner(conn, autoCommit, stopOnError);
+        FileReader reader;
+        try {
+            reader = new FileReader(cleanScript);
+        } catch (FileNotFoundException e) {
+            throw new RuntimeException("Unable to read " + file, e);
+        } 
+        try {
+            runner.runScript(reader);
+        } catch (IOException e) {
+            throw new RuntimeException("Unable to read " + file, e);
+        } catch (SQLException e) {
+            throw new RuntimeException("Unable to execute " + file, e);
+        }
+        
+        try {
+            conn.close();
+        } catch (SQLException e) {
+            throw new RuntimeException("Unable to close DB connection", e);
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/framework/db/test/com/cloud/utils/db/DbTestVO.java
----------------------------------------------------------------------
diff --git a/framework/db/test/com/cloud/utils/db/DbTestVO.java b/framework/db/test/com/cloud/utils/db/DbTestVO.java
new file mode 100644
index 0000000..5285bfe
--- /dev/null
+++ b/framework/db/test/com/cloud/utils/db/DbTestVO.java
@@ -0,0 +1,56 @@
+// 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
+// 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.utils.db;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+@Entity
+@Table(name = "test")
+public class DbTestVO {
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    long id;
+
+    @Column(name = "fld_int")
+    int fieldInt;
+
+    @Column(name = "fld_long")
+    Long fieldLong;
+
+    @Column(name = "fld_string")
+    String fieldString;
+
+    public String getFieldString() {
+        return fieldString;
+    }
+
+    public int getFieldInt() {
+        return fieldInt;
+    }
+
+    public long getFieldLong() {
+        return fieldLong;
+    }
+
+    public DbTestVO() {
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/framework/db/test/com/cloud/utils/db/DummyComponent.java
----------------------------------------------------------------------
diff --git a/framework/db/test/com/cloud/utils/db/DummyComponent.java b/framework/db/test/com/cloud/utils/db/DummyComponent.java
new file mode 100644
index 0000000..2922630
--- /dev/null
+++ b/framework/db/test/com/cloud/utils/db/DummyComponent.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
+// 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.utils.db;
+
+import org.springframework.stereotype.Component;
+
+@Component
+public class DummyComponent {
+
+	public void sayHello() {
+		System.out.println("Hello, world");
+	}
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/framework/db/test/com/cloud/utils/db/ElementCollectionTest.java
----------------------------------------------------------------------
diff --git a/framework/db/test/com/cloud/utils/db/ElementCollectionTest.java b/framework/db/test/com/cloud/utils/db/ElementCollectionTest.java
new file mode 100644
index 0000000..b860af5
--- /dev/null
+++ b/framework/db/test/com/cloud/utils/db/ElementCollectionTest.java
@@ -0,0 +1,72 @@
+// 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
+// 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.utils.db;
+
+import java.lang.reflect.Array;
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import junit.framework.TestCase;
+
+import org.apache.log4j.Logger;
+
+
+public class ElementCollectionTest extends TestCase {
+    static final Logger s_logger = Logger.getLogger(ElementCollectionTest.class);
+    ArrayList<String> ar = null;
+    List<String> lst = null;
+    Collection<String> coll = null;
+    String[] array = null;
+
+    public void testArrayList() throws Exception {
+        Field[] fields = this.getClass().getDeclaredFields();
+        for (Field field : fields) {
+            if (Modifier.isStatic(field.getModifiers())) {
+                continue;
+            }
+            Class<?> type1 = field.getType();
+            Object collection = null;
+            if (!type1.isArray()) {
+                ParameterizedType type = (ParameterizedType)field.getGenericType();
+                Type rawType = type.getRawType();
+                Class<?> rawClazz = (Class<?>)rawType;
+                if (!Modifier.isAbstract(rawClazz.getModifiers()) && !rawClazz.isInterface() && rawClazz.getConstructors().length != 0 && rawClazz.getConstructor() != null) {
+                    collection = rawClazz.newInstance();
+                }
+
+                if (collection == null) {
+                    if (Collection.class.isAssignableFrom(rawClazz)) {
+                        collection = new ArrayList();
+                    } else if (Set.class.isAssignableFrom(rawClazz)) {
+                        collection = new HashSet();
+                    }
+                }
+            } else {
+                collection = Array.newInstance(String.class, 1);
+            }
+            field.set(this, collection);
+            assert (field.get(this) != null);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/framework/db/test/com/cloud/utils/db/GlobalLockTest.java
----------------------------------------------------------------------
diff --git a/framework/db/test/com/cloud/utils/db/GlobalLockTest.java b/framework/db/test/com/cloud/utils/db/GlobalLockTest.java
new file mode 100644
index 0000000..8d6ff41
--- /dev/null
+++ b/framework/db/test/com/cloud/utils/db/GlobalLockTest.java
@@ -0,0 +1,81 @@
+// 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.utils.db;
+
+import org.apache.log4j.Logger;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import com.cloud.utils.Profiler;
+
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations="classpath:/testContext.xml")
+public class GlobalLockTest {
+    public static final Logger s_logger = Logger.getLogger(GlobalLockTest.class);
+    private final static GlobalLock _workLock = GlobalLock.getInternLock("SecurityGroupWork");
+    public static class Worker implements Runnable {
+        int id = 0;
+        int timeoutSeconds = 10;
+        int jobDuration = 2;
+        public Worker(int id, int timeout, int duration) {
+            this.id = id;
+            timeoutSeconds = timeout;
+            jobDuration = duration;
+        }
+        @Override
+        public void run() {
+            boolean locked = false;
+            try {
+                Profiler p = new Profiler();
+                p.start();
+                locked = _workLock.lock(timeoutSeconds);
+                p.stop();
+                System.out.println("Thread " + id + " waited " + p.getDuration() + " ms, locked=" + locked);
+                if (locked) {
+                    Thread.sleep(jobDuration*1000);
+                }
+            } catch (InterruptedException e) {
+            } finally {
+                if (locked) {
+                    boolean unlocked = _workLock.unlock();
+                    System.out.println("Thread " + id + "  unlocked=" + unlocked);
+                }
+            }
+        }
+    }
+
+    @Test
+    public void testTimeout() {
+        Thread [] pool = new Thread[50];
+        for (int i=0; i < pool.length; i++) {
+            pool[i] = new Thread(new Worker(i, 5, 3));
+        }
+        for (int i=0; i < pool.length; i++) {
+            pool[i].start();
+        }
+        for (int i=0; i < pool.length; i++) {
+            try {
+                pool[i].join();
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+            }
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/framework/db/test/com/cloud/utils/db/Merovingian2Test.java
----------------------------------------------------------------------
diff --git a/framework/db/test/com/cloud/utils/db/Merovingian2Test.java b/framework/db/test/com/cloud/utils/db/Merovingian2Test.java
new file mode 100644
index 0000000..8246faa
--- /dev/null
+++ b/framework/db/test/com/cloud/utils/db/Merovingian2Test.java
@@ -0,0 +1,77 @@
+// 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
+// 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.utils.db;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
+
+import org.apache.log4j.Logger;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+public class Merovingian2Test extends TestCase {
+    static final Logger s_logger = Logger.getLogger(Merovingian2Test.class);
+    Merovingian2 _lockMaster = Merovingian2.createLockMaster(1234);
+    
+    @Override @Before
+    protected void setUp() throws Exception {
+        _lockMaster.cleanupThisServer();
+    }
+    
+    @Override @After
+    protected void tearDown() throws Exception {
+        _lockMaster.cleanupThisServer();
+    }
+
+    @Test
+    public void testLockAndRelease() {
+        
+        s_logger.info("Testing first acquire");
+        boolean result = _lockMaster.acquire("first"+1234, 5);
+        Assert.assertTrue(result);
+        
+        s_logger.info("Testing acquire of different lock");
+        result = _lockMaster.acquire("second"+1234, 5);
+        Assert.assertTrue(result);
+        
+        s_logger.info("Testing reacquire of the same lock");
+        result = _lockMaster.acquire("first"+1234, 5);
+        Assert.assertTrue(result);
+        
+        int count = _lockMaster.owns("first"+1234);
+        Assert.assertEquals(count, 2);
+        
+        count = _lockMaster.owns("second"+1234);
+        Assert.assertEquals(count, 1);
+        
+        s_logger.info("Testing release of the first lock");
+        result = _lockMaster.release("first"+1234);
+        Assert.assertTrue(result);
+        
+        count = _lockMaster.owns("first"+1234);
+        Assert.assertEquals(count, 1);
+        
+        s_logger.info("Testing release of the second lock");
+        result = _lockMaster.release("second"+1234);
+        Assert.assertTrue(result);
+        
+        result = _lockMaster.release("first"+1234);
+        Assert.assertTrue(result);
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/framework/db/test/com/cloud/utils/db/TransactionContextBuilderTest.java
----------------------------------------------------------------------
diff --git a/framework/db/test/com/cloud/utils/db/TransactionContextBuilderTest.java b/framework/db/test/com/cloud/utils/db/TransactionContextBuilderTest.java
new file mode 100644
index 0000000..33e7aa0
--- /dev/null
+++ b/framework/db/test/com/cloud/utils/db/TransactionContextBuilderTest.java
@@ -0,0 +1,63 @@
+// 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
+// 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.utils.db;
+
+import java.util.List;
+import java.util.Map;
+
+import javax.inject.Inject;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import com.cloud.utils.component.ComponentContext;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations="classpath:/com/cloud/utils/db/transactioncontextBuilderTest.xml")
+public class TransactionContextBuilderTest {
+
+	@Inject
+	DbAnnotatedBaseDerived _derived; 
+	
+	DbAnnotatedBase _base;
+	
+	@Inject
+	List<DbAnnotatedBase> _list;
+	
+	@Test
+	public void test() {
+		// _derived.DbAnnotatedMethod();
+		// _base.MethodWithClassDbAnnotated();
+		
+		// test @DB injection on dynamically constructed objects
+		DbAnnotatedBase base = ComponentContext.inject(new DbAnnotatedBase());
+		base.MethodWithClassDbAnnotated();
+
+/*		
+		Map<String, DbAnnotatedBase> components = ComponentContext.getApplicationContext().getBeansOfType(DbAnnotatedBase.class);
+		for(Map.Entry<String, DbAnnotatedBase> entry : components.entrySet()) {
+			System.out.println(entry.getKey());
+			entry.getValue().MethodWithClassDbAnnotated();
+		}
+*/
+		for(DbAnnotatedBase entry : _list) {
+			entry.MethodWithClassDbAnnotated();
+		}
+	}
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/framework/db/test/com/cloud/utils/db/TransactionTest.java
----------------------------------------------------------------------
diff --git a/framework/db/test/com/cloud/utils/db/TransactionTest.java b/framework/db/test/com/cloud/utils/db/TransactionTest.java
new file mode 100644
index 0000000..101a533
--- /dev/null
+++ b/framework/db/test/com/cloud/utils/db/TransactionTest.java
@@ -0,0 +1,214 @@
+// 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
+// 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.utils.db;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import com.cloud.utils.component.ComponentContext;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+/**
+ * A test fixture to test APIs or bugs found for Transaction class. This test fixture will do one time setup before
+ * all its testcases to set up a test db table, and then tear down these test db artifacts after all testcases are run.
+ *
+ */
+public class TransactionTest {
+
+    @BeforeClass
+    public static void oneTimeSetup() {
+        Connection conn = null;
+        PreparedStatement pstmt = null;
+        try {
+            conn = Transaction.getStandaloneConnection();
+
+            pstmt = conn.prepareStatement("CREATE TABLE `cloud`.`test` ("
+                    + "`id` bigint unsigned NOT NULL UNIQUE AUTO_INCREMENT," + "`fld_int` int unsigned,"
+                    + "`fld_long` bigint unsigned," + "`fld_string` varchar(255)," + "PRIMARY KEY (`id`)"
+                    + ") ENGINE=InnoDB DEFAULT CHARSET=utf8;");
+
+            pstmt.execute();
+
+        } catch (SQLException e) {
+            throw new CloudRuntimeException("Problem with sql", e);
+        } finally {
+            if (pstmt != null) {
+                try {
+                    pstmt.close();
+                } catch (SQLException e) {
+                }
+            }
+            if (conn != null) {
+                try {
+                    conn.close();
+                } catch (SQLException e) {
+                }
+            }
+        }
+    }
+
+    @Test
+    /**
+     * When a transaction is set to use user-managed db connection, for each following db statement, we should see
+     * that the same db connection is reused rather than acquiring a new one each time in typical transaction model.
+     */
+    public void testUserManagedConnection() {
+        DbTestDao testDao = ComponentContext.inject(DbTestDao.class);
+        Transaction txn = Transaction.open("SingleConnectionThread");
+        Connection conn = null;
+        try {
+            conn = Transaction.getStandaloneConnectionWithException();
+            txn.transitToUserManagedConnection(conn);
+            // try two SQLs to make sure that they are using the same connection
+            // acquired above.
+            testDao.create(1, 1, "Record 1");
+            Connection checkConn = Transaction.currentTxn().getConnection();
+            if (checkConn != conn) {
+                Assert.fail("A new db connection is acquired instead of using old one after create sql");
+            }
+            testDao.update(2, 2, "Record 1");
+            Connection checkConn2 = Transaction.currentTxn().getConnection();
+            if (checkConn2 != conn) {
+                Assert.fail("A new db connection is acquired instead of using old one after update sql");
+            }
+        } catch (SQLException e) {
+            Assert.fail(e.getMessage());
+        } finally {
+            txn.transitToAutoManagedConnection(Transaction.CLOUD_DB);
+            txn.close();
+
+            if (conn != null) {
+                try {
+                    conn.close();
+                } catch (SQLException e) {
+                    throw new CloudRuntimeException("Problem with close db connection", e);
+                }
+            }
+        }
+    }
+
+    @Test
+    /**
+     * This test is simulating ClusterHeartBeat process, where the same transaction and db connection is reused.
+     */
+    public void testTransactionReuse() {
+        DbTestDao testDao = ComponentContext.inject(DbTestDao.class);
+        // acquire a db connection and keep it
+        Connection conn = null;
+        try {
+            conn = Transaction.getStandaloneConnectionWithException();
+        } catch (SQLException ex) {
+            throw new CloudRuntimeException("Problem with getting db connection", ex);
+        }
+
+        // start heartbeat loop, make sure that each loop still use the same
+        // connection
+        Transaction txn = null;
+        for (int i = 0; i < 3; i++) {
+            txn = Transaction.open("HeartbeatSimulator");
+            try {
+
+                txn.transitToUserManagedConnection(conn);
+                testDao.create(i, i, "Record " + i);
+                Connection checkConn = Transaction.currentTxn().getConnection();
+                if (checkConn != conn) {
+                    Assert.fail("A new db connection is acquired instead of using old one in loop " + i);
+                }
+            } catch (SQLException e) {
+                Assert.fail(e.getMessage());
+            } finally {
+                txn.transitToAutoManagedConnection(Transaction.CLOUD_DB);
+                txn.close();
+            }
+        }
+        // close the connection once we are done since we are managing db
+        // connection ourselves.
+        if (conn != null) {
+            try {
+                conn.close();
+            } catch (SQLException e) {
+                throw new CloudRuntimeException("Problem with close db connection", e);
+            }
+        }
+    }
+
+    @After
+    /**
+     * Delete all records after each test, but table is still kept
+     */
+    public void tearDown() {
+        Connection conn = null;
+        PreparedStatement pstmt = null;
+        try {
+            conn = Transaction.getStandaloneConnection();
+
+            pstmt = conn.prepareStatement("truncate table `cloud`.`test`");
+            pstmt.execute();
+
+        } catch (SQLException e) {
+            throw new CloudRuntimeException("Problem with sql", e);
+        } finally {
+            if (pstmt != null) {
+                try {
+                    pstmt.close();
+                } catch (SQLException e) {
+                }
+            }
+            if (conn != null) {
+                try {
+                    conn.close();
+                } catch (SQLException e) {
+                }
+            }
+        }
+    }
+
+    @AfterClass
+    public static void oneTimeTearDown() {
+        Connection conn = null;
+        PreparedStatement pstmt = null;
+        try {
+            conn = Transaction.getStandaloneConnection();
+
+            pstmt = conn.prepareStatement("DROP TABLE IF EXISTS `cloud`.`test`");
+            pstmt.execute();
+
+        } catch (SQLException e) {
+            throw new CloudRuntimeException("Problem with sql", e);
+        } finally {
+            if (pstmt != null) {
+                try {
+                    pstmt.close();
+                } catch (SQLException e) {
+                }
+            }
+            if (conn != null) {
+                try {
+                    conn.close();
+                } catch (SQLException e) {
+                }
+            }
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/plugins/hypervisors/vmware/pom.xml
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/vmware/pom.xml b/plugins/hypervisors/vmware/pom.xml
index 755244f..ad76411 100644
--- a/plugins/hypervisors/vmware/pom.xml
+++ b/plugins/hypervisors/vmware/pom.xml
@@ -64,15 +64,5 @@
       <artifactId>wsdl4j</artifactId>
       <version>1.4</version>
     </dependency>
-      <dependency>
-          <groupId>junit</groupId>
-          <artifactId>junit</artifactId>
-          <version>4.10</version>
-      </dependency>
-      <dependency>
-          <groupId>org.mockito</groupId>
-          <artifactId>mockito-all</artifactId>
-          <version>1.9.5</version>
-      </dependency>
   </dependencies>
 </project>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/plugins/pom.xml
----------------------------------------------------------------------
diff --git a/plugins/pom.xml b/plugins/pom.xml
index ff1e9c9..e2f767a 100755
--- a/plugins/pom.xml
+++ b/plugins/pom.xml
@@ -77,7 +77,7 @@
     </dependency>
     <dependency>
       <groupId>org.apache.cloudstack</groupId>
-      <artifactId>cloud-utils</artifactId>
+      <artifactId>cloud-api</artifactId>
       <version>${project.version}</version>
       <type>test-jar</type>
       <scope>test</scope>      

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/server/pom.xml
----------------------------------------------------------------------
diff --git a/server/pom.xml b/server/pom.xml
index 484d603..20bcece 100644
--- a/server/pom.xml
+++ b/server/pom.xml
@@ -92,7 +92,7 @@
     </dependency>
     <dependency>
       <groupId>org.apache.cloudstack</groupId>
-      <artifactId>cloud-utils</artifactId>
+      <artifactId>cloud-api</artifactId>
       <version>${project.version}</version>
       <type>test-jar</type>
       <scope>test</scope>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/server/src/com/cloud/api/ApiDispatcher.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/ApiDispatcher.java b/server/src/com/cloud/api/ApiDispatcher.java
index 223c6b3..65e2113 100755
--- a/server/src/com/cloud/api/ApiDispatcher.java
+++ b/server/src/com/cloud/api/ApiDispatcher.java
@@ -352,7 +352,7 @@ public class ApiDispatcher {
         for (Class<?> entity : entities) {
             // For backward compatibility, we search within removed entities and let service layer deal
             // with removed ones, return empty response or error
-            Object objVO = s_instance._entityMgr.findByUuidIncludingRemoved(entity, uuid);
+            Object objVO = s_instance._entityMgr.findByUuid(entity, uuid);
             if (objVO == null) {
                 continue;
             }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/server/src/com/cloud/api/ApiResponseHelper.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java
index f7b740b..c1ae7d0 100755
--- a/server/src/com/cloud/api/ApiResponseHelper.java
+++ b/server/src/com/cloud/api/ApiResponseHelper.java
@@ -31,6 +31,9 @@ import java.util.TimeZone;
 
 import javax.inject.Inject;
 
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
 import org.apache.cloudstack.acl.ControlledEntity;
 import org.apache.cloudstack.acl.ControlledEntity.ACLType;
 import org.apache.cloudstack.affinity.AffinityGroup;
@@ -70,6 +73,7 @@ import org.apache.cloudstack.api.response.HostForMigrationResponse;
 import org.apache.cloudstack.api.response.HostResponse;
 import org.apache.cloudstack.api.response.HypervisorCapabilitiesResponse;
 import org.apache.cloudstack.api.response.IPAddressResponse;
+import org.apache.cloudstack.api.response.ImageStoreResponse;
 import org.apache.cloudstack.api.response.InstanceGroupResponse;
 import org.apache.cloudstack.api.response.InternalLoadBalancerElementResponse;
 import org.apache.cloudstack.api.response.IpForwardingRuleResponse;
@@ -86,7 +90,6 @@ import org.apache.cloudstack.api.response.NetworkOfferingResponse;
 import org.apache.cloudstack.api.response.NetworkResponse;
 import org.apache.cloudstack.api.response.NicResponse;
 import org.apache.cloudstack.api.response.NicSecondaryIpResponse;
-import org.apache.cloudstack.api.response.ImageStoreResponse;
 import org.apache.cloudstack.api.response.PhysicalNetworkResponse;
 import org.apache.cloudstack.api.response.PodResponse;
 import org.apache.cloudstack.api.response.PortableIpRangeResponse;
@@ -144,9 +147,6 @@ import org.apache.cloudstack.usage.Usage;
 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.api.query.ViewResponseHelper;
 import com.cloud.api.query.vo.AccountJoinVO;
 import com.cloud.api.query.vo.AsyncJobJoinVO;
@@ -301,9 +301,9 @@ public class ApiResponseHelper implements ResponseGenerator {
     public final Logger s_logger = Logger.getLogger(ApiResponseHelper.class);
     private static final DecimalFormat s_percentFormat = new DecimalFormat("##.##");
     @Inject
-    private EntityManager _entityMgr = null;
+    private final EntityManager _entityMgr = null;
     @Inject
-    private UsageService _usageSvc = null;
+    private final UsageService _usageSvc = null;
     @Inject NetworkModel _ntwkModel;
 
     @Override
@@ -831,7 +831,7 @@ public class ApiResponseHelper implements ResponseGenerator {
                 capacityResponse.setCapacityType(capacity.getCapacityType());
                 capacityResponse.setCapacityUsed(capacity.getUsedCapacity());
                 if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU) {
-                    capacityResponse.setCapacityTotal(new Long((long) (capacity.getTotalCapacity())));
+                    capacityResponse.setCapacityTotal(new Long((capacity.getTotalCapacity())));
                 } else if (capacity.getCapacityType() == Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED) {
                     List<SummedCapacity> c = ApiDBUtils.findNonSharedStorageForClusterPodZone(null, pod.getId(), null);
                     capacityResponse.setCapacityTotal(capacity.getTotalCapacity() - c.get(0).getTotalCapacity());
@@ -1409,7 +1409,7 @@ public class ApiResponseHelper implements ResponseGenerator {
             templateResponse.setOsTypeName("");
         }
 
-        final Account account = ApiDBUtils.findAccountByIdIncludingRemoved(iso.getAccountId());
+        final Account account = ApiDBUtils.findAccountById(iso.getAccountId());
         populateAccount(templateResponse, account.getId());
         populateDomain(templateResponse, account.getDomainId());
 
@@ -1466,7 +1466,7 @@ public class ApiResponseHelper implements ResponseGenerator {
             isoResponse.setOsTypeId("-1");
             isoResponse.setOsTypeName("");
         }
-        Account account = ApiDBUtils.findAccountByIdIncludingRemoved(iso.getAccountId());
+        Account account = ApiDBUtils.findAccountById(iso.getAccountId());
         populateAccount(isoResponse, account.getId());
         populateDomain(isoResponse, account.getDomainId());
         boolean isAdmin = false;
@@ -1521,7 +1521,7 @@ public class ApiResponseHelper implements ResponseGenerator {
             isoResponse.setOsTypeName("");
         }
 
-        Account account = ApiDBUtils.findAccountByIdIncludingRemoved(iso.getAccountId());
+        Account account = ApiDBUtils.findAccountById(iso.getAccountId());
         populateAccount(isoResponse, account.getId());
         populateDomain(isoResponse, account.getDomainId());
 
@@ -1578,7 +1578,7 @@ public class ApiResponseHelper implements ResponseGenerator {
         isoResponses.add(isoResponse);
         return isoResponses;
     }
-*/
+    */
 
     @Override
     public SecurityGroupResponse createSecurityGroupResponse(SecurityGroup group) {
@@ -1909,7 +1909,7 @@ public class ApiResponseHelper implements ResponseGenerator {
                 regularAccounts.add(accountName);
             } else {
                 // convert account to projectIds
-                Project project = ApiDBUtils.findProjectByProjectAccountIdIncludingRemoved(account.getId());
+                Project project = ApiDBUtils.findProjectByProjectAccountId(account.getId());
 
                 if (project.getUuid() != null && !project.getUuid().isEmpty())
                     projectIds.add(project.getUuid());
@@ -2211,7 +2211,7 @@ public class ApiResponseHelper implements ResponseGenerator {
         }
 
         // populate network offering information
-        NetworkOffering networkOffering = (NetworkOffering) ApiDBUtils.findNetworkOfferingById(network.getNetworkOfferingId());
+        NetworkOffering networkOffering = ApiDBUtils.findNetworkOfferingById(network.getNetworkOfferingId());
         if (networkOffering != null) {
             response.setNetworkOfferingId(networkOffering.getUuid());
             response.setNetworkOfferingName(networkOffering.getName());
@@ -2455,11 +2455,11 @@ public class ApiResponseHelper implements ResponseGenerator {
     // ControlledEntity id to uuid conversion are all done.
     // currently code is scattered in
     private void populateOwner(ControlledEntityResponse response, ControlledEntity object) {
-        Account account = ApiDBUtils.findAccountByIdIncludingRemoved(object.getAccountId());
+        Account account = ApiDBUtils.findAccountById(object.getAccountId());
 
         if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
             // find the project
-            Project project = ApiDBUtils.findProjectByProjectAccountIdIncludingRemoved(account.getId());
+            Project project = ApiDBUtils.findProjectByProjectAccountId(account.getId());
             response.setProjectId(project.getUuid());
             response.setProjectName(project.getName());
         } else {
@@ -2485,10 +2485,10 @@ public class ApiResponseHelper implements ResponseGenerator {
     }
 
     private void populateAccount(ControlledEntityResponse response, long accountId) {
-        Account account = ApiDBUtils.findAccountByIdIncludingRemoved(accountId);
+        Account account = ApiDBUtils.findAccountById(accountId);
         if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
             // find the project
-            Project project = ApiDBUtils.findProjectByProjectAccountIdIncludingRemoved(account.getId());
+            Project project = ApiDBUtils.findProjectByProjectAccountId(account.getId());
             response.setProjectId(project.getUuid());
             response.setProjectName(project.getName());
             response.setAccountName(account.getAccountName());
@@ -3273,10 +3273,10 @@ public class ApiResponseHelper implements ResponseGenerator {
 	public UsageRecordResponse createUsageResponse(Usage usageRecord) {
 		UsageRecordResponse usageRecResponse = new UsageRecordResponse();
 
-		Account account = ApiDBUtils.findAccountByIdIncludingRemoved(usageRecord.getAccountId());
+        Account account = ApiDBUtils.findAccountById(usageRecord.getAccountId());
 		if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
 			//find the project
-			Project project = ApiDBUtils.findProjectByProjectAccountIdIncludingRemoved(account.getId());
+            Project project = ApiDBUtils.findProjectByProjectAccountId(account.getId());
 			usageRecResponse.setProjectId(project.getUuid());
 			usageRecResponse.setProjectName(project.getName());
 		} else {
@@ -3299,7 +3299,7 @@ public class ApiResponseHelper implements ResponseGenerator {
 		usageRecResponse.setUsage(usageRecord.getUsageDisplay());
 		usageRecResponse.setUsageType(usageRecord.getUsageType());
 		if (usageRecord.getVmInstanceId() != null) {
-			VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getVmInstanceId());
+            VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, usageRecord.getVmInstanceId());
 			usageRecResponse.setVirtualMachineId(vm.getUuid());
 		}
 		usageRecResponse.setVmName(usageRecord.getVmName());
@@ -3311,11 +3311,11 @@ public class ApiResponseHelper implements ResponseGenerator {
 		}
 
 		if(usageRecord.getUsageType() == UsageTypes.RUNNING_VM || usageRecord.getUsageType() == UsageTypes.ALLOCATED_VM){
-			ServiceOfferingVO svcOffering = _entityMgr.findByIdIncludingRemoved(ServiceOfferingVO.class, usageRecord.getOfferingId().toString());
+            ServiceOfferingVO svcOffering = _entityMgr.findById(ServiceOfferingVO.class, usageRecord.getOfferingId().toString());
 			//Service Offering Id
 			usageRecResponse.setOfferingId(svcOffering.getUuid());
 			//VM Instance ID
-			VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getUsageId().toString());
+            VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, usageRecord.getUsageId().toString());
 			usageRecResponse.setUsageId(vm.getUuid());
 			//Hypervisor Type
 			usageRecResponse.setType(usageRecord.getType());
@@ -3326,7 +3326,7 @@ public class ApiResponseHelper implements ResponseGenerator {
 			//isSystem
 			usageRecResponse.setSystem((usageRecord.getSize() == 1)?true:false);
 			//IP Address ID
-			IPAddressVO ip = _entityMgr.findByIdIncludingRemoved(IPAddressVO.class, usageRecord.getUsageId().toString());
+            IPAddressVO ip = _entityMgr.findById(IPAddressVO.class, usageRecord.getUsageId().toString());
 			usageRecResponse.setUsageId(ip.getUuid());
 
 		} else if(usageRecord.getUsageType() == UsageTypes.NETWORK_BYTES_SENT || usageRecord.getUsageType() == UsageTypes.NETWORK_BYTES_RECEIVED){
@@ -3334,15 +3334,15 @@ public class ApiResponseHelper implements ResponseGenerator {
 			usageRecResponse.setType(usageRecord.getType());
 			if(usageRecord.getType().equals("DomainRouter")){
 				//Domain Router Id
-				VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getUsageId().toString());
+                VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, usageRecord.getUsageId().toString());
 				usageRecResponse.setUsageId(vm.getUuid());
 			} else {
 				//External Device Host Id
-				HostVO host = _entityMgr.findByIdIncludingRemoved(HostVO.class, usageRecord.getUsageId().toString());
+                HostVO host = _entityMgr.findById(HostVO.class, usageRecord.getUsageId().toString());
 				usageRecResponse.setUsageId(host.getUuid());
 			}
 			//Network ID
-			NetworkVO network = _entityMgr.findByIdIncludingRemoved(NetworkVO.class, usageRecord.getNetworkId().toString());
+            NetworkVO network = _entityMgr.findById(NetworkVO.class, usageRecord.getNetworkId().toString());
 			usageRecResponse.setNetworkId(network.getUuid());
 
         } else if(usageRecord.getUsageType() == UsageTypes.VM_DISK_IO_READ || usageRecord.getUsageType() == UsageTypes.VM_DISK_IO_WRITE ||
@@ -3350,27 +3350,27 @@ public class ApiResponseHelper implements ResponseGenerator {
             //Device Type
             usageRecResponse.setType(usageRecord.getType());
             //VM Instance Id
-            VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getVmInstanceId().toString());
+            VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, usageRecord.getVmInstanceId().toString());
             usageRecResponse.setVirtualMachineId(vm.getUuid());
             //Volume ID
-            VolumeVO volume = _entityMgr.findByIdIncludingRemoved(VolumeVO.class, usageRecord.getUsageId().toString());
+            VolumeVO volume = _entityMgr.findById(VolumeVO.class, usageRecord.getUsageId().toString());
             usageRecResponse.setUsageId(volume.getUuid());
 
 		} else if(usageRecord.getUsageType() == UsageTypes.VOLUME){
 			//Volume ID
-			VolumeVO volume = _entityMgr.findByIdIncludingRemoved(VolumeVO.class, usageRecord.getUsageId().toString());
+            VolumeVO volume = _entityMgr.findById(VolumeVO.class, usageRecord.getUsageId().toString());
 			usageRecResponse.setUsageId(volume.getUuid());
 			//Volume Size
 			usageRecResponse.setSize(usageRecord.getSize());
 			//Disk Offering Id
 			if(usageRecord.getOfferingId() != null){
-				DiskOfferingVO diskOff = _entityMgr.findByIdIncludingRemoved(DiskOfferingVO.class, usageRecord.getOfferingId().toString());
+                DiskOfferingVO diskOff = _entityMgr.findById(DiskOfferingVO.class, usageRecord.getOfferingId().toString());
 				usageRecResponse.setOfferingId(diskOff.getUuid());
 			}
 
 		} else if(usageRecord.getUsageType() == UsageTypes.TEMPLATE || usageRecord.getUsageType() == UsageTypes.ISO){
 			//Template/ISO ID
-			VMTemplateVO tmpl = _entityMgr.findByIdIncludingRemoved(VMTemplateVO.class, usageRecord.getUsageId().toString());
+            VMTemplateVO tmpl = _entityMgr.findById(VMTemplateVO.class, usageRecord.getUsageId().toString());
 			usageRecResponse.setUsageId(tmpl.getUuid());
 			//Template/ISO Size
 			usageRecResponse.setSize(usageRecord.getSize());
@@ -3382,35 +3382,35 @@ public class ApiResponseHelper implements ResponseGenerator {
 
 		} else if(usageRecord.getUsageType() == UsageTypes.SNAPSHOT){
 			//Snapshot ID
-			SnapshotVO snap = _entityMgr.findByIdIncludingRemoved(SnapshotVO.class, usageRecord.getUsageId().toString());
+            SnapshotVO snap = _entityMgr.findById(SnapshotVO.class, usageRecord.getUsageId().toString());
 			usageRecResponse.setUsageId(snap.getUuid());
 			//Snapshot Size
 			usageRecResponse.setSize(usageRecord.getSize());
 
 		} else if(usageRecord.getUsageType() == UsageTypes.LOAD_BALANCER_POLICY){
 			//Load Balancer Policy ID
-            LoadBalancerVO lb = _entityMgr.findByIdIncludingRemoved(LoadBalancerVO.class, usageRecord.getUsageId().toString());
+            LoadBalancerVO lb = _entityMgr.findById(LoadBalancerVO.class, usageRecord.getUsageId().toString());
             usageRecResponse.setUsageId(lb.getUuid());
 		} else if(usageRecord.getUsageType() == UsageTypes.PORT_FORWARDING_RULE){
 			//Port Forwarding Rule ID
-            PortForwardingRuleVO pf = _entityMgr.findByIdIncludingRemoved(PortForwardingRuleVO.class, usageRecord.getUsageId().toString());
+            PortForwardingRuleVO pf = _entityMgr.findById(PortForwardingRuleVO.class, usageRecord.getUsageId().toString());
             usageRecResponse.setUsageId(pf.getUuid());
 
 		} else if(usageRecord.getUsageType() == UsageTypes.NETWORK_OFFERING){
 			//Network Offering Id
-			NetworkOfferingVO netOff = _entityMgr.findByIdIncludingRemoved(NetworkOfferingVO.class, usageRecord.getOfferingId().toString());
+            NetworkOfferingVO netOff = _entityMgr.findById(NetworkOfferingVO.class, usageRecord.getOfferingId().toString());
 			usageRecResponse.setOfferingId(netOff.getUuid());
 			//is Default
 			usageRecResponse.setDefault((usageRecord.getUsageId() == 1)? true:false);
 
 		} else if(usageRecord.getUsageType() == UsageTypes.VPN_USERS){
 			//VPN User ID
-            VpnUserVO vpnUser = _entityMgr.findByIdIncludingRemoved(VpnUserVO.class, usageRecord.getUsageId().toString());
+            VpnUserVO vpnUser = _entityMgr.findById(VpnUserVO.class, usageRecord.getUsageId().toString());
             usageRecResponse.setUsageId(vpnUser.getUuid());
 
 		} else if(usageRecord.getUsageType() == UsageTypes.SECURITY_GROUP){
 			//Security Group Id
-			SecurityGroupVO sg = _entityMgr.findByIdIncludingRemoved(SecurityGroupVO.class, usageRecord.getUsageId().toString());
+            SecurityGroupVO sg = _entityMgr.findById(SecurityGroupVO.class, usageRecord.getUsageId().toString());
 			usageRecResponse.setUsageId(sg.getUuid());
 		}
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/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
deleted file mode 100644
index 14ea2bf..0000000
--- a/server/src/com/cloud/dao/EntityManagerImpl.java
+++ /dev/null
@@ -1,150 +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.dao;
-
-import java.io.Serializable;
-import java.util.List;
-import java.util.Map;
-
-import javax.ejb.Local;
-import javax.naming.ConfigurationException;
-
-import org.springframework.stereotype.Component;
-
-import net.sf.ehcache.Cache;
-
-import com.cloud.utils.component.ManagerBase;
-import com.cloud.utils.db.EntityManager;
-import com.cloud.utils.db.GenericDao;
-import com.cloud.utils.db.GenericDaoBase;
-import com.cloud.utils.db.GenericSearchBuilder;
-import com.cloud.utils.db.SearchBuilder;
-import com.cloud.utils.db.SearchCriteria;
-
-@Component
-@Local(value=EntityManager.class)
-@SuppressWarnings("unchecked")
-public class EntityManagerImpl extends ManagerBase implements EntityManager {
-    String _name;
-    Cache _cache;
-
-    @Override
-    public <T, K extends Serializable> T findById(Class<T> entityType, K id) {
-        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) {
-        // Finds and returns a unique VO using uuid, null if entity not found in db
-        GenericDao<? extends T, String> dao = (GenericDao<? extends T, String>)GenericDaoBase.getDao(entityType);
-        return dao.findByUuid(uuid);
-    }
-
-    @Override
-    public <T> T findByUuidIncludingRemoved(Class<T> entityType, String uuid) {
-        // Finds and returns a unique VO using uuid, null if entity not found in db
-        GenericDao<? extends T, String> dao = (GenericDao<? extends T, String>)GenericDaoBase.getDao(entityType);
-        return dao.findByUuidIncludingRemoved(uuid);
-    }
-
-    @Override
-    public <T> T findByXId(Class<T> entityType, String xid) {
-        return null;
-    }
-
-    @Override
-    public <T> List<? extends T> list(Class<T> entityType) {
-        GenericDao<? extends T, ? extends Serializable> dao = GenericDaoBase.getDao(entityType);
-        return dao.listAll();
-    }
-
-    @Override
-    public <T> T persist(T t) {
-        GenericDao<T, ? extends Serializable> dao = (GenericDao<T, ? extends Serializable>)GenericDaoBase.getDao((Class<T>)t.getClass());
-        return dao.persist(t);
-    }
-
-    @Override
-    public <T> SearchBuilder<T> createSearchBuilder(Class<T> entityType) {
-        GenericDao<T, ? extends Serializable> dao = (GenericDao<T, ? extends Serializable>)GenericDaoBase.getDao(entityType);
-        return dao.createSearchBuilder();
-    }
-
-    @Override
-    public <T, K> GenericSearchBuilder<T, K> createGenericSearchBuilder(Class<T> entityType, Class<K> resultType) {
-        GenericDao<T, ? extends Serializable> dao = (GenericDao<T, ? extends Serializable>)GenericDaoBase.getDao(entityType);
-        return dao.createSearchBuilder((Class<K>)resultType.getClass());
-    }
-
-    @Override
-    public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
-        _name = name;
-        /*
-        String threadId = Long.toString(Thread.currentThread().getId());
-
-        CacheManager cm = CacheManager.create();
-
-        _cache = cm.getCache(threadId);
-
-        if (_cache == null) {
-            int maxElements = NumbersUtil.parseInt((String)params.get("cache.size"), 100);
-            int live = NumbersUtil.parseInt((String)params.get("cache.time.to.live"), 300);
-            int idle = NumbersUtil.parseInt((String)params.get("cache.time.to.idle"), 300);
-
-            _cache = new Cache(threadId, maxElements, false, live == -1, live == -1 ? Integer.MAX_VALUE : live, idle);
-            cm.addCache(_cache);
-
-        }*/
-        
-        return true;
-    } 
-
-    @Override
-    public boolean start() {
-        return true;
-    }
-
-    @Override
-    public boolean stop() {
-        return true;
-    }
-
-    @Override
-    public String getName() {
-        return _name;
-    }
-
-    @Override
-    public <T, K> List<K> search(Class<T> entityType, SearchCriteria<K> sc) {
-        GenericDao<T, ? extends Serializable> dao = (GenericDao<T, ? extends Serializable>)GenericDaoBase.getDao(entityType);
-        return dao.customSearch(sc, null);
-    }
-
-    @Override
-    public <T, K extends Serializable> void remove(Class<T> entityType, K id) {
-        GenericDao<T, K> dao = (GenericDao<T, K>)GenericDaoBase.getDao(entityType);
-        dao.remove(id);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/usage/pom.xml
----------------------------------------------------------------------
diff --git a/usage/pom.xml b/usage/pom.xml
index af08f53..2051d5e 100644
--- a/usage/pom.xml
+++ b/usage/pom.xml
@@ -28,7 +28,7 @@
   <dependencies>
     <dependency>
       <groupId>org.apache.cloudstack</groupId>
-      <artifactId>cloud-utils</artifactId>
+      <artifactId>cloud-api</artifactId>
       <version>${project.version}</version>
       <type>test-jar</type>
       <scope>test</scope>      

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/utils/pom.xml
----------------------------------------------------------------------
diff --git a/utils/pom.xml b/utils/pom.xml
index e8aa805..686afdd 100644
--- a/utils/pom.xml
+++ b/utils/pom.xml
@@ -83,11 +83,6 @@
       <version>${cs.jsch.version}</version>
     </dependency>
     <dependency>
-      <groupId>org.eclipse.persistence</groupId>
-      <artifactId>javax.persistence</artifactId>
-      <version>${cs.jpa.version}</version>
-    </dependency>
-    <dependency>
       <groupId>org.jasypt</groupId>
       <artifactId>jasypt</artifactId>
       <version>${cs.jasypt.version}</version>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f5e5b39c/utils/src/com/cloud/utils/AnnotationHelper.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/AnnotationHelper.java b/utils/src/com/cloud/utils/AnnotationHelper.java
deleted file mode 100755
index e7a6166..0000000
--- a/utils/src/com/cloud/utils/AnnotationHelper.java
+++ /dev/null
@@ -1,57 +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
-// 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.utils;
-
-import javax.persistence.Table;
-
-import org.apache.log4j.Logger;
-
-
-public class AnnotationHelper extends Object {
-	// This class contains routines to help query annotation elements of objects.
-
-	public static final Logger s_logger = Logger.getLogger(AnnotationHelper.class.getName());
-
-	public static String getTableName(Object proxyObj) {
-		// The cglib class is generated by cglib during runtime.
-
-		Class<?> curClass = proxyObj.getClass();
-		if (curClass == null) {
-            s_logger.trace("Could not retrieve class information for proxy object");
-			return null;
-		}
-
-		while (curClass.getSuperclass() != null && curClass.getSuperclass().getName() != "java.lang.Object") {
-			curClass = curClass.getSuperclass();
-		}
-		// At this point, curClass is the root base class of proxyObj's class, and curClass is not java.lang.Object.
-
-		Table tabObj = curClass.getAnnotation(Table.class);
-
-		if (tabObj == null) {
-            s_logger.trace(curClass + "does not have a Table annotation");
-			return null;
-		}
-
-		return tabObj.name();
-	}
-
-}
-
-
-
-